{}DSA Atlas

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.

Intermediate4 interview questions

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

ApproachUniqueSortableSizeCoordinationNotes
DB auto-increment (single)✓✓ strictly64every IDSPOF, write bottleneck
Multi-master with step (id % N)✓✗ across servers64nonehard to add servers
Ticket server (Flickr)✓✓64every IDSPOF unless paired odd/even
Range allocation✓roughly64once per blockIDs reveal allocation order
UUIDv4✓ (probabilistic)✗128noneindex fragmentation
UUIDv7 / ULID✓✓ (ms)128nonegreat default
Snowflake✓✓ (ms, k-sorted)64worker ID onlythe classic answer

3. Snowflake design

0 41-bit timestamp (ms)since custom epoch → ~69 years 10-bit worker5 DC + 5 machine 12-bit sequence4,096 per ms sign id = (ts − epoch) << 22 | worker << 12 | seq
Uniqueness comes from (time, worker, sequence); ordering from the timestamp in the high bits.
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

etcd / ZooKeeperworker-ID leases orders svc #1embedded generator, w=17 orders svc #2w=18 payments svc #1w=42 lease at startup, heartbeat; stop issuing IDs if the lease is lost
ID generation is local (sub-microsecond); coordination happens only at startup.

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

SchemeLayout
Twitter Snowflake41 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
Sonyflake39 ts (10 ms units, ~174 years) / 8 seq / 16 machine
ULID48 ts + 80 random, base32 string, lexicographically sortable
UUIDv748 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

0 / 4 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.