Unique ID Generation
By Ankur NayakReviewed
Distributed systems need unique IDs without a single database sequence becoming a bottleneck. Snowflake-style IDs pack a timestamp, a machine ID and a sequence number into 64 bits, so every server can mint sortable IDs independently.
How it works
An auto-increment column works on one database, but with many shards and many writers it becomes a bottleneck and a single point of failure. UUIDs avoid coordination but are 128 bits, random and not time-ordered, which hurts index locality.
Twitter's Snowflake (announced in 2010) builds a 64-bit ID from a millisecond timestamp, a worker ID and a per-millisecond sequence. IDs are unique without coordination, roughly sorted by time, and fit in a 64-bit integer. Discord, for example, uses Snowflake IDs for messages, which lets it sort and bucket them by time.
Another approach is range allocation: a coordinator hands each server a block of numbers (say 1,000,000 at a time) and the server counts through it locally. This is common for short codes, such as in URL shorteners, where the number is then base62-encoded.
Key points
- Snowflake: time + machine + sequence in 64 bits
- Range allocation: coordinate once per block, not per ID
- Time-ordered IDs keep indexes append-friendly
- Clock skew must never make IDs go backwards
When to use it, and pitfalls
Use it for
- Primary keys across sharded databases
- Message, post and event IDs that should sort by time
- Short, compact public IDs
Watch out for
- Clock moving backwards (NTP) producing duplicates; refuse to issue until it catches up
- Sequential IDs are guessable; don't expose them where enumeration matters
- Worker IDs must be unique across the fleet
Used in
Related building blocks
Frequently asked questions
Why not just use UUIDs?
UUIDs are fine for uniqueness, but they are 128 bits and random v4 UUIDs are not time-ordered, so inserts scatter across a B-tree index and sorting by ID is meaningless. Snowflake-style IDs are half the size and roughly sorted by creation time.
Sources
- twitter-archive/snowflake · GitHub