skip to content
jaeaeichsysdes

Distributed Unique IDs

Deriving every distributed ID generator from three first-principles mechanisms: coordination, probability, and partitioning space and time.

On one server, a single lock and counter (1, 2, 3, ...) works. Scale to 100 servers across 3 regions at 100,000 IDs/sec, and it fails in two ways:

  • Network bottleneck: every ID pays a round-trip and row-lock contention.
  • Global SPOF: a counter DB hiccup stalls writes fleet-wide.

The only three ways to avoid collisions

Every distributed ID generator is one of three pillars (or a hybrid). Click any pillar to focus it, then fire bursts in the simulator across three servers.

interactive · click any column to isolate its trade-off

01Coordinateshared counter or range leasesrv Asrv Bsrv Ccounter DBlock per IDfix: range leasereserve [1000..1999] once,serve 1,000 IDs from RAM02Randomize122 random bits, zero networka9f4…7c02…e1b8…p1p2p3p4cost: B-Tree splitsUUID v4 works offline andstays unguessable, at 128b03Space + Timeexclusive lane + local clock41b timenodeseqfullfullfullhotappend-only B-TreeSnowflake (64b) · UUID v7 (128b)guard against NTP clock skew

trade-off: coordination, entropy, or clock trust3 mechanisms

interactive · switch strategy and fire bursts across 3 nodes

server Anode 0
172806596198417280617676801728057573376
server Bnode 1
172806596608017280617717761728057577472
server Cnode 2
172806597017617280617758721728057581568

startup only · k-sorted · 64-bit41b time + 10b node + 12b seq

Pillar 1: Coordination

One authority prevents collisions; the craft is minimizing how often servers ask.

  • Central counter (AUTO_INCREMENT / Redis INCR): strictly monotonic and 64-bit, but every ID pays a network hop through one coordinator.
  • Multi-master ticket servers (Flickr): k independent DBs each start at a unique offset and increment by k (DB1: 1, 3, 5..., DB2: 2, 4, 6...). Removes the single-DB SPOF, but resizing requires reconfiguring strides and IDs drift out of global time order.
  • Range / segment leasing (Hi-Lo, Meituan Leaf-Segment): atomically reserve a block of 1,000 IDs ([1000..1999]) in one DB write, then serve from RAM in nanoseconds. Double buffering pre-fetches the next block at 80% usage to hide DB latency and brief blips. Trade-off: crashes drop unused RAM IDs (gaps), and order is per-server only.

Pillar 2: Probability (UUID v4)

UUID v4 packs 122 cryptographically random bits into 128 bits (5.3 × 1036 values) — at 1 billion IDs/sec, you would run for decades before a 50% collision chance.

  • Wins: zero coordination, offline client minting, and unguessable URLs (/orders/1001).
  • B-Tree tax: random keys jump across sorted B-Tree leaf pages instead of appending, causing page splits, random disk I/O, low fill factors, and bloated secondary indexes.

interactive · insert records to compare random splits vs sequential appends

uuid v4 (random)50% full · 0 splits
p1
····
p2
7365f5··
p3
be8bbc··
p4
c94e12fd0c4a
snowflake / uuid v7100% full · 0 splits
p1
101102103104
p2
105106107108

random touches 4 pages · time-sorted writes to 1 hot pagesequential append avoids page splits

note

Store UUIDs as native 16-byte UUID / BINARY(16) — never 36-byte VARCHAR, which more than doubles index memory.

Pillar 3: Partitioning space + time (Snowflake)

For zero per-ID network calls, 64-bit compactness, and append-only B-Tree writes, carve 64 bits into orthogonal namespaces:

41 bits

timestamp · 69.7 years

10 bits

1,024 nodes (32 DC × 32 MC)

12 bits

4,096 IDs / ms / node

Putting the timestamp in the most significant bits keeps IDs k-sorted, so inserts append cleanly to the rightmost hot B-Tree page. Drag any field or step the clock below to watch the 64 bits update.

interactive · drag any bit field or step the clock and sequence

0001011000100100100101101100100001010100100001101100000000010001

