Design a unique ID generator
Read first: Consensus and Raft, Partitioning and sharding
Unique ids are easy if you do not also need them roughly sorted in time. A ticket server gives a total order and a single counter, a random 128-bit id needs no coordination and scatters index writes, and a snowflake-shaped 64-bit id encodes time, a worker, and a sequence. None of the three needs a consensus round per value, because any coordination is once per worker lease or once per range.
You need ids that are unique, cheap to mint, and ordered enough to page a list. You do not need a consensus round for every id. If you coordinate at all, you do it once when a worker takes a lease, or once when a worker takes a range, and then the hot path is local arithmetic. A design that sends every id through Raft is a queueing theory mistake wearing a distributed-systems costume.
Requirements
The caller is every service that creates an order, a message, or a file. The human only sees that a list is stable when they scroll it.
Functional requirements:
- An id is unique across the system for as long as you store the row it names.
- Ids from the time-ordered options are monotonic enough to page. “Give me the next page after this id” should work inside one collection.
- The id fits in 64 bits for the ordered options, and you return it as a string. Discord documents this for their snowflake ids: they do not fit in every language’s integer. A language that keeps numbers in floating point will round a large integer, and two ids become one. You will not debug that twice.
- Minting is local on the hot path. No network round trip per id at the rates below.
- Gaps are allowed. Density is not a requirement. An unused id must never be issued twice.
Non-goals:
- A single global sequence with no gaps, shared by every service, that is also fast in every region.
- Cryptographic secrecy as the only requirement. If the id must be unguessable, say so and pick the random option. Do not bolt secrecy onto a counter.
- Using the id as a timestamp you can convert back to civil time for audits. Clocks step. Store a real timestamp column if you need one.
- One id format for every future product. The interview is allowed to end with “these three callers want three formats.”
Assumption: the services that page messages or orders need time order. The service that only needs an idempotency key does not. You will ask which one you are designing before you draw.
Estimation
Assumptions:
- 500 million new ids per day across orders, messages, and files together.
- Peak is 4 times the average, on the hour when jobs and humans both write. That 4 times is an assumption.
- You run several generators for availability even if one could carry the rate.
- A crashed generator may abandon a range. Gaps from that are acceptable. Assumption stated as a product rule, because some businesses think an invoice number cannot skip. This system is not that invoice sequence.
500,000,000 / 86400 = 5,787 ids per second average
500,000,000 / 1e5 = 5,000 ids per second shortcut
peak, 4x assumption = about 23,000 ids per second
A day is 86,400 seconds, so the shortcut of 1e5 is about 14 percent low. One million ids a day would be about 12 per second. You are a few thousand per second average, about 23,000 at the assumed peak. Hold that number against each option. It is high for a chatty per-id round trip and ordinary for a local counter.
Storage of the ids themselves is not a service you size, unless you are the ticket database storing nothing but a counter. The cost shows up in every table that keeps the id as a primary key. A 64-bit id is 8 bytes. A random 128-bit id is 16 bytes. At 500 million rows a day the id column alone is 4 GB a day versus 8 GB a day, and every secondary index pays it again. Over a year that is real and still not the reason to reject the random id. The reason is page locality, below. Bandwidth of the generator is negligible. An id response is a few dozen bytes. At 23,000 per second that is under a megabyte per second.
The conclusion of the estimate: throughput does not force a distributed protocol. Failure and ordering do.
High-level design
flowchart TD
caller[Caller] --> gen[Generator]
gen --> localbits[Clock worker and sequence]
lease[Worker lease] --> gen
ranges[Range table] --> gen
randompath[Random id mint] --> norder[Caller who needs no order]
Three options, one question in front of them. Ask whether two ids must sort in time, and whether that order must be a single total order or only a rough one.
The generator process is boring on purpose. It holds a worker number, the last timestamp it issued, and a sequence. Or it holds a block of integers it was given. Or it reads from the operating system’s random source. The interesting design is which of those three you are in, and what you do when the clock moves backward or the process dies.
Do not draw a consensus group on the arrow from caller to generator. If a lease service exists, it is off to the side, contacted when a process starts and when it renews. A renewal every half minute amortized over millions of ids is not a round trip per id.
Deep dive
A ticket server, including ranges
The simplest correct generator is one integer in one database. update counter set n = n + 1 and return the new value. Uniqueness is the row lock. Order is the integer. At 23,000 per second that row is a single lock being taken 23,000 times, and every region pays a round trip to it. It can work. It is a poor availability story, because a failover of that database stops every issuer, and a failover without fencing can run two counters.
Hand out ranges instead. A generator asks a table for the next block of 10,000 integers. The table does one atomic add of 10,000 and returns the bounds. The generator then issues those 10,000 locally, with no network. Uniqueness holds as long as ranges do not overlap. Order holds across generators if you want it to, because the integers themselves are ordered, though the time at which they are issued is not perfectly ordered. Generator A can still be handing out an older range while generator B has moved on. For an invoice-like sequence that is fine. For “latest message in this chat,” a range that was allocated early and used late sorts before newer work. Know which one you are building.
peak 23,000 ids/s across 4 generators = about 5,750 ids/s each
block of 10,000 / 5,750 = a new block about every 2 seconds
database writes = about 2 per second, not 23,000
That division is the argument. You moved coordination from per id to per range. Two block updates a second is a database that is asleep. Twenty-three thousand single-row increments is a database you will page yourself for.
When a generator crashes with 4,000 ids unused, those integers never appear. The gap is the cost of not leasing the same range to a replacement immediately. You must not give the abandoned tail to someone else while the crashed process might still be alive and issuing. A lease on the range, with a fencing generation, is the safe version. The replacement waits out the lease. This is one lease per range, still not a consensus round per id. The range table itself is one primary. Failover of that primary needs fencing so two primaries cannot allocate the same block. That is ordinary replication hygiene, and it is the only place a leader belongs in this design.
If the product forbids gaps, a ticket server with a single counter and no abandoned ranges is the honest answer, and you accept its outage window. Do not fake gapless and highly available. Those two requirements fight.
A random 128-bit id
A random 128-bit value needs no lease, no clock, and no table. The chance of a collision at a few thousand per second over decades is not a design problem you will hit. Stripe’s guidance uses a UUID as the usual client-generated idempotency key, which is this option in its natural habitat: unguessable enough, coordination-free, no need to sort.
The failure mode is using it as the clustered primary key of a table you read in time order. A B-tree keeps rows in key order on fixed-size pages. Random keys insert into random pages, dirty those pages, and split them. Time-ordered keys insert at the right edge. Indexes pay for that randomness on every write, and a “next page” query cannot use the id at all. You would add a timestamp column and an index on it, and then you have to define what happens when two rows share a timestamp.
Use the random id when the caller needs a handle that does not reveal how many orders you had this morning, and when nothing pages by that handle. Do not use it as the sort key of a message log. Do not “fix” it by also embedding the current time unless you are willing to specify the bit layout, which is the next option, done properly, in 64 bits rather than 128.
The snowflake shape, one published layout
Discord’s developer reference documents a 64-bit id with this layout, and it is the concrete snowflake shape to use in the interview. It is one option, not a law.
- 42 bits of milliseconds since the Discord epoch of 2015-01-01. That epoch as a number is 1420070400000.
- 5 bits of worker.
- 5 bits of process.
- 12 bits of increment inside the millisecond.
2^12 = 4,096 ids per generator per millisecond
4,096 * 1,000 = 4,096,000 ids per second per generator
2^5 * 2^5 = 1,024 generators if every worker and process bit is used
2^42 = 4,398,046,511,104 milliseconds
4,398,046,511,104 / 1000 / 86400 / 365.25 = about 139 years
About 139 years from the start of 2015 runs to about 2154. You will not spend interview time on what happens then. One generator at about four million ids per second covers your assumed peak of 23,000 with two orders of magnitude to spare. You run a second generator so a dead process does not stop the company, not because you are out of sequence bits. You can treat the 10 bits of worker and process as a single generator id if you do not need Discord’s split. Say you are borrowing their published layout, not claiming their deployment.
Inside one millisecond the generator increments the 12-bit sequence. If it exhausts 4,096, it waits for the next millisecond. It does not reuse a timestamp it has already issued. If the clock jumps backward, it refuses to issue and waits until the clock passes the last timestamp it used. A small step costs a short wait. A step of many seconds is an alert, not a silent wrap. Issuing anyway reuses ids or sorts new rows before rows you already returned.
Time order from this layout is per generator, and across generators it is only as good as the clocks. If generator A is 200 ms ahead of generator B, A’s ids sort after B’s even when B’s event happened later in real time, inside that skew. Paging one conversation that has a single writer is fine. A global “everything that just happened” view can be slightly scrambled. If you need a true total order, you are back to one ticket sequence. A wall clock alone is not an id. Two calls in the same millisecond on one machine would collide, and a backward step would reuse time. The sequence bits exist because the clock is not unique. The worker bits exist because the sequence is not global.
Worker ids are the coordination. A table of 1,024 slots, or of however many of the 10 bits you actually use, hands a process a slot with a lease of 60 seconds and a fencing generation. Assumption on those 60 seconds: long enough that a garbage-collection pause does not drop the lease, short enough that a dead process’s slot returns. Renew at 20 seconds. If the process cannot renew, it stops issuing before the lease can be given to someone else. Two processes with the same worker id will collide, and nothing in the bit math will save you. Two processes with different worker ids never need to talk on the hot path.
That lease can be a single primary database. It does not need to be a Raft group unless the lease table’s availability is itself the product. Even if it is Raft, the Raft round happens on renew, not on each id. Clocks are why the wait-on-rollback rule exists. You are not building TrueTime. You are refusing to pretend a stepped clock is still a counter.
Return the id as a decimal string. A double-precision float keeps 53 bits of integer precision, so not every integer above 2^53 is representable. 2^53 is 9,007,199,254,740,992. A 64-bit snowflake crosses that. The bug is silent: the id you read back is a nearby id. Strings do not round.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Single counter | Total order, no gaps if you never skip, trivial to explain | One row in the path of every id, and a hard outage when it fails |
| Ranges of 10,000 | Uniqueness with a couple of database writes per second | Gaps after a crash, and allocation order is not issue order |
| Random 128-bit | No coordination, no clock, hard to guess | No time order, random B-tree inserts |
| Snowflake-shaped 64-bit | Local minting, rough time order, half the width of a random id | Worker-id leases, and clock rollback must wait or you collide |
| Consensus per id | A total order you could have gotten from the counter | A round trip and a majority for a value that did not need one |
Pick from the requirement, not from novelty. Rough time order at this rate is the snowflake shape. A strict sequence with a human afraid of gaps is the counter. An opaque handle is the random id.
Failure modes
- Duplicate worker id. A lease expires and a replacement starts issuing while the old process, paused and then resumed, still has the old timestamp in memory and keeps going. Symptom: two rows, one primary key, the second insert fails or, worse, overwrites. The old process has to stop when renewal fails, and the lease has to outlast a pause. Fencing means an issue call that presents a stale generation is rejected by anyone still listening. On the fully local path nobody is listening, so the generator’s own refusal is the control. Do not keep a “best effort” mode that issues without a lease.
- Clock steps backward. Symptom: a unique-key violation, or a page of messages that reshuffles under a user. Waiting until time passes the last issued timestamp preserves uniqueness. It can stall one generator. A stall is the correct failure. A collision is not.
- Ticket failover without fencing. Two primaries both add 10,000 to what they believe is the current value and hand out the same range. This is split brain on the only coordinated state in the system. One writer, a generation number, the usual primary rules.
- Retry of “give me an id.” Minting is not idempotent. A retry gets a second id, which is correct for “allocate” and wrong for “the id of this order,” if the first call actually created the order and the response was lost. The order API carries an idempotency key, stores the id it already minted, and returns that row on the retry. The generator stays naive. The order service does not.
- Random ids as the clustered key of the hot table. Symptom: write latency climbs as the index stops fitting its dirty pages in cache, and the on-call team adds read replicas, which do not help a write amplification problem. Move the clustered key to a time-ordered id. Keep the random value as a separate unguessable token if you still need one.
- Depending on cross-generator order for authorization or for money. “The higher id happened later” is false across a clock skew window. Use the per-conversation sequence or the ticket integer when the order itself is the correctness condition.
In the interview
First five minutes: do the ids have to sort, and does the sort have to be one global sequence. Then the rate. About 5,000 per second with the shortcut, about 23,000 at a 4 times peak. One machine can mint that locally. Say you will not put Raft on the hot path. Name the option you are actually building. If they said “page a message list,” build the snowflake shape, mention the Discord layout so the bits are real, and mention the ticket range as the thing you would switch to for a gap-sensitive sequence.
Skip a history of every UUID version. A random 128-bit id and a time-ordered 64-bit id are enough contrast. Skip the year-2154 problem after one sentence.
The question that follows is “the clock went backward” or “two machines got the same worker id.” You wait, or you stop issuing, respectively. The tradeoff you admit: snowflake order is not a total order across machines, and a ticket range leaves gaps. You cannot have local minting, a global gapless sequence, and survival of a dead counter all at once.
Check yourself
Using the 42, 5, 5, and 12 bit layout, how many ids can one generator mint per second, and about how long do the time bits last?
The 12 sequence bits are 4,096 ids in one millisecond, which is 4,096,000 per second if the clock keeps up. The 42 time bits are about 4.40e12 milliseconds. Divided by 1,000, then by 86,400, then by 365.25, that is about 139 years from the epoch. The epoch in the Discord layout is the start of 2015, the number 1420070400000. Your peak of about 23,000 per second is far under one generator.
Why is a consensus round per id the wrong design at a few tens of thousands of ids per second?
Each id would wait on a majority and a leader append, so the rate is capped by a distributed log you do not need. Uniqueness comes from a worker id plus a local sequence, or from a preallocated range. Consensus, if it appears at all, belongs on the lease or on failover of the range table. A range of 10,000 turns 23,000 allocations per second into a couple of table writes per second.
The generator's clock jumps backward by 50 milliseconds. What do you do, and what bug are you avoiding?
You stop issuing until the clock passes the last timestamp you already encoded. Issuing in the repeated window either reuses a sequence you have used, which collides, or sorts brand new ids before ids you already handed out. A short wait is the failure mode you want. A unique-key violation in the message table is the one you do not.
A range generator crashes after using 6,000 of a 10,000 id block. Why is leaving a gap safer than handing the tail to a replacement immediately?
The crashed process may still be alive and issuing from the tail. A replacement that receives the same integers will collide with it. Waiting out a lease, then abandoning the tail, keeps uniqueness. The missing numbers are the cost. If the product cannot tolerate a gap, you do not use abandoned ranges. You use one counter and you accept its outage window.
When is a random 128-bit id the right answer, and when does it hurt?
It is the right answer for an unguessable handle that nobody sorts, such as an idempotency key. It hurts as the clustered primary key of a table you insert into and then read in time order. Random keys scatter B-tree writes across leaves, and the id cannot answer the next page. A time-ordered 64-bit id is the one that inserts at the edge and pages.
Based on: Discord developer reference, snowflake ids; Ongaro and Ousterhout, Raft; Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.