InterviewDryRun
Lesson 3 · 22 min video · free

Design a Unique ID Generator

Every row, message and order in a large system needs an id, and when thousands of machines create them at once, a single database counter stops working. This lesson designs a service that hands out unique, roughly time-ordered 64-bit ids across many data centres, and covers the clock and coordination problems that make it a favourite interview question.

What you will learn

  • Ask whether ids must be numeric, how many bits, how ordered, and how many per second before choosing.
  • Auto-increment does not scale across machines and UUIDs are too long and not ordered.
  • Pack a timestamp, a worker id and a per-millisecond sequence into 64 bits.
  • Generate ids inside each service from a library; coordinate only the worker ids.
  • Never let a clock moving backwards produce duplicates: wait, or refuse.
  • Time-ordered ids leak creation time and volume; scramble them if that matters.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The options, and why most fail
  5. Step 4: Packing 64 bits
  6. Step 5: Generating ids on one machine
  7. Step 6: A service or a library?
  8. Step 7: Handing out worker ids
  9. Step 8: When clocks misbehave
  10. Step 9: Limits and scaling
  11. Step 10: The follow-up questions
  12. Recap

Short on time? Read the answer outline for design a Unique ID Generator.

Practice this question with Max

The question

Welcome to lesson three of the InterviewDryRun system design course. Today we design something that every large system needs and almost nobody thinks about until it breaks: a generator of unique ids.

Every message, order, post and payment needs an id. On a single database, you would let the database count: one, two, three. But once data is split across hundreds of database shards, in several data centres, with thousands of servers creating records at the same moment, a single counter becomes a bottleneck and a single point of failure. So how do you hand out ids that never collide, without everyone asking one machine?

Max asks

“Design a service that hands out unique, roughly time-ordered sixty-four-bit ids across many data centres.”

That is how Max, our AI interviewer, asks it. Three phrases in that sentence carry the whole design. Unique: never two the same, ever. Roughly time-ordered: an id made later should usually be bigger. And sixty-four bits: they must fit in a standard long integer, which rules out some popular answers straight away.

This question is smaller than most, so interviewers go deeper. Expect to be asked about every bit of the id, about clocks that jump backwards, and about what happens when a machine restarts. We will cover requirements, the options and why most fail, the sixty-four-bit layout, how machines get their worker numbers, the clock problems, scaling, and the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    UniqueNo two ids are ever equal, across all data centres
  2. 02
    Numeric, 64 bitsFits a long integer and a database primary key
  3. 03
    Roughly time-orderedSorting by id sorts by creation time, to the millisecond
  4. 04
    Generated anywhereEvery service and data centre can make ids

Start with requirements. This question has a short list, so be precise about each one, and confirm each with the interviewer.

Unique is the non-negotiable one. A duplicate id can merge two customers' orders or overwrite somebody's message. So we will treat any design that can produce a duplicate, even once a year, as broken.

Numeric and sixty-four bits. Ask why. The usual reasons are that the id is a database primary key, where a compact integer makes indexes smaller and faster, and that sixty-four bits fit in a native integer in every language. Note that some languages lose precision above fifty-three bits when numbers become floating point, so ids are often sent to browsers as strings. Mentioning that shows practical experience.

Roughly time-ordered. Ask how rough. Usually the answer is: ids made in later milliseconds should be larger, but within the same millisecond, across different machines, order does not matter. That matters a lot, because sorting a chat history or a feed by id is then the same as sorting by time, and database indexes on the id stay append-only, which is fast.

And generated anywhere: every data centre must keep making ids even if it is cut off from all the others. That rules out any design where each id needs a call to one central place.

Non-functional requirements
  1. 01
    High throughputTens of thousands of ids a second per machine
  2. 02
    Low latencyMicroseconds, ideally no network call
  3. 03
    Highly availableMaking an id must never be the reason a write fails
  4. 04
    Long lifetimeDecades before the id space runs out

For the qualities: how many ids a second, and how fast? Assume tens of thousands per second per machine, millions in total, and that generating one should take microseconds. If every insert in the company waits on an id, the id generator's latency is added to everything.

