Distributed Locks & Unique IDs
Coordinate mutually exclusive jobs safely with fencing tokens and generate sortable 64-bit IDs at scale.
In plain words
A distributed lock makes sure only one server does a task at a time, like a single key to a shared room. Unique ID generators give every record a number no other server will ever reuse.
Think of it like…
A fencing token is a numbered ticket stamped on every lock checkout: the vault rejects anyone holding yesterday’s expired ticket number even if they swear they still hold the key.
Where you’ve seen it
Twitter’s Snowflake IDs combine a timestamp, a machine number, and a counter, so thousands of servers can create tweet IDs without talking to each other.
Words you’ll hear
- Lock lease
- A lock that expires automatically if the holder crashes.
- Fencing token
- An increasing number that stops an old, expired lock holder from writing.
- Snowflake ID
- A 64-bit ID made from time + machine ID + sequence.
- UUID
- A random 128-bit ID that is practically never duplicated.
Visual diagram
Theory & deep dive
Distributed Locks: Leases + Fencing Tokens
A naive lock without an expiry TTL deadlocks forever if the holder crashes. Adding a lease TTL fixes crashed holders, but introduces a subtle bug: if Worker A freezes during a long garbage-collection pause, its lease expires, Worker B gets the lock, and then Worker A wakes up and overwrites Worker B’s work!
The true fix is a fencing token: an ever-increasing number (33, 34, 35...) handed out with each lock. The database checks incoming_token >= last_seen_token and rejects stale zombies.
Unique IDs at Scale: Why Auto-Increment Breaks
A single SQL AUTO_INCREMENT column breaks as soon as you shard across multiple databases or need IDs generated without hitting one central bottleneck. Snowflake IDs solve this cleanly in 64 bits: [41 bits timestamp | 10 bits machine ID | 12 bits sequence] - fitting inside a standard SQL BIGINT, sortable by creation time, and generating 4,096 IDs per millisecond per worker with zero coordination!
How it works, step by step
Step 1 of 41. Acquire lock with a bounded Lease TTL
Always attach a TTL/lease so if a worker crashes mid-task, the lock automatically releases instead of deadlocking the system forever.
- Lease TTL
- e.g. 10–30s
- Renew
- Background heartbeat
When to use it & trade-offs
What it is
Distributed locks coordinate mutual exclusion across servers using time-bounded leases and fencing tokens, while distributed ID generators (like Snowflake) mint unique, roughly time-sorted 64-bit IDs with zero central DB bottleneck.
Why it matters: Naive locks fail when a paused worker wakes up after its lock expires; naive auto-increment DB IDs become a single-point write bottleneck.
When to reach for it
- Fencing tokens on leader election, cron job locking, and inventory leases
- Snowflake or UUIDv7 for primary keys in sharded SQL/NoSQL tables
- DB-allocated ID blocks (ticket server caching 1,000 IDs in RAM) for simple setups
When to avoid or be careful
- Using Redis
SET NX EXalone for strict correctness without fencing tokens (if a GC pause outlives EX, two workers write concurrently) - Using single-DB
AUTO_INCREMENTas a shared ID generator across 64 database shards
Unique ID Generation Strategies
Strengths: Zero central coordination; negligible collision risk.
Watch out: 128-bit size and random order cause severe B-Tree page fragmentation at scale.
Strengths: Fits in 64-bit integer, roughly time-sorted, zero cross-node sync per ID.
Watch out: Requires assigning unique worker IDs and handling NTP backward clock jumps.
Strengths: 48-bit millisecond timestamp prefix + randomness; no worker registry needed.
Watch out: Twice as wide as 64-bit Snowflake IDs (16 bytes vs. 8 bytes).
Interview signals & numbers to know
When this topic comes up
- unique ID generator
- 64-bit sortable ID
- distributed lock
- prevent duplicate cron
- clock skew
Benchmarks & rules of thumb
- Snowflake 41-bit ms span
- ~69 years
- Snowflake 12-bit seq/ms
- 4,096 IDs/ms per node
- UUIDv4 bits
- 128 bits (122 random)
- Typical lock lease
- 10–30 seconds
Common mistakes & follow-ups
Common interview mistakes
- Thinking a Redis TTL lock guarantees mutual exclusion when a client pauses longer than the TTL
- Using
AUTO_INCREMENTon sharded tables without step offsets or Snowflake IDs - Ignoring NTP clock stepping backward in Snowflake generators
Likely interviewer follow-ups
- Walk through the exact failure scenario where two workers both think they hold a Redis lock, and how fencing tokens prevent data corruption.
- Why does Snowflake use 41 bits for timestamps and 12 bits for sequences?
- What happens if NTP moves the system clock backward by 50 ms on a Snowflake worker?
Knowledge check
Put it into practice
Design full architectures with AI feedback
Apply Distributed Locks & Unique IDs inside real High-Level Design prompts or review Q&A flashcards.