Case study: Unique ID generator
Overview
Every post, message, order and payment needs an ID. In a single database, AUTO_INCREMENT does the job. In a system that writes from hundreds of servers across regions, millions of times per second, ID generation becomes a design problem of its own, and a favourite interview question.
Try the exercise first: 45 minutes, then compare.
1. Requirements
- Unique across all servers and data centres, forever.
- 64-bit integers (compact keys; fits in a
BIGINT). - Roughly sortable by time: newer IDs are larger, which helps pagination (“posts after ID X”) and B-tree index locality.
- High throughput: a million IDs per second at peak.
- Low latency and highly available: ID generation must never be the reason a write fails.
2. Options
| Approach | How | Pros | Cons |
|---|---|---|---|
| Database auto-increment | One counter | Simple, ordered | Bottleneck, single point of failure, not unique across shards |
| Multi-master with offsets | Server k uses k, k+N, k+2N… | No coordination | Hard to add servers; ordering by time is weak |
| UUID v4 | 122 random bits | Generate anywhere | 128 bits, random order fragments indexes, not time-sortable |
| UUID v7 / ULID | Timestamp + randomness | Time-ordered, generate anywhere | 128 bits |
| Ticket server / ranges | Central counter hands out blocks | Simple, 64-bit | Central store must be available; ordering only within a block |
| Snowflake-style | Timestamp + machine + sequence | 64-bit, time-ordered, no runtime coordination | Needs machine IDs and sane clocks |
If 128 bits is acceptable, UUID v7 is often the simplest good answer today. With the 64-bit requirement, Snowflake-style IDs fit best.
3. The Snowflake layout
- 41 bits of milliseconds since a custom epoch (for example 1 January 2025) last about 69 years.
- 10 bits of machine ID allow 1,024 generators; you can split them, such as 5 bits data centre + 5 bits machine.
- 12 bits of sequence allow 4,096 IDs per millisecond per generator, about 4 million per second each.
Generation is pure local computation: read the clock, increment the sequence, shift and combine. No network call.
if now_ms == last_ms:
seq = (seq + 1) & 4095
if seq == 0: wait until next millisecond
else:
seq = 0
last_ms = now_ms
id = ((now_ms - EPOCH) << 22) | (machine_id << 12) | seq4. Deep dives
Assigning machine IDs
Two generators with the same machine ID could produce duplicates. Options:
- assign IDs from configuration at deploy time (static fleets),
- lease an ID from ZooKeeper or etcd at startup (ephemeral nodes or leases), releasing it on shutdown,
- in Kubernetes, derive from a StatefulSet ordinal.
Clock problems
The timestamp comes from the machine’s wall clock, which NTP can adjust backwards. If the clock goes back, new IDs could repeat old ones. Defences:
- remember the last timestamp; if
now < last, wait until it catches up (small jumps) or refuse to generate and alert (large jumps), - run NTP in slew mode (gradual adjustment) and monitor clock offset.
Library or service?
- Library in each service: no network hop, scales with the fleet; needs machine-ID assignment for every instance.
- Dedicated ID service: fewer generators to manage, but adds a network call and must be highly available; clients can request IDs in batches to reduce calls.
Ordering guarantees
IDs are only roughly ordered across machines (clock skew of a few milliseconds, plus sequence ordering within a millisecond). That’s fine for “newest first” feeds, but don’t use ID order as proof that one event happened before another on a different machine (week 5, clocks).
5. Trade-offs
- Information leakage: timestamps in IDs reveal creation time, and sequential IDs reveal volume. Expose opaque or encoded IDs publicly if that matters.
- Epoch lifetime: 69 years is plenty, but choose the epoch deliberately.
- Throughput limits: 4,096 per millisecond per generator; add generators for more.
6. Follow-up questions
- IDs for a URL shortener? Encode the 64-bit ID in base62 (about 11 characters) or use smaller ranges for shorter codes.
- Need strictly increasing IDs? Only a single sequencer (or consensus) gives that, at a throughput cost.
- What if a data centre is isolated? Generators keep working: no coordination at runtime.
Recap
Unique IDs at scale must be generated without a central bottleneck. Snowflake-style IDs pack a millisecond timestamp, a machine ID and a sequence number into 64 bits, giving time-ordered, collision-free IDs at millions per second per generator. Assign machine IDs safely, guard against clocks moving backwards, and consider UUID v7 when 128 bits is acceptable.
Design it yourself (45 minutes)
Set a 45-minute timer and design an ID generation service for a large social platform: IDs must be unique across all data centres, fit in 64 bits, be roughly sortable by creation time, and support 1 million IDs per second at peak with very low latency. Compare at least three approaches before choosing one.
1. Requirements and constraints:
2. Options considered (pros/cons):
a) auto-increment
b) UUID
c) ticket server / ranges
d) timestamp-based (Snowflake)
3. Chosen design and bit layout:
4. Assigning machine IDs:
5. Clock problems:
6. Trade-offs:A strong answer covers:
- Auto-increment: simple but a single bottleneck/point of failure; not unique across DBs.
- UUID v4: generated anywhere, but 128 bits and not time-ordered (bad B-tree locality).
UUID v7/ULID are time-ordered but still 128 bits.
- Ticket server / range allocation: central counter hands out blocks; simple; the
central store must be highly available; IDs only roughly ordered across servers.
- Snowflake: 1 sign bit + 41-bit ms timestamp (~69 years from a custom epoch) +
10-bit machine ID (1,024 generators) + 12-bit sequence (4,096 per ms per machine)
→ ~4 million IDs/s per generator.
- Machine IDs: assigned via ZooKeeper/etcd leases or config; must be unique.
- Clock: NTP drift/backward jumps → refuse to generate (or wait) until the clock passes
the last timestamp; monitor skew.
- Deployment: library in each service (no network hop) or a small service.Summary
- Requirements usually include uniqueness without coordination, a compact 64-bit size and rough time ordering.
- UUID v4 is easy but large and random; auto-increment is ordered but centralised; ranges reduce coordination.
- Snowflake-style IDs combine a timestamp, a machine ID and a per-millisecond sequence in 64 bits.
- Machine IDs must be unique, typically assigned through a coordination service.
- Clocks can move backwards: detect it and wait or fail rather than risk duplicate IDs.