Then availability, because if id generation fails, every write fails. And lifetime: ask how many years the ids must last. We will design for many decades, because changing the id format of a live system is one of the most painful migrations there is.

Step 2: Back-of-the-envelope estimates

How big is the problem?
Ids per second10 millionat peak, across the company
Machines making idsup to 1,000across all data centres
Per machine10,000 / s10 per millisecond
64-bit space1.8 x 10^19about 18 quintillion
Ids in 50 years1.6 x 10^16at 10 million a second

A quick sizing tells us whether sixty-four bits are even enough.

Say ten million ids a second at peak, across up to a thousand machines. That is ten thousand a second per machine, or ten per millisecond. Remember that number: per machine, per millisecond. It will decide how many bits we need for a counter.

Sixty-four bits give about eighteen quintillion values. Ten million a second for fifty years is about sixteen quadrillion ids, roughly a thousandth of the space. So the space is big enough in total. The challenge is not the number of ids. It is splitting the bits so that machines never need to talk to each other, and so that the ids sort by time.

There is no storage to estimate here, because the generator stores almost nothing. That is unusual for an interview question, and worth saying: the design is all about coordination, not data.

Also check how many bits the timestamp needs to cover the lifetime we want. Milliseconds for fifty years is about one and a half trillion, which needs forty-one bits. That leaves twenty-two bits for everything else, the worker and the counter. So before we even design the layout, the arithmetic has told us how much room we have to play with.

Step 3: The options, and why most fail

Ways to make unique ids
ApproachGoodWhy it fails here
Database auto-incrementsimple, orderedone writer: a bottleneck and a single point
Auto-increment with stepseveral writershard to add servers; not time-ordered
UUID (random, 128 bits)no coordination at all128 bits, not ordered
Central ticket serversimple, orderednetwork call per id; single point
Timestamp + worker + sequence64 bits, ordered, localneeds worker ids and sane clocks

Before the answer, walk through the obvious options and say why each falls short. Interviewers want to see that you chose the design, not that you memorised it.

First, the database's auto-increment column. It is ordered and simple, but every id comes from one database. At ten million a second that one database is a bottleneck, and if it is down, nobody can create anything. And with many shards, each shard has its own counter, so ids collide across shards.

A classic patch: run several databases, and have each one count with a step. With two servers, one hands out odd numbers and the other even numbers. It works, but adding a third server means changing the step everywhere, and the ids are no longer in time order, because one server can run far ahead of the other.

Second, the random UUID. Every machine makes one locally with no coordination, and collisions are so unlikely that we can ignore them. It would be perfect, except that it is one hundred and twenty-eight bits, which breaks our sixty-four-bit requirement, and random ids are not ordered, so database indexes get random inserts all over the place, which is slow. Some newer UUID versions put a timestamp first and are ordered, which is worth a mention, but they are still a hundred and twenty-eight bits.

Third, a central ticket server: one service with a counter, and everyone asks it for the next number. It is ordered, but every id now costs a network round trip, and it is a single point of failure. You can soften this by handing out blocks of a thousand ids at a time, which is a good idea we will reuse later, but cross-data-centre ordering is still poor.

And the fourth: build the id from parts. A timestamp, plus the id of the machine making it, plus a small counter for ids made in the same millisecond. Each machine makes ids on its own, they sort by time because the timestamp comes first, and they fit in sixty-four bits. This is the design we will build. Its only needs are that every machine has a unique worker number, and that clocks behave.

Notice the pattern in this comparison. Every option that gives perfect order needs a single point that everyone talks to. Every option that needs no coordination gives up order or size. The design we are about to build sits in the middle: order to the millisecond, coordination only at start-up. Stating the pattern like this shows the interviewer you see the underlying trade-off, which is the real skill being tested.

Step 4: Packing 64 bits

The 64-bit layout
BitsFieldGives us
1sign bit, always 0ids stay positive
41milliseconds since our epochabout 69 years
5data centre id32 data centres
5machine id in that centre32 machines each, 1,024 in all
12sequence within the millisecond4,096 ids per ms per machine

Now the layout. Draw it as a row of sixty-four boxes and split it into fields. The interviewer will want you to justify every number, so let us go field by field.

