Lesson 1 of 16
10. Unique ID Generation

The picture to keep in your head

3 min read+10 XP

Every question below is answered twice: first at the bank, so you can picture it, then in the system, so you know exactly how it works. Each answer ends with a memory code to lock it in.

The picture to keep in your head

At a bank branch, a token machine hands out numbers: 1, 2, 3... Because there's one machine, no two customers ever get the same token. Now the bank opens twenty branches, each with its own machine. Each branch's tokens are unique inside that branch, but head office now has twenty customers holding "token 57". To tell them apart, the bank needs a different idea: stamp the branch on each token, hand each branch its own book of numbers, or give out random raffle tickets too long to ever repeat.

That's the problem of unique IDs in a distributed system.

Our running example: the bookstore's order IDs. While there was one database, orders.id simply counted up. Now the bookstore is splitting orders across several databases (sharding, Chapter 15) and many app servers create orders at once. Every order still needs one ID that no other order, anywhere, will ever have.

At the bankIn the system
One token machineAuto-increment in one database
Twenty branches, twenty machinesMany servers or shards creating IDs
A random raffle ticketUUID v4
A token stamped with time, branch and countSnowflake-style ID
A token stamped with the time, then randomUUID v7
Head office giving each branch a book of numbersTicket server handing out ID ranges
A wall clock that gets set backClock skew

the bank's tokens mapped to ID schemes.

Figure: one counter is easy. Many counters must never hand out the same number.