Design a Distributed Unique ID Generator
Generate billions of unique, roughly time-ordered 64-bit IDs across many machines without coordination — UUID v4/v7, database sequences and ticket servers, range allocation, Twitter Snowflake bit layout, worker-ID assignment, clock skew and rollback handling, and the trade-offs between them.
1. Requirements
- IDs are unique across the whole system, forever.
- 64-bit numeric (fits
BIGINT, compact indexes). - Roughly time-sortable (newer IDs are bigger) — useful for pagination and index locality.
- Generate 10,000+ IDs/s per node, low latency (< 1 ms), no single point of failure.
- Not required: strictly sequential, gap-free numbering (that needs coordination and is rarely needed — invoices are the exception).
2. Options compared
| Approach | Unique | Sortable | Size | Coordination | Notes |
|---|---|---|---|---|---|
| DB auto-increment (single) | ✓ | ✓ strictly | 64 | every ID | SPOF, write bottleneck |
Multi-master with step (id % N) | ✓ | ✗ across servers | 64 | none | hard to add servers |
| Ticket server (Flickr) | ✓ | ✓ | 64 | every ID | SPOF unless paired odd/even |
| Range allocation | ✓ | roughly | 64 | once per block | IDs reveal allocation order |
| UUIDv4 | ✓ (probabilistic) | ✗ | 128 | none | index fragmentation |
| UUIDv7 / ULID | ✓ | ✓ (ms) | 128 | none | great default |
| Snowflake | ✓ | ✓ (ms, k-sorted) | 64 | worker ID only | the classic answer |
3. Snowflake design
import threading, time
class Snowflake:
EPOCH = 1_704_067_200_000 # 2024-01-01T00:00:00Z in ms
WORKER_BITS, SEQ_BITS = 10, 12
MAX_SEQ = (1 << SEQ_BITS) - 1
def __init__(self, worker_id: int):
assert 0 <= worker_id < (1 << self.WORKER_BITS)
self.worker = worker_id
self.last_ts, self.seq = -1, 0
self.lock = threading.Lock()
def _now(self) -> int:
return time.time_ns() // 1_000_000
def next_id(self) -> int:
with self.lock:
ts = self._now()
if ts < self.last_ts: # clock moved backwards
if self.last_ts - ts > 5:
raise RuntimeError("clock regression; refusing to issue IDs")
ts = self.last_ts # small regression: keep using last ts
if ts == self.last_ts:
self.seq = (self.seq + 1) & self.MAX_SEQ
if self.seq == 0: # sequence exhausted this ms
while ts <= self.last_ts:
ts = self._now()
else:
self.seq = 0
self.last_ts = ts
return ((ts - self.EPOCH) << (self.WORKER_BITS + self.SEQ_BITS)) \
| (self.worker << self.SEQ_BITS) | self.seq
public final class Snowflake {
private static final long EPOCH = 1_704_067_200_000L;
private final long worker;
private long lastTs = -1, seq = 0;
public Snowflake(long worker) { this.worker = worker; }
public synchronized long nextId() {
long ts = System.currentTimeMillis();
if (ts < lastTs) {
if (lastTs - ts > 5) throw new IllegalStateException("clock moved backwards");
ts = lastTs;
}
if (ts == lastTs) {
seq = (seq + 1) & 0xFFF;
if (seq == 0) while ((ts = System.currentTimeMillis()) <= lastTs) Thread.onSpinWait();
} else {
seq = 0;
}
lastTs = ts;
return ((ts - EPOCH) << 22) | (worker << 12) | seq;
}
}
4. Deployment architecture
Alternatively run a small, replicated ID service (stateless instances, each with its own worker ID) when you can't embed a library everywhere — but then every ID costs a network call (batch them).
5. Variants
| Scheme | Layout |
|---|---|
| Twitter Snowflake | 41 ts / 10 worker / 12 seq |
| Instagram (in Postgres) | 41 ts / 13 logical shard / 10 seq — generated by a PL/pgSQL function per shard, so IDs encode the shard |
| Sonyflake | 39 ts (10 ms units, ~174 years) / 8 seq / 16 machine |
| ULID | 48 ts + 80 random, base32 string, lexicographically sortable |
| UUIDv7 | 48 ts + version + 74 random |
6. Trade-offs
- Clock dependence is the main risk → NTP slewing, regression checks, alerting.
- Information leakage: IDs reveal creation time and roughly how many IDs a worker issues; use opaque public IDs if that matters.
- Ordering is approximate across workers (clock skew of a few ms) — fine for feeds and pagination, not for strict causality.
- If you only need uniqueness and you're not constrained to 64 bits, UUIDv7 avoids worker-ID management entirely.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.