id: 159556595515174094569.7 yrs · 1,024 nodes · 4,096/ms

The modern hybrid: UUID v7 and ULID

Combine Pillar 3 and Pillar 2 to get append-only ordering without managing machine IDs, at the cost of 128 bits instead of 64:

  • Prefix (48 bits): Unix ms timestamp (~8,900 years, sequential B-Tree appends).
  • Suffix (74–80 bits): cryptographically random bits (no worker-ID coordinator).

Break it: NTP clock skew

When NTP steps a server’s wall clock backward, a naive Snowflake generator reuses an earlier millisecond and emits a duplicate. Trigger a backward jump in naive mode, then test wait / spin and logical clock.

interactive · step the clock backward to trigger a collision, then test each guard

wall 5001ms20975874048DUPLICATE ID! clock jumped -2ms
wall 5003ms20984262656clean tick · 5003ms
wall 5002ms20980068352clean tick · 5002ms
wall 5001ms20975874048clean tick · 5001ms

status: COLLISION · duplicate at 5001msswitch guard mode, then step backward

Three more production traps

  • Machine ID leases in Kubernetes: acquire worker IDs (0–1023) from etcd, ZooKeeper, or a DB lease table with TTL heartbeats instead of hardcoding them in auto-scaling clusters.
  • Information leakage: sequential and Snowflake IDs expose order volume and creation timestamps; use UUID v7/v4 or obfuscate at the API boundary (Sqids or format-preserving encryption).
  • JavaScript 53-bit precision trap: JS Number (IEEE 754 float64) loses precision above 253 − 1 — always serialize 64-bit Snowflake IDs as JSON strings ("id": "159556782...").

System design decision matrix

Requirement Best fit Why
Compact 64-bit, high write QPS, time-sorted DB keys, own infra Snowflake 8 bytes, append-only B-Tree, ~4M IDs/s/node
Time-sorted DB keys, zero worker-ID ops, 128-bit is fine UUID v7 / ULID 48-bit ms prefix + random suffix, no coordinator
Simple sequential integers without clock-skew risk Range leasing DB contacted once per block; RAM-speed serving
Offline clients, zero coordination, opaque public tokens UUID v4 122 random bits, unguessable, works disconnected

Where this shows up in system design

  • Design Discord / SlackMessage IDs use 64-bit Snowflake so chat history paginates by ID without a separate timestamp index.
  • Design URL ShortenerRange leasing (or Base62-encoded counter blocks) generates short 7-character codes without DB lock contention.
  • Design Twitter / News FeedTweet IDs (Snowflake) give natural reverse-chronological sorting across sharded timelines.
  • Design Stripe / PaymentsUUID v4/v7 for public payment intent tokens and client-generated idempotency keys.
  • Design Offline Notes / SyncClient-side UUID v4 or UUID v7 lets disconnected mobile devices mint primary keys before syncing.

Check yourself: system design scenarios

interactive · pick an architecture for each prompt to test your intuition

1. Discord / Slack message IDs

150k writes/s · time-sorted · 64-bit int · own infra

You're designing message storage for a chat platform ingesting 150,000 messages/sec across dozens of shards. Messages must sort naturally by time and fit in an 8-byte integer for fast pagination.

2. Offline-first mobile notes app

offline clients · zero coordination · merge later

Users create and edit notes on airplanes with zero connectivity, then sync to the cloud hours later. Two devices must never collide when syncing new notes.

3. Public e-commerce order URLs (/orders/<id>)

PostgreSQL B-Tree · no worker-ID ops · unpredictable URL

Your checkout service writes orders to PostgreSQL (B-Tree primary key). You don't want to manage ZooKeeper/etcd worker IDs, and you must not expose your daily order volume in the URL.

4. Internal billing invoice numbers

short integers · no clock-skew risk · 2k writes/s

Finance wants clean, human-readable sequential integers for internal invoices (~2,000/sec peak). They never want NTP clock skew to block or duplicate an invoice ID.

esc
⌘B sidebar[ ] prev/next1–5 flowsc copyt theme