Tech Interview RoomStudy guides

System Design

Design a unique ID generator for a distributed system (like Twitter Snowflake).

Intermediate · 2 min read · Lesson 5 of 36 in System Design

🔢
Design at a glance

Time + machine + counter = an id that is never the same twice.

64bits per id
41 bitsmilliseconds (about 69 years)
10 bitsworker id (1,024 nodes)
4,096ids per ms per worker
Core building blocks
Service instances→Embedded Snowflake generator→Worker-id leases in etcd or ZooKeeper→NTP-synced clocks
Key decision

Generate ids locally with the Snowflake layout; only worker ids need coordination, leased once at startup.

Trade-off
Snowflake: sortable, no coordination per id, needs a sane clock
vs
UUID v4: zero coordination, random and index-unfriendly
Remember
  • Never call a central service per id
  • Lease unique worker ids
  • If the clock goes backwards, wait or refuse

1. Requirements

  • 64-bit numeric ids, globally unique without coordination per id.
  • Roughly time-ordered (sortable by creation time, good for B-tree index locality).
  • 10,000+ ids per second per node, low latency, highly available.

2. Options

  • UUID v4: 128-bit random; no coordination; not sortable, larger indexes and poor insert locality in B-trees. UUID v7 (RFC 9562) adds a millisecond timestamp prefix, so it is time-ordered and a good choice when 128 bits are acceptable.
  • Database auto-increment or ticket servers (Flickr used two MySQL servers with odd/even offsets): simple but a bottleneck and a single point of failure.
  • Range allocation: nodes lease blocks of ids from a central counter.
  • Snowflake: a 64-bit layout generated locally on each node.

3. Build it step by step

The Snowflake layout (64 bits)

  • 1 bit sign (always 0).
  • 41 bits milliseconds since a custom epoch (about 69 years).
  • 10 bits machine id (1,024 workers), often split into datacenter and worker.
  • 12 bits sequence within the same millisecond (4,096 ids per ms per worker).

Stage 1: database auto-increment

Stage 1: one database sequence
Services
Order ServicePayment Service
↓1. INSERT returns next id
Database
🗄️ Single database with AUTO_INCREMENT

Flow:

  1. Every service inserts into the database and receives the next sequence value.

Problem: a network round trip per id, one database caps throughput, and it is a single point of failure.

Stage 2: ticket servers handing out ranges

Stage 2: range allocation
Services
Order ServicePayment Service
↓1. lease a block of 1,000 ids
Allocator
+Ticket server A (odd)+Ticket server B (even)

Flow:

  1. Each service instance leases a block (or uses two servers with odd/even sequences, as Flickr did) and hands out ids from memory until the block is used up.

Problem: ids are no longer ordered by creation time across instances, and the allocator is still a dependency at startup and for every block.

Final architecture: Snowflake generators inside each service

Final architecture
Services
Order ServicePayment ServiceChat Service
↓1. in-process library call (no network)
Generators
+Snowflake generator (worker 17)+Snowflake generator (worker 18)
↓2. lease worker id at startup only
Coordination
🗄️ etcd or ZooKeeper (worker id leases)

End-to-end: 2. At startup each instance leases a unique worker id (or uses its StatefulSet ordinal).

  1. For every id, the generator combines the current millisecond, its worker id and a per-millisecond sequence, entirely in memory: millions of roughly time-ordered ids per second with no coordination per id. If the clock moves backwards, the generator waits or fails rather than risk duplicates.

4. Deep dives

  • Worker id assignment: must be unique among running nodes. Lease it from ZooKeeper/etcd (ephemeral node) or a database at startup; in Kubernetes, derive it from a StatefulSet ordinal.
  • Clock going backwards (NTP adjustment): if the current time is less than the last timestamp, wait until it catches up for small drifts, or refuse and alert for large ones; never generate an id with an older timestamp, or duplicates become possible.
  • Sequence overflow: if 4,096 ids are used within one millisecond, spin until the next millisecond.
  • Ids are k-sorted (ordered across workers only to within clock skew), which is usually enough.
  • Embed as a library (no network hop) or run as a small service.

Example

java
public final class Snowflake {
    private static final long EPOCH = 1704067200000L; // 2024-01-01T00:00:00Z
    private final long workerId;
    private long lastTs = -1, seq = 0;

    public Snowflake(long workerId) {
        if (workerId < 0 || workerId > 1023) throw new IllegalArgumentException("workerId");
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long ts = System.currentTimeMillis();
        if (ts < lastTs) throw new IllegalStateException("Clock moved backwards by " + (lastTs - ts) + " ms");
        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) | (workerId << 12) | seq;
    }
}

Follow-up questions interviewers ask

Try answering each one before you open it.

Why are random UUIDs bad as primary keys in MySQL or PostgreSQL?

B-tree indexes stay efficient when new keys are appended at the right edge. Random UUIDs insert at random positions, causing page splits, poor cache locality, write amplification and larger indexes (16 bytes vs 8). With InnoDB, the primary key is the clustered index, so the whole table suffers. Time-ordered ids (Snowflake, UUID v7, ULID) avoid this.

Can you extract the creation time from a Snowflake id, and is that a problem?

Yes: (id >> 22) + EPOCH gives the millisecond timestamp, which is handy for debugging and time-range sharding. It also leaks creation time and approximate volumes to anyone who sees ids. If that matters for public ids, expose a separate opaque identifier or encrypt the id.