Case studies

Design a unique ID generator

Generate 64-bit, roughly time-sortable IDs on many machines with no coordination per ID. The hard parts are handing out worker IDs safely and clocks that move backwards.

Case study21 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A social app keeps posts in one MySQL database, and the primary key is an AUTO_INCREMENT column. IDs are unique, compact and in creation order, and nobody thinks about them. Then the posts table is split across 16 database servers. Each server has its own counter, so 16 different posts now have ID 1001. Asking one central database for every ID fixes uniqueness and puts a single point of failure in front of every write in the company.

Twitter met this in 2010 when it began moving tweets from MySQL to Cassandra, which has no auto-increment. Its answer, announced that year, was Snowflake: a small service that builds each ID from the current time, the generator’s own number and a counter, so many machines can produce IDs at once without talking to each other. The background and the wider set of schemes are in unique IDs. This case study designs the generator.

Requirements

Functional

  • Every ID is unique across all machines and regions, for the life of the system.
  • IDs fit in 64 bits, so they are stored in an ordinary BIGINT column.
  • IDs are roughly sortable by time: one created a second after another compares greater.
  • Generating an ID needs no network call to a shared component.

Not required: consecutive numbers with no gaps, and unguessable IDs. These IDs reveal when they were made.

Non-functional

  • Throughput: 100,000 IDs a second at peak across the fleet, with room for ten times that.
  • Latency: microseconds in process, under 2 ms at p99 as a network service.
  • Availability: no single point of failure. A generator that is cut off from every other machine keeps working.
  • Lifetime: at least 50 years before the ID space runs out.
  • Safety over liveness: returning an error is acceptable. Returning a duplicate is not.

Capacity estimates

There is almost no hardware to size. The scarce resource is bits.

Field Working Result
Sign 1 bit, always 0 IDs stay positive in signed types
Timestamp 41 bits of milliseconds: 2^41 ms / 31.5 billion ms per year about 69.7 years
Worker ID 10 bits 1,024 generators
Sequence 12 bits per millisecond: 4,096 x 1,000 about 4.1 million IDs per second per worker
Demand 100,000 per second / 1,000 100 IDs per millisecond, fleet-wide

One generator could meet the whole demand 40 times over. Throughput is not the problem. The design effort goes into the two things the layout takes for granted: that every generator has a different worker ID, and that a generator’s clock never repeats a millisecond.

The split is adjustable. If you wanted a generator inside every application process, 1,024 worker IDs would not be enough, and you would move two or three bits from the sequence to the worker field.

API

As a library there is one call, next_id(), which returns a 64-bit integer. As a service:

GET /v1/ids?count=3

200 OK
{ "ids": ["7309642518034468864", "7309642518034468865", "7309642518034468866"] }

IDs travel as strings in JSON. JavaScript numbers are exact only up to 2^53, and a larger ID parsed as a number is silently rounded to a different one. Twitter added a string form of the ID to its API for this reason.

Anyone can read the creation time back out of an ID: timestamp_ms = (id >> 22) + EPOCH.

Data model

The ID itself is the main data structure.

Bits Field Notes
1 sign always 0
41 timestamp milliseconds since a custom epoch, such as the start of the year you launch
10 worker ID 3 bits of region and 7 bits of worker within the region
12 sequence resets to 0 each millisecond

The timestamp sits in the high bits so that comparing IDs compares time first. A custom epoch matters: counting from 1970 would spend most of the 69 years before the system exists.

Two small pieces of state support it.

  • Worker registry, in etcd or ZooKeeper: one key per worker ID, holding the owner’s host name and the highest timestamp that owner may have used, attached to a lease.
  • Generator state, in memory: last_timestamp and sequence. A high-water mark of the timestamp is also saved outside the process, for restarts.

High-level architecture

Unique ID generator reference architecture7 components: App services, Load balancer, ID generator 1, ID generator 2, etcd or ZooKeeper, NTP time source, Databases. Connections: App services to Load balancer; Load balancer to ID generator 1 (next_id); Load balancer to ID generator 2; ID generator 1 to etcd or ZooKeeper (lease and renew); ID generator 2 to etcd or ZooKeeper; NTP time source to ID generator 2 (clock sync); App services to Databases (insert with ID).App servicesneed IDs for new rowsLoad balancerID generator 1worker ID 1ID generator 2worker ID 2etcd orZooKeeperworker ID leasesNTP time sourceslewed and leap-smearedDatabasesrows keyed by IDnext_idlease and renewclock syncinsert with ID
Unique ID generator reference architecture

Startup. A generator claims a free worker ID in the coordination store under a lease, reads the high-water mark left by that ID’s previous owner, and waits until its own clock has passed it. Only then does it report healthy.

Request. An application service asks for an ID through the load balancer. The generator reads its clock, combines the timestamp, its worker ID and the next sequence number, and returns. Nothing else is contacted. The application uses the ID as the primary key of the row it writes.

In the background. The generator renews its lease every few seconds and records a new high-water mark with each renewal. The machine’s clock is kept in step by NTP.

Deep dives

The options, against the requirements

