Lesson 7 of 16
10. Unique ID Generation

10.6 What are ticket servers and ID ranges?

3 min read+10 XP

At the bank: Head office gives each branch a book of tokens: branch 1 gets 1 to 1,000, branch 2 gets 1,001 to 2,000. Branches hand them out on their own and only call head office when the book runs out. Or, with two head offices, one hands out odd numbers and the other even ones.

In the system: Keep plain, short, numeric IDs, but share out the counter.

a ticket server handing out blocks of 1,000; two ticket databases using odd and even numbers.

Figure: blocks cut calls to the counter by a thousand times; odd and even lets either counter fail without stopping the other.

  • Blocks (ranges): a ticket server (often one row in a database, updated with an atomic next = next + 1000) hands each app server a block of IDs. The app server uses them from memory and asks for a new block when it runs out. One call per 1,000 IDs. If a server crashes, the rest of its block is simply skipped: gaps are fine, duplicates aren't. (The URL shortener in Chapter 31 uses exactly this.)
  • Step and offset: two ticket databases with auto-increment step 2, one starting at 1 and one at 2, hand out odd and even numbers. Flickr described running ticket servers this way in 2010. Either can fail and the other keeps going.

Trade-offs: IDs stay small and numeric, but they're only roughly in time order (server 3's block may be used before server 1's), and the ticket server is one more thing to run and keep available.

Memory code: "Give each branch a book of numbers."