Topic 075 / Core
Unique ID generation
Chapter 5.5 · Distributing Data
What and why
A single auto-increment counter is a central coordination point that doesn't survive sharding (→ 73) cleanly. Unique ID generation picks a strategy for producing ids that are unique — and usually also sortable — across many independent writers. Builds on: → 73 (partitioning and sharding).
Diagram
| Strategy | Sortable | Coordination needed | Index-friendly |
|---|---|---|---|
| Auto-increment | yes | yes (one counter) | yes |
| UUIDv4 | no | none | no — scatters inserts |
| Snowflake-style | roughly, by time | none (timestamp + node id) | yes |
How it works
- Auto-increment: the database assigns the next integer — simple and sortable, but a single point of coordination with no meaning across shards.
- UUIDv4: generated anywhere with no coordination, effectively collision-free, but random — insertions scatter across the whole index (→ 64) rather than appending at one edge, and the id carries no time ordering.
- Snowflake-style: pack a timestamp, a node/worker id, and a per-node sequence number into one integer — roughly time-sortable, generated independently on each node with no central counter, at the cost of needing stable node ids and reasonable clock discipline.
Practical example
(illustrative layout). 41 bits of millisecond timestamp + 10 bits of node id + 12 bits of per-node sequence gives each node up to 4,096 ids per millisecond, unique and roughly time-ordered, with no shared counter between nodes.
When to use it
- Use when: auto-increment for a single, unsharded database with no decentralized generation need; snowflake-style once writes are distributed across shards or nodes and rough time ordering still matters.
- Avoid when: UUIDv4 as a clustered/primary B-tree key at high insert volume — the random scatter costs real index write performance.
- Failure scenarios: two nodes misconfigured with the same node id, producing colliding ids; a node's clock jumping backward, producing a duplicate or out-of-order id (clock drift → 135).
- Simpler alternative: plain auto-increment, until sharding actually requires decentralized generation.
Practice
(mechanism, 15–20 min, any language). Implement a tiny snowflake-style generator (timestamp + fixed node id + an in-memory sequence counter) and generate 1,000 ids across two simulated node ids. Verify no collisions occur and that each node's ids are monotonically increasing. Done when 1,000 ids show zero collisions and per-node monotonic order.
Key takeaway
Pick an id strategy by whether generation must be decentralized and whether sort order matters — not by habit. Done when you can: name the failure each strategy is immune to and vulnerable to. Used next in → Projects 2, 13; clock synchronization → 135.
References
None — this topic makes no external claims.
Source directory