Option 64-bit Time-sortable Coordination
One auto-increment database Yes Yes Every ID, single point of failure
Ticket servers with offsets Yes Roughly A database call for every ID
UUID v4 No, 128 No None
UUID v7 No, 128 Yes None
Leased counter ranges Yes No One call per block
Snowflake-style Yes Yes, roughly Once, at startup

Ticket servers are the scheme Flickr described in 2010: two MySQL servers hand out IDs, one configured to produce odd numbers and the other even, so either can fail. It works, but every ID is a database round trip, and the two counters drift apart, so order is only approximate.

UUID v4 is 122 random bits. No coordination, but it is twice the size and random keys scatter inserts across a B-tree index, which costs page splits and cache misses. UUID v7, standardised in RFC 9562 in 2024, puts a 48-bit millisecond timestamp first and fixes the ordering problem. It only fails here on size.

Leased ranges, as used for short codes in the URL shortener, give unique 64-bit numbers with little coordination, but two servers working through different blocks produce IDs in no time order.

Snowflake-style IDs are the only row that meets all four requirements. If the 64-bit limit were dropped, I would use UUID v7 and delete most of this design.

Generating IDs and assigning worker IDs

The generator is a few lines, run under a lock or on a single thread:

def next_id():
    now = current_millis()
    if now < last_ts:
        raise ClockMovedBackwards(last_ts - now)
    if now == last_ts:
        seq = (seq + 1) & 4095
        if seq == 0:                      # 4,096 IDs used in this millisecond
            now = wait_for_millis_after(last_ts)
    else:
        seq = 0
    last_ts = now
    return ((now - EPOCH) << 22) | (worker_id << 12) | seq

All of the difficulty is in worker_id. Two generators with the same worker ID are each correct on their own, and together they produce duplicates that nothing detects until a primary key conflict appears somewhere downstream.

Static assignment puts the worker ID in configuration, or takes it from a stable identity such as a Kubernetes StatefulSet ordinal. It needs no runtime dependency. It fails through human error: a copied configuration file, or a machine image cloned with its ID inside.

Leased assignment has each generator claim an ID at startup with an atomic create-if-absent in etcd or ZooKeeper, tied to a lease or an ephemeral node. If the process dies, the lease expires and the ID becomes free. The original Snowflake used ZooKeeper for worker IDs. Two hazards remain.

  • A paused process. A generator stalls for 40 seconds in a garbage collection pause or a VM migration. Its lease expires, another process claims its worker ID, and then the first one wakes up and carries on. To prevent this, the generator tracks its lease deadline on a monotonic clock and refuses to issue once it has passed, until it has renewed. Long leases, of minutes, make this rare and let a generator ride out a short outage of the coordination store. The same idea appears as fencing in distributed locks.
  • Reuse. A new owner of worker ID 7 must not issue timestamps the old owner already used. This is what the high-water mark in the registry is for: the new owner waits until its clock is beyond it.

I would use leases, with a database unique constraint on the ID column as the last line of defence.

Clocks

The generator reads the wall clock, and wall clocks are not monotonic. NTP can step the clock back after drift. A virtual machine can resume from a pause with a stale clock. An operator can set the time by hand. A leap second can repeat a second on systems that do not smear it.

If the clock goes back and the generator carries on, it can issue the same (timestamp, sequence) pair twice. The options when now is less than last_ts:

  • Wait if the gap is a few milliseconds.
  • Refuse if it is larger: return errors, fail the health check so the load balancer sends traffic to other generators, and alert. The original Snowflake refused requests until the clock caught up.
  • Keep a logical clock: use the larger of now and last_ts, so the timestamp never decreases. IDs stay unique, and their embedded time runs slightly ahead of real time until the clock catches up.

None of these helps after a restart, because last_ts was in memory. That is the second job of the persisted high-water mark: on startup the generator waits until the clock passes it.

Prevention matters as much. Configure the time daemon to slew the clock (adjust its rate) and not step it, and use a time source that smears leap seconds.

Finally, be honest about ordering. Clocks on different machines differ by milliseconds under NTP, and within one millisecond the worker ID outranks the sequence. Two IDs created close together on different workers can sort in the wrong order. These IDs are good for “newest first” lists and index locality. They are not a way to decide which of two events caused the other.

Multi-region. The three region bits make each region’s ID space disjoint, so regions never coordinate, and each has its own coordination store for worker leases. Three bits allow eight regions with 128 workers each.

Bottlenecks and failure modes

  • Duplicate worker IDs. The worst failure, because it is silent. Leases, the monotonic deadline check and a unique constraint in the database are the defences.
  • Coordination store down. Running generators continue until their leases run out, which is why leases are long. New generators cannot start, so keep spare capacity running.
  • Clock stepped back. Affected generators refuse and leave the pool. With several generators per region, callers retry against another.
  • Sequence exhausted. After 4,096 IDs in one millisecond the generator waits for the next one, adding up to 1 ms. At 100 IDs per millisecond fleet-wide this does not happen.
  • Timestamp exhausted. About 69 years after the epoch. Record the date in the design document.
  • Information leak. IDs reveal creation time, and counting IDs reveals volume. Do not use them as secrets or expose them where that matters.

