URL Shortener
IDs without a central counter
Before you start
- Open lesson
Requirements
Each worked system starts from a scoped list of verbs and numbers.
Why it matters
Links, orders, messages, and log events need ids that never collide, sort roughly by creation time, and remain cheap under many app servers. Sending every create through one counter couples unrelated services to one row and one machine. Generating an id must require no database round trip or distributed lock, while a retried create must still receive the same logical id.
Example
Design a unique ID service
Many app servers need ids that are unique, roughly time-ordered, and cheap to generate. The shortener is one client.
- Input
- ms = 123456789, machine = 7, sequence = 3
- Output
- 517815303958531
Approach 2 · Resolve the bottleneck
The idea
Keep one example in view
Design a unique ID service
ms = 123456789, machine = 7, sequence = 3→517815303958531
The baseline, One shared counter, is 1 round trip per id · O(1). The better model below keeps this exact input and removes that bottleneck.
Instead of incrementing one shared database row, let machine 7 combine millisecond 123456789 with local sequence 3 into a 64-bit id; the timestamp, machine, and sequence fields prevent collisions without per-create coordination.
Build one 64-bit value from 41 timestamp bits, 10 machine bits, and 12 sequence bits. For millisecond 123456789, machine 7, and sequence 3, shifting each field into place produces 517815303958531. High timestamp bits make values roughly chronological; the machine field separates simultaneous generators.
A machine may issue 4,096 ids in one millisecond, then waits for the next tick. If its clock moves backward, it also waits rather than reuse an earlier timestamp and sequence. Store a client idempotency key with the created resource so a network retry returns the existing id instead of minting another.
Pro
The rest of this is on Pro
The idea above is free. The walkthrough, the cost, and the practice are on Pro.