CodingNodes Space play · ←→ step · R restart

The problem

Every table needs a primary key, and inside a single database the job is boring: mark the column auto_increment and the server counts for you. Spread the data across many databases — or let many servers mint their own keys — and that comfort evaporates, because two counters that cannot see each other will happily hand out the same number twice.

This chapter designs the fix: a small service whose only job is to issue unique, numeric, sortable 64-bit IDs, thousands of times per second, with no server ever asking another for permission. The winning idea is to stop counting and start composing — split 64 bits into fields for time, place and a per-millisecond burst counter — the approach Twitter open-sourced as Snowflake.

We first watch auto_increment fail, weigh the three standard alternatives, then build the bit layout field by field and run it end to end: timestamp, datacenter, machine, sequence — and the 69-year clock hiding inside 41 bits.

Requirements

Functional — what it must do

  • Issue IDs that are unique across every generator in the fleet — no two calls, anywhere, ever return the same value.
  • IDs contain digits only and fit a signed 64-bit integer: 8 bytes on the wire, a <code>BIGINT</code> key in any store.
  • IDs sort by creation time — an ID issued later is always larger, so ordering by the key is ordering by time.
  • Callers fetch one or many IDs per request and get an answer in a couple of milliseconds.

Non-functional — how well it must do it

  • Generation is local: no network hop, no lock, no coordination — a cut-off generator still mints IDs.
  • Highly available by construction: generators live in several datacenters, and losing one site leaves the rest issuing.
  • Burst headroom: each machine can issue 4,096 IDs per millisecond (≈ 4.1 million per second) — hundreds of times our peak.
  • The timestamp must not overflow in the system's lifetime: 41 bits buy about 69 years from the epoch we pick.

Scale — how much it must take

  • 10,000 IDs per second at peak — about 864 million a day — issued by a handful of generator machines behind a load balancer.

Assumptions — the numbers this design is sized for

A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.

Peak traffic
10,000 IDs/s
About 864 million IDs a day. One machine could carry it alone; we still run a fleet so nothing depends on a single box.
ID width
64 bits
8 bytes per ID — a BIGINT primary key everywhere, and half the size of the 128-bit UUID we will reject.
Generator fleet
2 datacenters × 2 machines
Four generators. Their datacenter and machine bits are fixed at startup and never change while running.
Per-machine ceiling
4,096 IDs/ms
Twelve sequence bits reset every millisecond. At 10,000 IDs/s over the fleet, each machine uses about 3 of its 4,096 slots.
On-screen load
3 IDs in one ms
Small on purpose, so every ID in the animations can be read digit by digit.
Custom epoch
2020-06-01 UTC
The 41-bit clock counts from launch day, not 1970 — no bits are spent on decades before the first ID existed.
Timestamp runway
≈ 69 years
2^41 − 1 ms from the 2020 epoch puts overflow past the year 2089; a new epoch is the planned migration.
Latency budget
≤ 2 ms per ID
One clock read plus bit packing, all in memory — no disk, no network round trip, no lock.

Takeaways

Part 1

Why auto_increment stops working

A single database is a fine counter for itself. The design breaks at exactly the moment more than one machine must mint IDs.

  1. 1
    One database counts

    One table, one writer: auto_increment hands out 1040, 1041, 1042 in order. The values are unique because exactly one process owns the counter.

  2. 2
    Three apps, one counter

    Scale the app tier out and every insert still detours through the one database that counts. That database is now both a latency floor and a single point of failure for every write in the system.

  3. 3
    Two counters, one collision

    Give each database its own auto_increment and both count honestly from zero — into the same numbers. The duplicate only surfaces later, when reads from both shards are merged.

Part 2

Three candidates

The standard shortlist — multi-master counters, UUIDs, a central ticket server. Each one fixes the previous failure and opens a new one.

  1. 1
    Multi-master: step by k

    Instead of adding 1, each database adds k, the number of databases in the ring. The odd and even streams never overlap — until a database joins or leaves and the whole stride has to be re-cut.

  2. 2
    UUID: mint one locally

    Every server generates IDs alone, no coordination at all, and the collision odds stay negligible even at enormous rates. But the format is 128 bits, mixes in hex letters, and encodes no time — three of our requirements missed at once.

  3. 3
    Ticket server: one counter again

    Flickr's answer for distributed primary keys: one small database whose only job is handing out the next number. Numeric and simple — but the ticket server is a single point of failure, and adding a second one reintroduces the synchronization problem.

  4. 4
    Score the candidates

    Scored against our requirements, only a layout that packs time and place into the 64 bits themselves passes every column. That is the design the rest of this chapter builds.

Part 3

The 64-bit layout