The top bit stays zero. That keeps the id positive in languages with signed integers, so ids always sort correctly and never show up as negative numbers in somebody's dashboard.

Then forty-one bits of time, in milliseconds. Two to the power forty-one milliseconds is about sixty-nine years. But not since nineteen seventy: we count from our own custom epoch, say the day the system launches. Counting from nineteen seventy would waste more than fifty years of the space on dates before our company existed.

Next, ten bits to identify the machine. Here they are split into five bits for the data centre and five for the machine within it, so thirty-two data centres of thirty-two machines, one thousand and twenty-four generators in all. The split is a choice: if you have three data centres and thousands of machines each, use two bits and eight bits instead. Say that it is tunable.

And the last twelve bits are a sequence number that counts ids made by this machine within the same millisecond, from zero to four thousand and ninety-five. Our estimate said ten per millisecond per machine, so four thousand and ninety-six gives us hundreds of times the headroom.

Making one id
id = (now_ms - EPOCH) << 22
   | datacenter_id   << 17
   | machine_id      << 12
   | sequence

// read the parts back out
time_ms = (id >> 22) + EPOCH
machine = (id >> 12) & 0x3FF

Building the id is just shifting each field into place and joining them. And this reveals a nice property: you can read the creation time and the machine straight out of any id. That is extremely handy when debugging, because an id in a log line tells you when and where the record was made, without any lookup.

Why is uniqueness guaranteed? Two ids from different machines differ in the machine bits. Two ids from the same machine in different milliseconds differ in the time bits. Two ids from the same machine in the same millisecond differ in the sequence. So as long as each machine id belongs to exactly one running process, and time on each machine never goes backwards, two ids can never be equal. Those two conditions are exactly where the rest of the interview goes.

Step 5: Generating ids on one machine

The generator loop
lock:
  now = current_millis()
  if now < last:  handle clock going backwards
  if now == last:
      seq = (seq + 1) & 4095
      if seq == 0:            // 4,096 used this ms
          now = wait_until(last + 1)
  else:
      seq = 0
  last = now
  return make_id(now, worker, seq)

Here is the generator on a single machine. It remembers the last millisecond it used and the sequence within it. When asked for an id, it reads the clock. If we are still in the same millisecond, it increments the sequence. If the clock has moved on, it resets the sequence to zero.

If the sequence wraps around, meaning we made four thousand and ninety-six ids in one millisecond, the generator simply waits for the next millisecond. That wait is less than a millisecond, it is rare at our rates, and it keeps uniqueness guaranteed. Say this explicitly, because interviewers often ask what happens when the sequence overflows.

The whole thing runs under a lock, or as a single atomic compare-and-set on one sixty-four-bit word that holds the last time and the sequence together. It costs nanoseconds. A single machine can produce millions of ids a second this way, far beyond what we need.

One small refinement: instead of always starting the sequence at zero in each new millisecond, some designs start at a random small number. With very low traffic, every id would otherwise end in zero, which can create uneven distribution if the id is later used to pick a shard. It is a detail, but it shows you have thought about how the id is used downstream.

Step 6: A service or a library?

Two ways to deploy it
leaseleaseSERVICEOrder serviceid library insideSERVICEMessage serviceid library insideSTOREWorker id registryleases, strongly consistentSERVICEId serviceoptional, for others

The question says a service, but there is a real choice here. We could run a dedicated id service that other services call over the network. Or we could ship the generator as a library that every service runs inside its own process.

I would choose the library for the hot path. Generating an id becomes a function call, taking microseconds, with no network and nothing to go down. The only shared thing is a small registry that hands out worker ids, which each process contacts once at start-up, not once per id. So the only coordination in the whole system happens when a process starts.

A thin network service is still useful for clients that cannot run the library, say a script in another language. It is just another process that holds a worker id and answers requests. And to make it fast, clients can ask for a batch of ids at once.

Say the trade-off clearly. The library puts the logic in every service, so a bug fix means updating every service, and every team has to deploy it correctly. The service centralises the logic but adds a network call and a dependency to every write. For ten million ids a second, the library wins.

