Designing a Distributed Unique ID Generator
Difficulty: Beginner · Prerequisites: Back-of-Envelope Estimation Asked at: Twitter, Discord, Instagram, Amazon, Flipkart
TL;DR
Every distributed system needs unique IDs - for users, orders, messages, posts. A single auto-increment DB column breaks at scale. This design explores 4 approaches: UUID, database sequences, Snowflake IDs, and range-based allocation.
💡 A UUID (universally unique identifier) is a 128-bit value generated from randomness - big enough that two machines choosing independently will in practice never pick the same one. That is the baseline every other approach here is trading against. Learn more →
flowchart LR
SVC["Any Service<br/>needs an ID"]
IDG["ID Generator"]
DB[("Optional DB<br/>for coordination")]
SVC -->|"1. Request ID"| IDG
IDG -->|"2. Reserve ID range"| DB
In 2 sentences: Generate globally unique, roughly time-sorted, 64-bit IDs without a single point of failure. Twitter’s Snowflake approach (timestamp + machine ID + sequence) is the industry standard for most use cases.
Understanding the Problem
Almost every system needs unique identifiers. User IDs, order IDs, message IDs, transaction IDs - they must be globally unique across all servers, ideally sortable by creation time, and generated with extremely low latency (< 1ms). The challenge is generating these at scale (10K-100K IDs/sec) across multiple machines without coordination or collisions.
Naive First Cut
flowchart LR
S1["Server 1"]
S2["Server 2"]
DB[("Single DB<br/>AUTO_INCREMENT")]
S1 --> DB
S2 --> DB
Just use AUTO_INCREMENT in a single MySQL/Postgres table.
Why this breaks:
- Single point of failure - if the DB goes down, no service can generate IDs
- Bottleneck - all ID generation is serialized through one DB
- Can’t scale horizontally - adding more app servers doesn’t help, the DB is the limit
- Sequential and guessable - exposes total count, easy to scrape
- Cross-datacenter latency - if services are in multiple regions, every ID requires a round-trip to one DB
💡 Distance sets a floor on latency that no faster database removes: a round trip between continents is 150-250ms. If generating an id has to cross one, the id costs a thousand times more than the work it precedes.
The rest of the doc explores 4 production-ready alternatives.
Prior Art We’re Drawing From
- Twitter Snowflake - The original distributed ID generator. 64-bit IDs composed of timestamp + datacenter + machine + sequence. Open-sourced in 2010, now the de facto standard. (Twitter Engineering Blog)
- Instagram Sharded IDs - Modified Snowflake using Postgres schemas to embed shard information into IDs. Generates IDs at the DB layer without a separate service. (Instagram Engineering)
- Discord Snowflakes - Twitter Snowflake adapted for Discord with epoch starting at Discord’s launch date. Used for messages, users, channels. (Discord Developer Docs)
- MongoDB ObjectId - 12-byte ID with timestamp + random + counter. No central coordination needed. Demonstrates the random + counter hybrid approach. (MongoDB Docs)
Functional Requirements
Core
- Generate globally unique IDs - no two IDs should ever collide across all services and servers
- IDs must be 64-bit numeric - fits in a long/bigint, can be used as primary keys and sorted efficiently
- Roughly time-ordered - IDs generated later should be larger than IDs generated earlier (enables range queries and chronological sorting)
Below the Line
- Human-readable (short URLs, display-friendly)
- Cryptographically unpredictable
- Embeddable shard/partition information
- Custom epoch support
Non-Functional Requirements
| NFR (non-functional requirement) | Target |
|---|---|
| Throughput | 10K-100K IDs/sec per node |
| Latency | < 1ms per ID generation |
| Availability | 99.999% - ID generation cannot be a single point of failure |
| Uniqueness | Zero collisions, ever, across all nodes |
Core Entities
- ID - the 64-bit unique identifier itself
- Node - a machine/process that generates IDs (identified by a machine ID)
- Timestamp - millisecond-precision time component within the ID
- Sequence - per-node counter that resets each millisecond
Technology Choices
| Tier | Purpose | Primary Pick | Alternatives | Why Primary Wins Here |
|---|---|---|---|---|
| ID Algorithm | Core ID generation logic | Snowflake (timestamp + machine + seq) | UUIDv7, Sonyflake, ULID, DB range allocation | 64-bit, time-sorted, no coordination, 10K+ IDs/ms per node |
| Coordination | Machine ID assignment | ZooKeeper | etcd, Consul, Kubernetes lease | Guarantees unique machine IDs across fleet; fast failover |
| Timestamp Source | Clock accuracy | NTP-synced system clock | GPS clock, PTP, Atomic clock | Good enough for ms precision; GPS/atomic only needed for sub-us |
💡 Three rows, three things to know. UUIDv7 and ULID (Universally Unique Lexicographically Sortable Identifier) are newer identifier formats that put the timestamp first so the values sort by creation time, and Sonyflake is a Snowflake variant with a different split of the 64 bits. ZooKeeper and etcd are small, strongly consistent stores whose job is to let a fleet of machines agree on facts like “who holds machine ID 7” - they are trusted here for exactly the one decision per startup that must never be wrong twice, and this is what leader election and distributed locking are built on. NTP (Network Time Protocol) keeps a machine’s clock roughly right over the internet, to within milliseconds; GPS (Global Positioning System) receivers and PTP (Precision Time Protocol) do far better at far greater cost, and “sub-us” means sub-microsecond accuracy this design does not need.
| Backup/Range Store | Fallback ID ranges when Snowflake unavailable | Postgres | MySQL, DynamoDB, etcd | Simple atomic range allocation with SELECT ... FOR UPDATE |
Why Snowflake over UUID? UUIDs are 128-bit (wastes index space) and not sortable by time. Snowflake gives 64-bit IDs that fit in a database bigint, sort chronologically, and encode the generating machine — all without network round-trips for each ID.
Data Modeling
In-Memory (Snowflake ID Structure — 64-bit layout):
Bit layout: [1 unused] [41 bits timestamp] [10 bits machine_id] [12 bits sequence]
~69 years of ms 1024 machines 4096 IDs per ms
Example ID: 6820374963445760001
Binary: 0|10111101001010011001010100111000010|0000000001|000000000001
|<---- 41-bit timestamp ---->|<-machine->|<--sequence-->|
ZooKeeper / etcd (Coordination — machine ID assignment):
Path: /snowflake/machines/{machine_id} → { hostname, lease_expiry, last_heartbeat }
Ephemeral node: auto-deleted if machine disconnects (ID becomes available for reassignment)
Max machines: 1024 (10-bit machine_id field)
Postgres (Backup/Range Store — fallback ID ranges):
CREATE TABLE id_ranges (
range_id SERIAL PRIMARY KEY,
machine_id INTEGER NOT NULL,
start_value BIGINT NOT NULL,
end_value BIGINT NOT NULL,
allocated_at TIMESTAMP NOT NULL,
exhausted_at TIMESTAMP
);
-- Used only when Snowflake is unavailable (failover to range-based allocation)
Access Patterns:
| Query | Data Source | How |
|---|---|---|
| Generate next ID | In-memory (per process) | Combine current_ms + machine_id + atomic_increment(sequence) — no network call |
| Assign machine ID on startup | ZooKeeper | Create ephemeral node at /snowflake/machines/{id} — CAS ensures uniqueness |
| Handle clock skew | In-memory | If current_ms < last_ms: wait until clock catches up (reject requests for 1-5ms) |
| Allocate fallback range | Postgres | SELECT start_value, end_value FROM id_ranges WHERE machine_id = ? FOR UPDATE |
💡 Three terms from this table. An ephemeral node in ZooKeeper exists only while that machine’s session is alive, so a crashed machine automatically gives its ID back. CAS is compare-and-set: write this value only if it still holds the value I last read, which is how two machines racing for the same ID produce one winner. Clock skew is two machines’ clocks disagreeing, or one machine’s clock jumping - including backwards, which is the case this row is defending against. And FOR UPDATE locks the row so only one allocator can claim a range at a time. Learn more →
How 4096 IDs/ms Is Guaranteed Without Collision:
- Machine 7 needs a new ID at timestamp T=1720000000123ms
- Concatenate:
(T - epoch) << 22 | (machine_id << 12) | sequence_counter
💡 Reading the shifts:<< Nmoves a value left by N bits, making room for the N bits of every field to its right. The sequence occupies the lowest 12 bits, machine_id the next 10, so the timestamp is pushed up by 22 - and because the timestamp ends up in the highest bits, comparing two IDs as plain integers compares their creation times. - sequence_counter starts at 0 for each new millisecond, increments atomically per ID generated
- If sequence hits 4096 in the same ms (extremely rare): busy-wait until next millisecond, reset sequence to 0
💡 Busy-waiting means looping until the clock advances rather than sleeping - wasteful in general, but here it can only ever last under a millisecond, which is cheaper than the bookkeeping needed to avoid it. - Two machines generating simultaneously: different machine_id bits guarantee no collision even with identical timestamps
- Clock drift protection: if
current_ms < last_generated_ms(clock went backward due to NTP): reject/wait — never generate an ID with a past timestamp
The 4 Approaches
Approach 1: UUID
550e8400-e29b-41d4-a716-446655440000
128-bit random identifier. No coordination needed - any server can generate one independently.
| Pros | Cons |
|---|---|
| Zero coordination | 128 bits (too large for primary key, bad index performance) |
| Any node generates independently | Not sortable by time |
| Zero collisions (practically) | Not human-friendly |
| Simple to implement | Fragmented B-tree indexes (random order) |
💡 Database indexes are B-trees (balanced search trees: a shallow, sorted, on-disk structure). Inserting keys in random order scatters writes across the whole tree and keeps pulling cold pages into memory, while inserting in increasing order keeps appending to the same place - which is the real cost of a random UUID as a primary key. Learn more →
Verdict: Use for cases where time-ordering doesn’t matter and you don’t need compact IDs (e.g., idempotency keys, distributed trace IDs).
Approach 2: Database Ticket Server
Two (or more) databases that hand out IDs from disjoint ranges.
flowchart LR
SVC["Service"]
DB1["Ticket Server 1<br/>IDs: 1 3 5 7 ..."]
DB2["Ticket Server 2<br/>IDs: 2 4 6 8 ..."]
SVC -->|"1. Get odd ID"| DB1
SVC -->|"2. Get even ID"| DB2
Server 1 increments by 2 starting at 1. Server 2 increments by 2 starting at 2. No collisions.
| Pros | Cons |
|---|---|
| Simple to understand | Still requires DB round-trip per ID |
| Numeric, sortable | Adding a 3rd server requires changing the step (breaks existing pattern) |
| Flickr used this at scale | Not truly time-ordered across servers |
Verdict: Works for small-medium scale. Flickr used this pattern. But inflexible when adding/removing nodes.
Approach 3: Snowflake (Industry Standard)
A 64-bit ID composed of multiple fields packed into a single long integer.
| 1 bit unused | 41 bits timestamp | 5 bits datacenter | 5 bits machine | 12 bits sequence |
flowchart LR
subgraph "64-bit Snowflake ID"
A["0"]
B["41 bits<br/>timestamp ms"]
C["5 bits<br/>datacenter"]
D["5 bits<br/>machine"]
E["12 bits<br/>sequence"]
end
💡 Unlike every other diagram here, this one has no arrows on purpose - it is a picture of one 64-bit number laid out left to right, not a flow between components. Read the five boxes as five adjacent slices of the same integer.
How it works:
- 41 bits for timestamp - milliseconds since a custom epoch (e.g., Twitter uses Nov 4, 2010). Gives ~69 years of IDs before overflow.
- 5 bits datacenter ID - supports 32 datacenters
- 5 bits machine ID - supports 32 machines per datacenter (1024 total nodes)
💡 This is the same ten bits the Data Modeling section callsmachine_id, just split into 5 for the datacenter and 5 for the machine within it. 32 × 32 = 1024 either way, which is why both layouts give the same fleet ceiling. - 12 bits sequence - counter per millisecond per machine. Supports 4096 IDs/ms/machine = 4 million IDs/sec per machine
Why this is great:
- No coordination - each machine generates independently using its own machine ID
- Time-sorted - IDs increase over time (timestamp is the most significant bits)
- 64-bit - fits in a bigint, great index performance
- High throughput - 4M IDs/sec per node without any network calls
- Unique - machine ID + sequence guarantees no collision within the same millisecond
| Pros | Cons |
|---|---|
| No coordination at runtime | Requires machine ID assignment (one-time setup via ZooKeeper or config) |
| Time-sorted | Clock skew between machines can cause non-monotonic ordering |
💡 Monotonic means never going backwards - here, that a later ID is always numerically larger than an earlier one. Because the timestamp sits in the high bits, a machine whose clock is a second behind its neighbour mints IDs that sort before theirs, so “sorted by ID” stops meaning “sorted by time” across machines. | 64-bit, compact | 69-year lifespan (enough for most systems) | | 4M IDs/sec/node | Need NTP sync to prevent clock drift |
Clock skew handling: If the system clock moves backward (NTP correction), either wait until the clock catches up, or refuse to generate IDs until the clock advances past the last timestamp used. Twitter’s Snowflake logs an error and waits.
Approach 4: Range-Based Allocation
A central service pre-allocates ID ranges to application servers. Each server generates IDs from its range without further coordination.
flowchart LR
ALLOC["Range Allocator<br/>central service"]
S1["Server 1<br/>range: 1-1000"]
S2["Server 2<br/>range: 1001-2000"]
S3["Server 3<br/>range: 2001-3000"]
ALLOC -->|"1. Assign range 1-1000"| S1
ALLOC -->|"2. Assign range 1001-2000"| S2
ALLOC -->|"3. Assign range 2001-3000"| S3
How it works:
- Central allocator (backed by a DB) hands out ranges of 1000 or 10000 IDs at a time
- Each app server increments locally within its range - zero network calls per ID
- When a range is exhausted, fetch a new range from the allocator
- If a server crashes mid-range, those unused IDs are simply wasted (acceptable)
| Pros | Cons |
|---|---|
| Very fast (local increment) | IDs not time-sorted across servers |
| Simple implementation | Wasted IDs on server crash |
| Central allocator is low-QPS (called rarely) | Allocator is still a SPOF (mitigate with replicas) |
| Used by Google Spanner | Not as compact as Snowflake |
💡 A SPOF is a single point of failure: one component whose loss stops everything. QPS is queries per second, and “low-QPS” is the whole argument for this design - the allocator is called once per million IDs, so one instance with replicas is enough. Spanner is Google’s globally distributed SQL database. Learn more →
Comparison Table
| Approach | Bits | Time-sorted | Coordination | Throughput/node | Best for |
|---|---|---|---|---|---|
| UUID | 128 | ❌ | None | Unlimited | Trace IDs, idempotency keys |
| Ticket Server | 64 | Partial | DB per ID | ~10K/sec | Small-medium scale |
| Snowflake | 64 | ✅ | None at runtime | 4M/sec | Most use cases |
| Range Allocation | 64 | ❌ (within node only) | Rare (per range) | Unlimited | Sharded DBs, Google Spanner |
Recommended: Snowflake Implementation
For most interview answers, Snowflake is the go-to. Here’s the generation flow:
sequenceDiagram
participant App as Application
participant Gen as ID Generator (local)
participant Clock as System Clock
App->>Gen: generateId()
Gen->>Clock: currentTimeMillis()
Clock-->>Gen: timestamp
Gen->>Gen: check if same ms as last ID
alt Same millisecond
Gen->>Gen: increment sequence
else New millisecond
Gen->>Gen: reset sequence to 0
end
Gen->>Gen: compose: timestamp | datacenter | machine | sequence
Gen-->>App: 64-bit unique ID
No network calls. No DB lookups. Pure local computation.
What this leaves open. That flow is the whole hot path and it is genuinely free — a few bit shifts per ID. What it does not say is where any of its inputs come from, and all three gaps are correctness problems rather than performance ones:
machineis read as if it already exists. The uniqueness of every ID rests on no two live generators sharing that value, and nothing here says who assigns it. That is Deep Dive 1.- The clock is trusted to move forward. The flow compares against the last millisecond to decide whether to reset the sequence, which handles the clock advancing. It has no branch for the clock going backward, and clocks do. That is Deep Dive 2.
- The bit layout is fixed at 64 bits. 41 for the timestamp, 10 for the machine, 12 for the sequence — that is 4,096 IDs per millisecond per machine, and the ceiling is arithmetic rather than a tuning parameter. That is Deep Dive 3.
Deep Dives
1) Every ID’s uniqueness rests on the machine ID. Who hands those out?
Problem: Each node needs a unique machine ID (10 bits = 1024 possible). How do you assign these without collisions? If two machines accidentally get the same ID, they’ll generate duplicate IDs.
In simple terms: Before a machine can start generating IDs, it needs a name tag (its machine ID). We need to make sure no two machines wear the same name tag.
Bad: the generation flow reads machine without ever saying where it came from, so the obvious answer is to hardcode it in config files. “Server A = machine 1, Server B = machine 2.” Error-prone — someone deploys a new server and forgets to update the config. Doesn’t work with auto-scaling (Kubernetes spinning up pods dynamically).
Good: Use ZooKeeper or etcd. Each node, on startup, connects to ZooKeeper and claims the next available sequential ID via an ephemeral node. If the node crashes, ZooKeeper detects the missing heartbeat and releases the ID for reuse.
💡 A heartbeat is a small periodic “still here” message. “Ephemeral” means the node exists only while those heartbeats continue, and “sequential” means ZooKeeper appends a unique increasing number to the name - which is how the machine learns which ID it got. Learn more →
How it works step by step:
- Node starts up → connects to ZooKeeper
- Creates an ephemeral sequential node:
/id-generators/machine-0007 - Reads its sequence number (7) → that’s its machine ID
- If the node crashes, ZooKeeper auto-deletes the ephemeral node
- Next node to start gets the recycled ID
Great: Use the network interface MAC address or container hostname hash to derive a machine ID. No external dependency at all.
💡 A MAC (media access control) address is the unique hardware identifier burned into a network card, so it is a value the machine already has and nobody has to hand out. Worth noting that % 1024 is the fragile part: modulo-based placement changes every mapping the moment the divisor changes, which is exactly the problem consistent hashing exists to avoid.
How it works:
- Take the machine’s MAC address (unique per network card):
AA:BB:CC:DD:EE:FF - Hash it:
hash("AA:BB:CC:DD:EE:FF") % 1024→ machine ID = 547 - On startup, register this ID in a shared store (Redis or DB) to verify no collision
- If collision detected (extremely rare) → fall back to random + retry
Trade-off: ZooKeeper approach is safer (guarantees uniqueness) but adds an external dependency. MAC-based is simpler but theoretically collision-possible (hash collisions). In practice, most companies use ZooKeeper/etcd because they already run it for other coordination tasks.
2) NTP can move the clock backward. What stops that from minting a duplicate?
Problem: NTP (the protocol that syncs your system clock with the internet) can adjust the clock backward. If timestamp decreases, two IDs could have the same timestamp + sequence = collision.
In simple terms: Imagine your clock shows 10:05, then suddenly jumps back to 10:03 (because NTP realized it was 2 minutes ahead). Now the ID generator thinks it’s 10:03 again and might generate the same IDs it made the first time at 10:03. Duplicate IDs.
Bad: ignore it, which is what the recommended flow does — it branches on “same millisecond as last” and “new millisecond” and has no third case for a timestamp that moved backward, so a rewound clock silently re-enters the first branch and replays sequence numbers it has already issued. Hope clocks are always correct. “NTP adjustments are rare.” True — but when it happens, you get duplicate IDs in your database, corrupt data, and a very bad day debugging.
Good: Detect backward clock movement. The generator tracks lastTimestamp (the timestamp it used for the most recent ID). Before generating a new ID, check: if currentTime < lastTimestamp → REFUSE to generate. Wait until the clock catches up.
How it works:
- Generator keeps
lastTimestamp = 10:05:00.123 - Next call:
currentTime = 10:04:59.900(clock went back!) - Generator detects: current < last → clock skew!
- Options: (a) spin-wait doing nothing until
currentTime >= lastTimestamp, or (b) throw an error and let the caller retry later
💡 Note what this is defending: if the clock jumps backwards and the machine keeps minting, it will re-issue timestamps it has already used and can hand out an ID it handed out before. Refusing to generate is the safe option precisely because uniqueness cannot be checked after the fact. - Once clock catches up, resume normal generation
Downside: During the wait, no IDs are generated. If the clock was adjusted back by 5 seconds, you have 5 seconds of downtime for that node.
Great: Use a logical clock component. Instead of waiting, “borrow from the future” by continuing to increment the sequence counter even though the timestamp hasn’t advanced. Eventually the real clock catches up and things normalize.
💡 A logical clock is a counter that only ever goes up, used in place of wall-clock time. It gives you a consistent order without needing the machines’ clocks to agree, which is the trade being made here. Learn more →
How it works:
- Clock goes back → keep using
lastTimestamp(the old, higher value) - Keep incrementing the sequence counter (normally resets each millisecond, but now it keeps growing)
- If sequence overflows (hits 4096) → then you must wait (no choice)
- In practice, a 1-2 second clock adjustment only “borrows” ~4096 sequences — well within limits
What Twitter’s Snowflake actually does: Logs an error to alert ops, then waits. They chose simplicity over cleverness — a few milliseconds of waiting is better than complex “borrowing” logic that’s hard to reason about.
3) 64 bits are all spent. Where do IDs come from past 4M a second?
Problem: One Snowflake node generates 4M IDs/sec (4096 per millisecond). What if you need 100M/sec? (e.g., a messaging platform generating IDs for every single message across billions of conversations)
In simple terms: One machine can make 4 million IDs per second. What if that’s not enough? How do you get 100 million per second?
Bad: widen the sequence field inside the same 64 bits the recommended layout already spends in full. 16 bits buys 65,536 per millisecond, and the bits have to come from somewhere: taking them from the timestamp cuts the 69-year lifespan to about 4 years, and taking them from the machine field cuts the fleet ceiling. Or steals from machine ID, reducing max nodes from 1024 to 64.
Good: Run multiple Snowflake instances. The bit layout already supports 1024 machines (10 bits for datacenter + machine). Deploy 25 machines × 4M/sec each = 100M/sec. Each machine has a unique ID, so no collisions.
How it works:
- Deploy 25 ID generator instances (each with a unique machine ID)
- Put them behind a load balancer
- Services request IDs from any instance (round-robin)
- Each instance generates 4M/sec independently
- Total throughput: 25 × 4M = 100M/sec
- Zero coordination between instances at runtime
Great: For extreme scale beyond 1024 machines, use the range-based approach as a hybrid. A central allocator hands out blocks of Snowflake machine IDs dynamically. Each “micro-generator” thread gets its own machine ID from the pool, generates IDs locally, and returns the machine ID when done.
💡 Leasing a machine ID per thread rather than per machine multiplies the per-millisecond ceiling, because each thread gets its own 4096-wide sequence. The cost is that returning an ID for reuse reintroduces the exact hazard Deep Dive 2 was about - a reused machine ID plus a rewound clock can re-issue IDs - so the pool has to be certain the previous holder has stopped.
When is this needed? In practice, almost never. Even Twitter at peak (~140K tweets/sec + internal IDs) only needed a handful of Snowflake nodes. The 4M/sec per node limit is extremely generous. Most companies never hit it.
Design Self-Audit
- Single points of failure? The machine-ID registry, and the design’s best property is how little it is used: a node consults ZooKeeper or etcd once at startup and never again, so a registry outage blocks new nodes from joining and does not stop a single ID from being minted. Deep Dive 1 is what buys that.
- Clock dependence? The sharpest risk on the page, and Deep Dive 2 is explicit about it: a backward clock step must stall generation rather than mint, because a duplicate ID is unrecoverable while a few milliseconds of unavailability is not.
- Hot partition / skew? Worth naming because it is a consequence rather than a flaw. These IDs are time-ordered, so any index built on them is written only at its right edge — every insert lands in the same B-tree page and the same shard if you range-partition on the ID. Both Cloud Spanner and DynamoDB document this as the thing not to do. If the ID is a primary key and writes must spread, hash-partition on it or prefix a shard key; keep the monotonic form where the ordering is what you want.
- Stale reads after writes? Not applicable. Generation is in-process with no shared read path, which is the whole reason this design can claim 4M IDs a second.
- Dead-letter / reconciliation? None. There is no asynchronous step to lose anything in, so there is nothing to reconcile.
- Cost at the hot tier? Negligible, and that is the point: an ID costs a few CPU instructions and no network call. The cost of this component is the operational attention the clock and the registry need, not infrastructure.
Core Flows
Flow 1 - A node starts and claims a machine ID
sequenceDiagram
autonumber
participant G as ID Generator node
participant Z as ZooKeeper or etcd
participant NTP as NTP
G->>Z: create ephemeral node for a free machine id
alt claim succeeded
Z-->>G: machine id 7 held by this session
else id already taken
G->>Z: try the next free id
Z-->>G: machine id 8 held by this session
end
G->>NTP: confirm clock is in sync
NTP-->>G: offset within tolerance
G->>G: begin serving ids
Note over G,Z: the session heartbeat is what keeps the claim
- The claim is an ephemeral node, so an ID is released automatically when the process dies. A crashed node does not strand its machine ID until somebody notices.
- This happens once, at startup. After it, the generator never talks to the registry again — which is the property the Design Self-Audit calls out, because it means a registry outage blocks new nodes and stops no IDs.
- Clock sanity is checked before serving rather than discovered later.
Failure worth calling out: if the registry session drops but the process survives — a network partition rather than a crash — the ephemeral node disappears and another node can claim the same machine ID while the original keeps minting. That is the one scenario that produces genuine duplicates, so losing the session has to stop generation, not just log a warning.
Flow 2 - Generating an ID
sequenceDiagram
autonumber
participant APP as Application
participant LB as Load Balancer
participant G as ID Generator
APP->>LB: next id
LB->>G: route to any node
G->>G: read current millisecond
alt same millisecond as last id
G->>G: increment sequence
else new millisecond
G->>G: reset sequence to zero
end
G-->>APP: 64 bit id
- No coordination at all on this path. The uniqueness comes from the machine ID claimed in Flow 1 plus the timestamp plus the sequence, so any node can answer without asking anyone.
- The load balancer can route anywhere, because nodes share nothing. That is what makes the tier horizontally scalable rather than merely replicated.
- The sequence is what covers multiple IDs inside one millisecond; when it overflows, the generator waits for the next millisecond rather than reusing a number.
Failure worth calling out: sequence exhaustion inside a single millisecond is a stall, not an error, and under sustained load it becomes the throughput ceiling for that node — the bits allocated to the sequence are a hard limit on IDs per millisecond. Deep Dive 3 is where that ceiling gets re-examined.
Flow 3 - The clock moves backwards
sequenceDiagram
autonumber
participant NTP as NTP
participant G as ID Generator
participant APP as Application
NTP->>G: time adjustment moves clock back
G->>G: current millisecond is behind last issued
G-->>APP: refuse and stall until the clock catches up
Note over G,APP: callers see latency rather than a duplicate
- The check is against the last timestamp this node actually issued, held in memory — not against any external notion of correct time.
- The response to going backwards is to wait. A few milliseconds of stall is recoverable; a duplicate ID written as a primary key is not.
- This is why the NTP client should be configured to slew rather than step, so the backward movement is gradual enough to never cross the threshold.
Failure worth calling out: a large backward jump — a VM resumed from a snapshot, say — stalls the node for as long as the jump. Stalling indefinitely is the safe behaviour and a terrible service, so the honest response is to refuse readiness and let the load balancer route elsewhere, rather than hold the caller’s request open.
Final Architecture
Bringing the recommended pieces together: a fleet of stateless Snowflake generators (embedded as a library in each app, or as a dedicated service behind a load balancer for the scaling case), machine IDs assigned on startup via ZooKeeper/etcd, and NTP keeping clocks in sync to bound skew.
Components in this picture:
- Load Balancer: spreads ID requests across the generator fleet. It only appears in the “dedicated service” variant - when the generator runs as a library inside each app, there is no network call and no balancer.
- ID Generator 1..N: stateless Snowflake generators. Stateless except for one thing that matters enormously: the machine ID each one claimed at startup, which is what makes its IDs distinct from its neighbours’.
- ZooKeeper (machine-ID registry): hands out and tracks machine IDs, one per generator, and reclaims an ID when its holder stops heartbeating (Deep Dive 1).
- NTP (Network Time Protocol) time sync: keeps every generator’s clock within milliseconds of real time. It is drawn as a component because the timestamp sits in the high bits of every ID, so clock accuracy is a correctness input, not an operational nicety (Deep Dive 2).
flowchart LR
APP["Application Services"]
LB["Load Balancer"]
G1["ID Generator 1<br/>Snowflake"]
G2["ID Generator 2<br/>Snowflake"]
GN["ID Generator N<br/>Snowflake"]
ZK[("ZooKeeper<br/>machine-ID registry")]
NTP["NTP time sync"]
APP -->|"Request unique ID"| LB
LB -->|"Route"| G1
LB -->|"Route"| G2
LB -->|"Route"| GN
G1 -->|"Claim machine ID"| ZK
G2 -->|"Claim machine ID"| ZK
GN -->|"Claim machine ID"| ZK
NTP -->|"Clock sync"| G1
NTP -->|"Clock sync"| G2
NTP -->|"Clock sync"| GN
Each generator produces IDs locally with zero runtime coordination (4M/sec/node); ZooKeeper is touched only once per node at startup for machine-ID assignment, and NTP prevents the clock skew that Deep Dive 2 addresses. Add nodes to scale past 4M/sec (Deep Dive 3).
How it works end-to-end:
- Application needs an ID — calls the ID Generator service (or embedded library) via Load Balancer
- Load Balancer routes — distributes requests across the fleet of Snowflake generators
- Generator produces ID locally — combines current timestamp (41 bits) + machine ID (10 bits) + sequence counter (12 bits) into a 64-bit ID with zero coordination
- Machine ID claimed at startup — each generator registers once with ZooKeeper/etcd to get a unique 10-bit machine ID
- NTP keeps clocks in sync — prevents clock skew from causing duplicate or out-of-order IDs across generators
- ID returned to caller — unique, time-sorted, globally unique identifier delivered in <1ms
Interview Cheat Sheet
| Question | Answer |
|---|---|
| “Why not UUID?” | 128 bits, not sortable, bad index performance. Use when time-ordering isn’t needed. |
| “Why not auto-increment?” | Single DB bottleneck, SPOF, can’t scale horizontally, sequential = guessable. |
| “What’s Snowflake?” | 64-bit ID = timestamp(41) + datacenter(5) + machine(5) + sequence(12). No coordination. 4M IDs/sec/node. |
| “How is uniqueness guaranteed?” | Unique machine ID ensures no two nodes produce the same bits. Sequence resets per millisecond per node. |
| “What about clock skew?” | Detect backward movement, wait until clock catches up. Or use logical clock. |
| “How to assign machine IDs?” | ZooKeeper, etcd, or derive from MAC/hostname hash with collision check. |
| “Is it truly globally unique?” | Yes - as long as machine IDs are unique and clocks don’t go backward without detection. |
What’s Expected at Each Level
Mid-level
Know that auto-increment doesn’t scale. Propose UUID or Snowflake. Explain the Snowflake bit layout and why 64-bit time-sorted IDs are preferred over 128-bit random UUIDs for database primary keys. Understand the trade-offs table.
Senior
Drive the discussion on clock skew handling, machine ID assignment strategies, and when to choose Snowflake vs range-based allocation. Discuss the index performance implications of random vs sequential IDs. Know that Twitter, Discord, and Instagram all use Snowflake variants.
Staff+
Discuss multi-region ID generation with region bits, capacity planning for the 69-year timestamp limit, and hybrid approaches for extreme throughput. Address the operational burden of ZooKeeper for machine ID assignment vs stateless alternatives. Cover how Snowflake IDs leak creation time (privacy concern for some products).
🎯 Key Takeaways
- Auto-increment is the naive solution - breaks at scale, SPOF, guessable
- Snowflake is the industry standard - 64-bit, time-sorted, no coordination, 4M IDs/sec/node
- UUID when ordering doesn’t matter - trace IDs, idempotency keys
- Range allocation for extreme scale - Google Spanner pattern, trades ordering for simplicity
- Clock skew is the main operational risk - detect and wait is the standard mitigation
Related Designs
- URL Shortener - uses Base62 ID generation for short links
- Pastebin - unique ID generation for paste URLs
- Key-Value Store - consistent hashing uses similar partitioning concepts
Related Concepts
Understand the building blocks used in this design:
- Consistent Hashing → — assigns ID ranges or worker nodes so generators never collide
- Leader Election → — coordinates the authority that hands out node IDs and epochs
- Database Replication → — durably persists allocated ID ranges so restarts don’t reissue IDs
Discussion
Newest first