Trade-offs

Decision Chosen Alternative Why
Scheme Snowflake-style 64-bit UUID v7 Half the key size; costs worker ID management
Worker IDs Leased from etcd Static configuration Survives human error; adds a startup dependency
Clock goes back Wait briefly, else refuse Logical clock Embedded time stays truthful; costs availability on that node
Deployment Small service per region Library in every process Few worker IDs to manage; costs a network hop
Ordering Roughly by time Strict global order Strict order needs a single sequencer on every write

45-minute interview script

A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.

  1. 0:00 to 5:00

    Requirements 5 min

    Ask what the IDs are for. Pin down the four properties (unique, 64-bit, roughly time-sortable, no coordination per ID), the rate, and whether IDs may reveal creation time. Confirm that gaps are fine.

  2. 5:00 to 9:00

    Capacity estimates 4 min

    This is a bit budget, not a hardware estimate. Work out how long 41 bits of milliseconds last, how many workers 10 bits allow and how many IDs per millisecond 12 bits give, then compare with demand.

  3. 9:00 to 11:00

    API 2 min

    A next_id call in a library or a tiny service. IDs as strings in JSON. How to read the timestamp back out.

  4. 11:00 to 15:00

    Data model 4 min

    Draw the bit layout. Explain the custom epoch, the worker registry and the small state each generator keeps.

  5. 15:00 to 21:00

    High-level design 6 min

    Generators behind a load balancer, the coordination store used only at startup and for heartbeats, and time sync. Discuss library against service.

  6. 21:00 to 27:00

    Deep dive: the options 6 min

    Auto-increment, ticket servers, UUID v4 and v7, leased ranges and Snowflake, each against the four requirements. Show why only one meets all of them.

  7. 27:00 to 34:00

    Deep dive: worker IDs 7 min

    Static config against leases in etcd or ZooKeeper. Walk through a paused process whose lease expires and how the generator protects itself. Cover reuse of a worker ID.

  8. 34:00 to 41:00

    Deep dive: clocks 7 min

    Why wall clocks go backwards, what the generator does when it notices, and the restart case where it cannot notice without persisted state. State what ordering the IDs do and do not give.

  9. 41:00 to 43:00

    Multi-region and failure modes 2 min

    Region bits inside the worker field, no cross-region calls. Name the worst failure, which is two generators sharing a worker ID.

  10. 43:00 to 45:00

    Wrap-up 2 min

    Summarise the layout and the two safety rules. Say when you would simply use UUID v7 instead.

Sketch this design on the whiteboard Run it as a timed mock

Key takeaways

  • A Snowflake-style ID is a timestamp, a worker ID and a per-millisecond sequence packed into 64 bits, with the timestamp in the high bits so IDs sort by time.
  • The capacity plan is a bit budget. 41 bits of milliseconds last about 69 years, 10 bits give 1,024 workers and 12 bits give 4,096 IDs per millisecond per worker.
  • Uniqueness rests on two rules. No two live generators share a worker ID, and no generator ever reuses a timestamp it has already used.
  • Wall clocks move backwards. A generator must detect it, and must persist its last timestamp so it can also detect it after a restart.
  • IDs from different workers are only roughly ordered. Do not use them to decide which of two events happened first.
  • If 128 bits are acceptable, UUID v7 gives time-sortable IDs with no worker IDs to manage.

Check yourself

1. In the classic Snowflake layout, why is the timestamp placed in the most significant bits?
2. A generator notices that the current time is 3 seconds earlier than the timestamp of the last ID it issued. What should it not do?
3. Two generator processes start with worker ID 7 because of a configuration mistake. What is the likely symptom?
4. Why does UUID v7 fail the requirements in this design even though it is time-sortable?
5. A generator restarts after its machine's clock was stepped back by 5 seconds. It kept its last timestamp only in memory. What is the risk?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What are the fields of a Snowflake ID?

1 unused sign bit, 41 bits of milliseconds since a custom epoch, 10 bits of worker ID and a 12-bit sequence that counts IDs within one millisecond.

How long do 41 bits of milliseconds last?

2 to the power 41 milliseconds is about 69.7 years, counted from whatever epoch you choose. That is why you pick a recent custom epoch and not 1970.

How does a generator get its worker ID?

At startup it claims an unused ID in etcd or ZooKeeper under a lease and keeps the lease alive. If it cannot renew, it stops issuing before the lease expires.

What does a generator do when the clock goes backwards?

It must not issue IDs with a timestamp lower than the last one used. It waits if the gap is a few milliseconds and otherwise refuses and drops out of the pool until the clock catches up.

What does "roughly time-sortable" mean?

IDs created a second apart sort in order. IDs created within a few milliseconds on different workers may not, because of clock skew and because the worker ID sits above the sequence.

Why send 64-bit IDs as strings in JSON?

JavaScript numbers are exact only up to 2 to the power 53. A larger ID parsed as a number is silently rounded to a different ID.

Review the deck