If the interviewer insists on a network service, make it cheap with batching. A client asks for a thousand ids at once and keeps them in memory, handing them out locally. One round trip now covers a thousand writes. The price is that if the client crashes, its unused ids are lost forever, and that is perfectly fine: nobody needs ids to be gapless. Say that explicitly, because gapless ids are a requirement people sometimes assume without asking, and it is far more expensive to guarantee.

Step 7: Handing out worker ids

Getting a unique worker id
  1. 01
    Static configSimple, but humans make mistakes
  2. 02
    Lease from a registryClaim a free id with a time-limited lease
  3. 03
    Renew while aliveHeartbeat every few seconds
  4. 04
    Stop before it expiresNever make ids on an expired lease

Uniqueness depends on no two running processes sharing a worker id. How do processes get one? The simplest answer is configuration: each machine is given a number. That works for a small fleet, but with autoscaling and containers that come and go, someone eventually copies a config file, and you have two machines with the same id producing duplicates silently.

The robust answer is a lease. On start-up, a process asks a small, strongly consistent registry, the kind of coordination store that uses a consensus protocol, to claim a free worker id from zero to one thousand and twenty-three. The claim is a conditional write, so two processes cannot claim the same number. And it comes with a lease, say thirty seconds.

The process renews its lease every few seconds while it is alive. If it dies, the lease expires and the number becomes free for a new process. And the critical rule: if a process cannot renew its lease, for example because it is cut off from the registry, it must stop generating ids before the lease runs out. Otherwise the registry could give its number to someone else while it is still using it.

Notice the registry is not on the request path. If it is down, processes that already hold leases keep working. Only new processes cannot start. That is the kind of failure we can live with, and you should say so.

An interviewer might ask: why not just use the machine's network address as the worker id? With ten bits, we would have to squeeze an address into a thousand values, and two machines can end up with the same squeezed value. Hashing does not give uniqueness. Leasing does. That is a useful general principle to state: when uniqueness matters, allocate, do not hash.

Step 8: When clocks misbehave

Clock problems and what to do
ProblemDangerResponse
Clock steps back 5 msreuse old timestamps: duplicateswait until it catches up
Clock steps back 10 swaiting stalls writesrefuse, alert, take node out
Restart with clock behindlast time is lostpersist a high-water mark
Clocks differ across machinesids slightly out of orderfine: only rough order promised

Now the part interviewers love. Our uniqueness depends on time never going backwards on a machine. But clocks do go backwards. Time synchronisation adjusts them, virtual machines get paused and resumed, and occasionally someone sets a clock by hand.

If the clock steps back a few milliseconds, our generator would reuse timestamps it already used. With the sequence starting over, it could produce exact duplicates. The fix is simple: the generator remembers the last timestamp, and if the clock is behind it, it waits until the clock catches up. A few milliseconds of waiting is harmless.

If the clock jumps back by seconds, waiting would freeze every write on that machine. So above a threshold, the generator refuses to make ids, raises an alert, and the health check takes the machine out of service until the clock is fixed. A refused write is retried elsewhere. A duplicate id is a silent data corruption. That trade-off should be said out loud.

A restart is the sneaky case. The process forgets the last timestamp it used. If the machine comes back with its clock behind, nothing in memory warns us. So every few seconds, the generator can record a high-water mark of time, either locally or with its lease, and on start-up it refuses to issue ids until the clock is past that mark. A fresh lease with a new worker id solves it too, which is one more reason to prefer leases.

And across machines, clocks are never exactly the same. Two machines a few milliseconds apart will produce ids that are slightly out of order relative to each other. That is fine, because we only promised rough ordering. Make sure you say this: if the interviewer needs strict global ordering, sixty-four-bit ids from independent machines cannot provide it, and you would need a single sequencer, with all the costs we rejected earlier.

Also configure time synchronisation to slew rather than step where possible. Slewing slows or speeds the clock slightly until it is correct, instead of jumping, which means time on a machine never moves backwards in the first place. It does not replace the checks, but it makes them rare.

Step 9: Limits and scaling