Snowflake's move is to stop counting and start composing: fix five fields inside the 64 bits, each with exactly one job.

  1. 1
    Five fields, 64 bits

    Here is the whole design in one picture: 1 sign bit, 41 bits of timestamp, 5 for the datacenter, 5 for the machine, 12 for the sequence. The widths sum to exactly 64 — an ID is not generated, it is assembled.

  2. 2
    The sign bit

    One bit at the far left, permanently zero. It keeps every ID positive for anything that reads it as a signed integer, and stays in reserve for future format changes.

  3. 3
    41 bits of time

    Milliseconds since a custom epoch, placed leftmost so time dominates the numeric order: a later creation is simply a larger number. Sorting by the key requires no extra work — the order is in the bits themselves.

  4. 4
    5 + 5 bits of place

    Five bits name the datacenter and five more the machine inside it: 32 × 32 = 1,024 generators, each stamping its own address into every ID it makes. Both values are fixed when the process starts and changing them needs review — a slip would forge another machine's signature.

  5. 5
    12 bits of sequence

    A counter from 0 to 4,095 that resets every millisecond. It stays at zero unless this machine mints more than one ID in the same millisecond — the field that lets one box ride out bursts.

Part 4

The clock inside

The timestamp is what makes IDs sortable — and the only field with an expiry date.

  1. 1
    Start the clock in 2020

    Counting from 1970 would waste five decades of bits before the first ID exists. The epoch is a line we choose — ours is the June 2020 launch — and every timestamp is just the offset from it.

  2. 2
    Decode an ID backwards

    Shift the ID right by 22 bits and the timestamp falls out; add the epoch back and you hold the creation time to the millisecond. Every ID carries its own birth certificate.

  3. 3
    69 years of runway

    The field tops out at 2,199,023,255,551 ms — about 69.7 years after the epoch, past the year 2089 for us. At that point a new epoch or a migration is due; picking a late epoch is what pushed the deadline that far out.

Part 5

Same millisecond, many IDs

Within one millisecond on one machine, only the sequence field separates IDs — and it can run dry.

  1. 1
    First ID of the millisecond

    A new millisecond begins, the sequence restarts at zero, and the first ID of the burst is assembled on machine 17 in datacenter 4.

  2. 2
    Two more, same millisecond

    The timestamp cannot change yet, so the sequence climbs: 920, 921, 922. Consecutive integers fall straight out of the layout — snowflake IDs sort correctly even inside a single millisecond.

  3. 3
    The 4,096th ID waits

    The 4,097th ID of one millisecond does not exist yet — the generator spins until the clock ticks and 4,096 fresh slots open. Our peak spends about 3 of those slots per machine: roughly 400 times the headroom we need.

Part 6

When clocks disagree

The layout quietly assumes every generator reads the same time. Real clocks drift, and drift bends the sort order.

  1. 1
    One clock, in theory

    Nothing in the layout forces two machines to agree on the current millisecond. In the happy model one invisible clock serves the whole fleet, disciplined by NTP.

  2. 2
    Two ms of skew

    Two IDs are created at the same real instant, but machine B's clock reads two milliseconds behind, so B's ID is numerically smaller and sorts first. Skew does not break uniqueness — it quietly bends the time order.

  3. 3
    The defenses

    Synchronize with NTP, refuse to stamp a time earlier than the last ID this machine issued, and alert when a clock steps backwards badly. The place bits protect uniqueness; these defenses protect the sort order.

★ Finale

End to end

One call to the ID service, from HTTP request to stored primary key — every field doing the job this chapter gave it.

  1. 1
    The whole system

    Four generators behind a load balancer; storage on the right writes every ID it receives as a primary key. No generator ever talks to another — that is the entire point of the layout.

  2. 2
    Routed to machine 17

    The load balancer picks a healthy generator: machine 17 in datacenter 4. Those ten bits of its identity were fixed when the process started — it cannot stamp anyone else's address.

  3. 3
    Assemble five fields

    Read the clock, pack 41 + 5 + 5 + 12 bits around the sign bit, return the number. It is all local work — the whole assembly takes microseconds, with no lock and no network hop.

  4. 4
    A burst in the same ms

    Two more calls land on machine 17 within the same millisecond. The timestamp holds still, the sequence climbs, and three consecutive numbers go back over the wire.

  5. 5
    Sorted by construction

    The IDs reach storage already in creation order — no sort key, no index rebuild, no central counter anywhere in the path. Ten thousand calls a second, each answered from a single clock read.

🌐 In the wild

In the wild

The pieces of this diagram have names. The chapter's reference list points at four of them — an illustrative mapping, not insider detail.

  1. 1
    Four names for the diagram

    Every block you built maps to a named system or standard from the reference list: a layout that Twitter shipped, an alternative Flickr ran, a format the UUID standard defines, and a protocol that keeps the clock honest.

  2. 2
    Twitter: the layout, shipped

    Twitter announced Snowflake in 2010, and tweet IDs still follow the shape you assembled: time, place and sequence packed into 64 bits. Our version differs only in the epoch we chose and the size of the fleet we stamped.

  3. 3
    Flickr: the ticket server

    For smaller scales, Flickr's ticket-server write-up is still the honest comparison: one database, auto_increment, done. It meets every requirement except availability — one box, one failure domain — which is exactly why bigger systems moved on.

  4. 4
    UUID: a different contract

    The UUID standard is the industry's other default: mint uniqueness locally, ignore time and width entirely. Where storage is cheap and IDs never need to sort, it wins on simplicity — it just cannot pass this chapter's checklist.

  5. 5
    NTP: the metronome

    Snowflake's quiet dependency is disciplined time — NTP is what keeps every generator's 41-bit clock close enough for the sort order to mean something. The last reference in the chapter is the protocol the whole layout leans on.