Unique ID generator
medium 28 minGive every record its own number, from many servers at once.
See it run
Build an ID from its bits, then see what a full millisecond, a wrong clock and a crash do to it.
Operations
Build a Snowflake ID
Time, datacenter, machine and counter become one 64-bit number.
Step 1 of 7
A request
| Bits | Value | |
|---|---|---|
| Time | 41 | - |
| Datacenter | 5 | - |
| Machine | 5 | - |
| Counter | 12 | - |
A new order needs an ID. Nothing is filled in yet.
Step 1: A request
def make(ms, datacenter, machine, counter): i = ms - EPOCH # 41 bits i = i << 5 | datacenter # 5 bits i = i << 5 | machine # 5 bits i = i << 12 | counter # 12 bits return i- Coordination
- Machine number, once
- Weak point
- Clock and number
Time is in the highest bits, so larger means later.
In the real world
The same unique id generator doing real jobs. Pick one and step through it.
Auto-increment on two servers.
Step 1 of 3
Both start at 1
| Server A | Server B | |
|---|---|---|
| Order 1 | ID 1 | ID 1 |
Same ID
Server A and server B each count for themselves.
Step 1: Both start at 1
Common mistakes
The bugs interviewers watch for, with the fix beside each.
One machine number, two processes
criticalThe same millisecond and counter give the same ID.
WrongMACHINE = 7 # in the imageRightMACHINE = leases.take() # renewed while we runIgnoring the last time
criticalAfter a correction of the clock, IDs are repeated.
Wrongnow = clock()counter = 0Rightnow = clock()if now < last: wait_or_refuse()Numbers in JSON
majorJavaScript rounds integers beyond 2^53.
Wrong{"id": 395848345190559745}Right{"id": "395848345190559745"}The ID as a secret
criticalSequential and time-based IDs can be guessed.
WrongGET /photos/1042 # no checkRightphoto = find(1042)if photo.owner != user: return 404
Interview tips
Explain it in one line
- Share out numbers before, or build them from parts nobody else has.
SNOW
- Sortable, No coordination.
- One machine one number, Works at scale.
Good numbers
- 41 bits of ms: 69.7 years.
- 12 bits: 4,096 a millisecond.
- 10 bits: 1,024 machines.
Expect these questions
- What if the clock goes back?
- Who gives out machine numbers?
- Why not UUIDv4?