When the layout runs out
  1. 01
    More than 4,096 per msWait, or give a busy service two worker ids
  2. 02
    More than 1,024 workersMove bits from sequence to machine id
  3. 03
    Year 69Plan the next epoch long before
  4. 04
    Hot shard from ordered idsDo not shard by raw id; hash it first

Every fixed layout has limits, and a good answer says what they are. If one process needs more than four thousand and ninety-six ids per millisecond, it waits, or it holds two worker ids and alternates between them.

If we need more than a thousand and twenty-four generators, we take bits from the sequence, which has far more room than we need, and give them to the machine id. Twelve bits of sequence and ten of machine could become ten and twelve: four thousand workers, each still making a thousand ids per millisecond.

At sixty-nine years, the timestamp runs out. That is far away, but the custom epoch means the clock started at launch, not at nineteen seventy, so we got the full sixty-nine. Mention it, and say that a format version in reserved bits would make the eventual migration easier.

And one trap downstream: ordered ids are terrible shard keys if you split data into ranges of ids, because all new writes go to the newest range, which becomes a hot spot. If data is sharded by id, hash the id first, or shard by something else, like the user. This is a nice point to raise, because it connects the id design to the database design.

Step 10: The follow-up questions

Max asks

“A virtual machine is paused for thirty seconds and resumed. What does your generator do?”

When it resumes, its clock may jump forward, which is harmless, or if time sync corrects it, may later step back. Forward is fine. Backwards beyond our threshold makes it refuse and alert. The bigger risk is the lease: thirty seconds paused can mean the lease expired and the registry gave our worker id to another process. So on every resume, and before every batch, the generator checks that its lease is still valid, and if not, it stops and claims a new id.

Max asks

“Your ids reveal when an order was made and roughly how many orders you take per day. Is that a problem?”

It can be. Anyone who sees two order ids can subtract them and estimate our volume, which competitors would love. If that matters, keep the time-ordered id internally, and show users a different identifier: either a separate random public id, or the internal id passed through a reversible scramble with a secret key. The database keeps fast, ordered keys, and the outside world sees nothing useful.

Max asks

“Could you make ids strictly increasing across all data centres?”

Not without a single source of order, which means a network round trip to one place for every id, or to a consensus group. That costs latency, and the system stops making ids when that place is unreachable. So I would push back: ask what the ordering is for. Usually it is for sorting a conversation or a feed, where order within one conversation is what matters, and that can be guaranteed by giving each conversation its own sequence number instead.

Max asks

“How would you test that your generator never produces a duplicate?”

Three ways. A unit test that runs many threads in one process and checks every id is unique, including across a forced sequence overflow. A test that fakes the clock moving backwards by small and large amounts, and checks the generator waits or refuses. And in production, a cheap check: every service can log the worker id and lease it started with, and an alert fires if two live processes ever report the same worker id. Duplicates are silent, so you need to look for them on purpose.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsUnique, 64 bits, roughly ordered, made anywhere
  2. 02
    5 to 10: estimates10 per ms per machine; 64 bits is plenty in total
  3. 03
    10 to 20: optionsAuto-increment, steps, UUIDs, ticket server: why not
  4. 04
    20 to 35: the design41 time, 10 worker, 12 sequence; library; leases
  5. 05
    35 to 45: clocks and limitsBackwards clocks, restarts, overflow, privacy

Here is the plan for forty-five minutes. Five minutes of requirements: unique, sixty-four bits, roughly time-ordered, and made anywhere without a central call. Five minutes of numbers: ten ids per millisecond per machine, and a space that is huge in total.

Ten minutes on the options, saying exactly why auto-increment, stepped counters, UUIDs and a ticket server each fall short. That sets up the design so it feels like the obvious answer rather than a memorised one.

Fifteen minutes on the design itself: forty-one bits of time from a custom epoch, ten of worker id, twelve of sequence; a library in every service; worker ids from a leasing registry. And the final ten on clocks going backwards, restarts, sequence overflow and what the ids reveal. If you keep coming back to the two conditions for uniqueness, unique workers and monotonic time, the interviewer will see that you understand why it works, not just how.

The bit layout is easy to memorise. Defending it while someone asks what happens when the clock jumps back is the part that needs practice. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson four.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.