10. Unique ID Generation
Practice: five levels
Assignments
Five levels. Do them in order. Answers are in "Solutions" at the end, so try first.
Level 1: Think (no code)
A. Which ID scheme fits? One line each.
- A small app with one PostgreSQL database.
- A chat app writing 200,000 messages a second across many servers, shown newest first.
- Password-reset links sent by email.
- Short links for a URL shortener.
- Order IDs across 8 database shards, stored in a
BIGINTcolumn.
B. True or false? Explain.
- "Our order IDs are UUID v4, so we don't need to check that the order belongs to the user."
- "Snowflake IDs from two different machines are exactly in the order the events happened."
- "Auto-increment IDs are always continuous, so the highest ID equals the number of orders."
Level 2: Calculate
- A Snowflake-style layout gives 41 bits of milliseconds. How many years does it last from its epoch? If you only used 39 bits?
- With 12 sequence bits, how many IDs can one machine make per millisecond? Per second? With 1,024 machines, per second in total?
- How many base62 characters do you need for every possible 64-bit value? For 6 billion short links?
- Roughly what's the chance of any collision among one trillion UUID v4s? (Use n² ÷ (2 × 2¹²²).)
Level 3: Build
In Python, write:
- A
Snowflakegenerator with 41 time bits (from your own epoch), 10 machine bits and 12 sequence bits. It must: produce unique, increasing IDs; wait for the next millisecond when 4,096 IDs are used up; and refuse if the clock moves backwards. - A
decode(id)that returns the time, machine and sequence. - A
uuid7(ms)that builds a valid version-7 UUID from a timestamp.
Check that: 10,000 IDs from one generator are unique and sorted; the 4,097th ID in one millisecond lands in the next millisecond; two machines produce different IDs in the same millisecond; a backwards clock raises an error; UUID v7s made at increasing times sort in order and report version 7.
Level 4: Debug
The orders table suddenly reports a duplicate primary key error a few times a week, always on the same server, always around the time its clock is corrected by NTP.
- Find the bug. Walk through how a duplicate is created.
- Fix it.
Level 5: Design
The bookstore is moving to 8 order shards and adding a public "share your wishlist" feature. Design its IDs:
- Order IDs: the scheme, the bit layout or format, and why.
- How machine or shard IDs are assigned and kept unique.
- What happens when a clock jumps backwards.
- Wishlist share links: the format and why.
- How existing auto-increment order IDs (up to about 40 million) keep working.