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.8 How do you make short IDs with base62?
3 min read+10 XP
At the bank: A long token number is hard to read out over the phone. Writing it with letters as well as digits makes it much shorter.
In the system: Base62 writes a number using 62 symbols: 0-9, a-z, A-Z. Each character carries more information than a decimal digit, so IDs get much shorter, and they're safe in URLs without escaping.
| Characters | Distinct values (62ⁿ) |
|---|---|
| 6 | about 56.8 billion |
| 7 | about 3.5 trillion |
| 11 | about 5.2 × 10¹⁹, more than every 64-bit number (about 1.8 × 10¹⁹) |
So any 64-bit Snowflake ID fits in 11 base62 characters, and a counter-based short link fits in 6 or 7 (Chapter 1's shortener; Chapter 31 in depth). The bookstore can share wishlists as shop.example.com/w/4A8ywU.
Two notes:
- Base62 only rewrites a number; it doesn't make it random. A base62 counter is just as guessable as the number underneath (10.9).
- Some systems drop look-alike characters (
0andO,1,landI) for IDs people type by hand; Base58 does exactly that.
Memory code: "Same number, fewer characters: digits plus both alphabets."