Unique ID Generation at Scale
Generate unique, roughly sortable IDs across many servers with UUIDs, Snowflake-style IDs, ticket servers or ULIDs, and know their trade-offs.
Intermediate · about 2 hours · difficulty 3/5
Learn first: Sharding and Partitioning
A single database can hand out auto-increment IDs. Once you shard or run many writers, you need IDs that are unique without coordination on every write.
Options
- UUID v4: 128 random bits. No coordination, effectively no collisions. Downsides: large, not sortable, and random inserts fragment B-tree indexes.
- UUID v7 / ULID: time-ordered prefix plus randomness. Sortable by creation time and index friendly. A strong modern default.
- Snowflake (Twitter): 64-bit integer = timestamp (41 bits) + machine/worker ID (10 bits) + per-millisecond sequence (12 bits). Compact, roughly time-sorted, about 4,096 IDs per millisecond per worker.
- Ticket server / range allocation: a central service hands out blocks of IDs (1 to 10,000 to server A). Simple and dense, but the allocator must be highly available.
- Database sequences with offsets: server 1 uses odd numbers, server 2 even. Works for a fixed small number of writers.
What to consider
- Size (fits in a 64-bit column?), sortability, whether IDs leak information (sequential order IDs reveal your daily volume to competitors), and URL friendliness (Base62 encode for short links).
- Clock issues: Snowflake relies on clocks. If a clock goes backwards (NTP adjustment), a worker must wait or refuse to issue IDs.
- Worker ID assignment: hand out unique worker IDs via config or a coordinator like ZooKeeper or etcd.
Pitfalls
- Exposing sequential IDs in public URLs, making scraping and enumeration trivial.
- Using random UUID v4 as the primary key of a huge, write-heavy MySQL table and suffering index bloat.
You are ready to move on when you can lay out the bits of a Snowflake ID, estimate how many years its timestamp lasts, and choose an ID scheme for orders, short URLs and chat messages.
Key concepts
- Auto-increment limits
- UUID v4
- UUID v7 and ULID
- Snowflake IDs
- Ticket servers and range allocation
- Clock skew handling
- Base62 encoding
Mini project
Implement a Snowflake-style ID generator with configurable epoch and worker ID, generate 1 million IDs across 4 threads, verify uniqueness and ordering, and simulate a backwards clock jump to show your handling.
Check yourself
Why do time-ordered IDs like UUID v7 or Snowflake insert more efficiently into a B-tree index than random UUID v4?
Free resources
- Twitter Snowflake (archived) (GitHub)
- RFC 9562: UUIDs (IETF)
- ULID specification (GitHub)