Generate unique ids without a central counter
Auto-increment ids need one database; UUIDs are random and index poorly.
Say it like this
Ids must be unique across many writers with no coordination on the hot path, so I use time-ordered ids like Snowflake or UUIDv7 that sort by creation time and index well.
Basic solution
Use time-ordered ids: a timestamp plus node id plus sequence (Snowflake), or ULID / UUIDv7.
A Snowflake id and where its bits come from
Each writer combines its clock, its node id and a local counter into one 64-bit id, so no two writers coordinate per insert. The id sorts by time, so inserts append to the index.
How it works
- Each writer is assigned a small node id at startup, from config, a coordination service, or a lease, so no two live writers share one. The node id is what keeps two machines from ever producing the same id.
- On each insert the writer reads its clock in milliseconds and takes the next value of an in-memory sequence counter for that millisecond. No network call is involved.
- It packs the three into one 64-bit integer: 41 bits of timestamp, 10 bits of node id, 12 bits of sequence (the Snowflake layout). The timestamp sits in the high bits, so ids sort by time.
- If the sequence overflows (more than 4,096 ids requested in one millisecond on one node) the writer spins until the clock ticks to the next millisecond and the sequence resets to zero.
- The id goes into the row as the primary key. Because the high bits are time, each new row lands at the right-hand end of the B-tree index and ids sort by creation order.
Why not the obvious alternatives
- Database auto-increment is one counter on one node: every insert round-trips to it, and if that node is down nothing can be inserted anywhere.
- Random UUIDv4 is unique without coordination, but each insert lands at a random position in the index, so pages split and the cache thrashes; 128 bits also doubles key and index size compared with 64.
Worked example
News feed post ids
- 50M DAU, 5% post per day ≈ 2.5M posts/day, ~30 writes/s average, ~300/s at peak; trivially inside one node's 4,096 ids per millisecond, so the sequence never overflows.
- Snowflake layout: 41 bits of ms since a custom epoch gives 2^41 ms ≈ 69 years before the timestamp wraps; 10 bits allow 1,024 writers; 12 bits allow 4,096 ids per ms per writer, or 4M ids/s per writer.
- Ids sort by time, so the timeline cache can keep a sorted set of post ids and page by "ids less than cursor" without a separate timestamp column.
- Key size: 8 bytes vs 16 for a UUID. On 1B posts with 3 indexes that is 24 GB less index data to hold in memory.
- For the URL shortener the requirement flips: aliases must be unguessable, so sequential ids are wrong there and the pre-generated random key table is the right tool.
Variants and when each wins
Snowflake-style (timestamp + node + sequence)
- A 64-bit id built locally from the clock, a node id and a counter, time-ordered and with no coordination per id. It wins when keys must be small or you already assign node ids; it needs node ids assigned once and tolerates no clock going backwards.
ULID / UUIDv7
- A 128-bit id with a millisecond timestamp prefix and random bits after it, so it sorts by time and needs no node id. It wins when you want zero coordination and can afford 16 bytes; the low bits are still random.
Database sequence with range allocation
- Each writer grabs a block of 1,000 ids from one database sequence and hands them out locally. It wins for simplicity when strict ordering within a block matters; ids are guessable and the sequence is a dependency.
Pre-generated key table (KGS)
- A service fills a table with random keys ahead of time and writers claim batches of them. It wins when ids must be unguessable, because they are random and collision-free by construction; it is one more service to run.
Pick UUIDv7 when you want zero coordination and can afford 16 bytes; Snowflake when keys must be small or you already assign node ids; KGS when ids must be unguessable.
Failure modes
Clock goes backwards
- A node emits an id smaller than its previous one, or a duplicate of one it already issued. It happens because an NTP step adjustment or a VM resume moved the clock back. Fix it by refusing to issue ids until the clock passes the last timestamp used, and alerting if the gap is large.
Duplicate node ids
- Two writers produce the same id in the same millisecond. It happens because a node id was reused after a restart while the old process was still alive and still issuing ids. Fix it by leasing node ids from etcd or ZooKeeper with a TTL, or deriving them from a stable slot such as a StatefulSet ordinal.
Ids leak information
- A competitor estimates your daily order volume from the gaps between ids, or a user guesses the id of the next resource. It happens because ids expose their creation time and are nearly sequential. Fix it by never using the id as an access token, and adding a separate random public identifier for anything user-facing.
Sequence exhaustion
- A burst stalls writes for a millisecond at a time. It happens because more than 4,096 ids were requested in one millisecond on one node, so the writer had to spin. Fix it with more nodes, or by moving bits from the node id field to the sequence field.
Epoch overflow
- Ids stop sorting correctly, decades from now. It happens because 41 bits of milliseconds run out about 69 years after the chosen epoch. Fix it by choosing a custom epoch at launch and documenting the rollover date; it is a 69-year problem, not an incident.
Interviewer follow-ups
Answer out loud before you open each one.
Why are random UUIDs bad for a primary key?
Random keys insert at random positions in a B-tree, so every insert touches a different page, causes splits and evicts useful pages from cache. Time-ordered keys append at the right edge, so inserts are sequential and the working set of index pages stays small.
How do you assign node ids safely?
Take a lease from a coordination service at startup with a TTL, and refresh it while running. If the lease cannot be refreshed, stop issuing ids. In Kubernetes a StatefulSet ordinal works as a stable slot without a lease.
What happens if two data centres generate ids at once?
Reserve a few bits of the node id for the region so two regions never share a node id. Ordering across regions is only as good as their clocks, which is fine for sorting a feed and not fine for deciding which write won.
How would you make these ids safe to expose in a URL?
I would not. Keep the Snowflake id internal and add a public id that is random, such as a base62 string from a key table, with a unique index. The URL shortener needs exactly this because the alias must not be guessable.
Connections
- In study paths
- Splitting the data
- Pairs with
- Partition the data · Order events within a stream · Do not trust the client clock · Page results with a cursor
- Pulls against
- Default to a relational database
- Used in
- URL Shortener (TinyURL / bit.ly) · News Feed (Twitter / X timeline)
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Writer | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Aurora | Posts table | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |