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
Memory card and where the analogy breaks
3 min read+10 XP
The memory card (tear this page out)
| # | Question | Memory code |
|---|---|---|
| 10.1 | A good ID? | Unique always; then pick from fast, sorted, small, secret |
| 10.2 | Auto-increment? | One machine, one counter: perfect, until there are two |
| 10.3 | Why it breaks? | Many counters repeat; one counter queues |
| 10.4 | UUIDs? | v4 is a raffle ticket; v7 is a raffle ticket with a timestamp on the front |
| 10.5 | Snowflake? | Time, machine, count: stamp all three and nothing can clash |
| 10.6 | Ticket servers? | Give each branch a book of numbers |
| 10.7 | Clock skew? | Time-based IDs trust the clock, so never trust a clock that runs backwards |
| 10.8 | Base62? | Same number, fewer characters: digits plus both alphabets |
| 10.9 | Guessable or not? | Sequential inside, random outside, and always check who's asking |
The whole chapter in one line: One counter until you can't; then stamp time and machine, or hand out books of numbers, and keep the public ones random.
Where the analogy breaks
- A bank token is thrown away after the visit. An ID lives forever in databases, logs, URLs and other systems, so changing the scheme later is very hard. Choose carefully up front.
- Bank clocks don't jump. Server clocks do, which is a real source of duplicate IDs in time-based schemes.
- A raffle ticket can repeat in a small raffle. A 122-bit random ID practically never does: the numbers involved are beyond everyday intuition.
Quick check
Five questions on this chapter. Pick an answer, then check it.
quiz