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
trade-off: coordination, entropy, or clock trust3 mechanisms
interactive · switch strategy and fire bursts across 3 nodes
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/ RedisINCR): 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
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
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
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.
Select an option to check the trade-off.
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.
Select an option to check the trade-off.
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.
Select an option to check the trade-off.
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.
Select an option to check the trade-off.
SPOFreliability
Single Point of Failure: any component whose failure stops the whole system because there is no independent fallback.
monotonicordering
Always moving in one direction: every newly generated value is strictly greater than (or never less than) the previous one.
double bufferingpattern
Pre-fetching the next leased ID block in the background before the current one runs dry, hiding database latency.
B-Treestorage
A self-balancing sorted tree stored in fixed-size disk pages, used by relational databases for primary and secondary indexes.
page splitstorage
When a B-Tree leaf page fills up and splits into two half-full pages, causing extra writes and leaving wasted space.
k-sortedordering
Roughly time-ordered: every item sits within k positions of its true global order, without requiring cross-node locks.
leasecoordination
Time-bounded exclusive ownership of a resource (like a machine ID or lock) that expires automatically if the holder crashes.