10. Unique ID Generation
1
The picture to keep in your head2
10.1 What makes a good ID?3
10.2 What's wrong with auto-increment?4
10.3 Why does auto-increment break across many servers?5
10.4 What are UUIDs, and which version should you use?6
10.5 How do Snowflake IDs work?7
10.6 What are ticket servers and ID ranges?8
10.7 Why does clock skew matter for time-based IDs?9
10.8 How do you make short IDs with base62?10
10.9 Should IDs be guessable or unguessable?11
Memory card and where the analogy breaks12
Practice: five levels13
Interview questions14
Solutions15
Sources16
Code lab10. Unique ID Generation
10.1 What makes a good ID?
3 min read+10 XP
The problem
At the bank: A good token is never repeated, easy to read out, and ideally tells staff who came first. It shouldn't let a stranger guess someone else's token and walk up to the counter.
In the system: Decide what you need before picking a scheme. The properties that matter:
| Property | Why it matters | Example need |
|---|---|---|
| Unique | The whole point. Never two rows with one ID | Always |
| Generated without a bottleneck | Thousands of servers creating IDs can't all wait on one counter | High write rates |
| Sortable by time | "Newest first" for free; new rows land at the end of an index (Chapter 9) | Feeds, orders, messages |
| Compact | 64-bit numbers are smaller and faster than 128-bit or long strings | Huge tables, short URLs |
| Unguessable | Stops people walking through /orders/1001, /orders/1002... | Private links, public URLs |
You can't have everything at once. Sortable IDs leak creation order; unguessable IDs are long and random. The schemes in this chapter are different trade-offs between these columns.
Memory code: "Unique always; then pick from fast, sorted, small, secret."