SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a URL Shortener
  • Design Pastebin
  • Design a Rate Limiter
  • Design a Unique ID Generator
  • Design a Key-Value Store
  • Design a Scalable Parking System (Smart Parking)
System Design/Case Studies/Easy
Interview case study

Design a Unique ID Generator

Make billions of unique, roughly time-ordered IDs on many machines with no central bottleneck.

โฑ 28 min readEasy case studyIntermediate23 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

โ€œDesign a unique ID generator for a distributed system.โ€

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Asking before drawingThe prompt hides the real requirements: how many bits, sortable or not, how many per second, how long it must last, and whether IDs may be guessed. Each answer rules schemes in or out.
Comparing the options honestlyUUID, auto-increment, ticket server, ranges and Snowflake each win somewhere. The interviewer wants the trade-offs, not a memorised answer.
Bit-level thinking and capacity mathsWhy 41 bits, how many years, how many machines, how many IDs per millisecond. Numbers you can derive on the spot show real understanding.
Clocks and failure casesThis is where most candidates fall down. Clocks go backwards and two nodes can share a worker ID. A good answer says what happens and how to stop duplicates.
Knowing the limitsIDs are roughly sorted, not strictly sorted. They leak time. They do not give event order or gap-free numbers. Saying so is a sign of seniority.

TL;DRThe whole design in 60 seconds

Give every server a small generator library that builds a 64-bit number from three parts: when (milliseconds since a custom epoch), who (a worker ID leased to this server) and which one (a counter inside the same millisecond). No server talks to any other server to make an ID, so it takes microseconds and never becomes a bottleneck.

  • Layout: 1 sign bit, 41 bits of time, 10 bits of worker (5 datacentre + 5 worker), 12 bits of counter. 41 bits of milliseconds last about 69.7 years. 1,024 workers. 4,096 IDs per millisecond per worker, or 4.096 million a second.
  • Why not the others: UUID v4 is 128 bits and random, so it does not sort and fragments indexes. One auto-increment database is a bottleneck and a single point of failure.
  • Clock going back: remember the last timestamp. Wait if the gap is a few milliseconds. Refuse and alert if it is bigger. Persist the last timestamp so a restart cannot reuse time.
  • Worker IDs: take a lease from etcd or ZooKeeper, stop generating if the lease might be lost, and never hand the same ID to two live nodes.
  • Limits we state out loud: IDs are roughly time-ordered, not strictly ordered across servers. They reveal creation time. They are not secrets, and they are not gap-free. Send them as strings in JSON.
๐Ÿ’กHow to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
4
6
17
8
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Size of the ID, sortable or not, rate, lifetime, guessability. Say what is out of scope.
2. Estimate3IDs per second, per year, per server, and the years a 41-bit time field lasts.
3. API and data4nextId(), an optional batch call, and the worker lease record.
4. High-level design6Library in each server, lease store, time source, and the databases that use the IDs.
5. Deep dives17Scheme and bit layout, then clocks going backwards, then worker IDs, then how it is deployed.
6. Scale and failures8Duplicates, lease loss, restarts, hot keys, monitoring, leaks.
7. Wrap up3Recap, trade-offs, what you would do next.

Step 1Clarify requirementsabout 4 min

๐Ÿค”
Pause. Try it yourself first
You have 60 seconds. Write down five questions that would change the design. Hint: think about the size of the ID, whether it must sort by time, how many per second, how long it must last, and what happens if two IDs are the same.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Do the IDs have to be numbers, and how big may they be?A 64-bit number fits a database BIGINT and a CPU register. A 128-bit ID does not.Numeric, 64 bits at most, so it fits a BIGINT column.Rules out UUID (128 bits). Points to a Snowflake-style layout.
Must IDs sort by creation time?Sortable IDs make range queries, pagination and index inserts cheaper. It costs a clock.Yes, roughly. Newer IDs should be larger.Put the timestamp in the high bits. Random UUID v4 is out.
Strictly ordered, or roughly ordered?Strict global order needs one sequencer. Rough order is cheap.Roughly is fine: within a few milliseconds is OK.No central counter. Servers generate on their own.
How many IDs per second, on average and at peak?Decides how many bits for the counter, and whether one server can keep up.10,000 a second on average and 100,000 at peak across the company.Tiny for this design. The hard part is correctness, not speed.
How long must the scheme last?Fixes the number of time bits.At least 50 years, and more is better.41 bits of milliseconds give 69.7 years. That is enough.
How many servers will generate IDs, and in how many datacentres?Fixes the number of worker bits.A few hundred servers now, up to about 1,000, in 3 datacentres.10 worker bits (1,024) is enough. Include a datacentre field.
Must the ID be hard to guess, or may it show when it was made?A time-based ID leaks creation time and some volume.It may show time. It must not be the only protection for private data.Authorisation is checked on every object, never by hiding the ID.
Can there ever be gaps or a duplicate? Does anything need gap-free numbers?Gap-free numbering (invoice numbers) is a different, harder problem.Gaps are fine. Duplicates are never fine.No need for a single locked counter. We fail closed on any doubt.
Is this a library inside each service, or a service others call over the network?A network call adds latency and a new point of failure.Either. A library is preferred. Some clients may need an HTTP call.Library first, with a small service as an optional wrapper.
What availability and latency do we need?ID generation is on the critical path of every write.As available as the service that uses it, and well under 1 ms.No remote call on the hot path. Local, in memory generation.

Write the scope on the board

Functional (must do)
  • โ€ขCreate a unique ID on demand, from any server
  • โ€ขIDs are 64-bit integers that fit a BIGINT
  • โ€ขIDs sort roughly by creation time
  • โ€ขOptional batch: get N IDs in one call
  • โ€ขAnyone can read the creation time back out of an ID
Non-functional (how well)
  • โ€ขNever produce the same ID twice, even across restarts and clock errors
  • โ€ขGenerate in under 1 ms (microseconds in-process)
  • โ€ขNo central point on the hot path, so no single point of failure
  • โ€ขLast at least 50 years, handle 100,000 IDs per second at peak
  • โ€ขWork across several datacentres without talking between them
Out of scope (say it)
  • โ€ขStrict global ordering of events (use a logical clock for that)
  • โ€ขGap-free numbers such as invoice numbers
  • โ€ขSecret or unguessable tokens (use a random value for those)
  • โ€ขPublic, user-friendly IDs (we can encode or hide the internal one)
๐ŸŽค
Say it out loud
โ€œLet me confirm the scope. We need unique 64-bit numeric IDs that sort roughly by creation time, generated by many servers across a few datacentres, with no central service on the hot path. I will design for 10,000 IDs a second on average and 100,000 at peak, up to about a thousand generators, and a lifetime of at least 50 years. Gaps are fine, duplicates are never fine. I will leave strict event ordering, gap-free numbers and secret tokens out. Does that match what you have in mind?โ€

Step 2Estimate the scaleabout 3 min

๐Ÿค”
Pause. Try it yourself first
On paper: how many IDs per day and per year? How many per server at peak? How long do 41 bits of milliseconds last? How many IDs can one server make in one millisecond with a 12-bit counter?

Assumptions (say them first)

AssumptionValue
Average IDs per second (whole company)10,000
Peak IDs per second100,000 (10 times the average)
Servers that generate IDs200 now, up to 1,000 later
Datacentres3
Target lifetimeat least 50 years
Layout we will propose1 sign + 41 time + 10 worker + 12 counter = 64 bits
A service for batches (if used) handlesabout 50,000 requests per second per node
Typical request over the networkabout 100 bytes

The arithmetic, line by line

WhatMathsResult
IDs per day (average)10,000 ร— 86,400 s864 million per day
IDs per year864M ร— 365about 315 billion per year
Peak IDs per server100,000 รท 200 servers500 per second per server
What one worker can make2^12 per ms = 4,096 ร— 1,000 ms4.096 million per second
Headroom over our peak per server4,096,000 รท 500about 8,200 times
Years in 41 bits of milliseconds2^41 ms = 2.2 ร— 10^12 ms รท (1,000 ร— 31.6M s per year)about 69.7 years
Workers we can name2^10 = 32 datacentres ร— 32 workers1,024 workers
Space used by IDs in a table (ID column only)315 billion ร— 8 bytesabout 2.5 TB per year (5 TB per year if 16-byte UUIDs)
Bandwidth if clients call a central service at peak100,000 ร— 100 bytesabout 10 MB per second
Nodes for that central service100,000 รท 50,000, then 3 for zones2 needed, so 3
When does an ID pass 2^53 (JavaScript limit)?2^53 รท 2^22 = 2^31 msabout 25 days after the epoch
What the numbers tell us about the design
  • โ€ขSpeed is not the problem. One worker can make 4.096 million IDs a second, thousands of times what a server needs. Correctness is the hard part.
  • โ€ข41 bits is a good fit: 69.7 years from a chosen start date. Pick the epoch close to launch so you spend none of it on the past.
  • โ€ข10 worker bits means 1,024 live generators. That is plenty, but it is a hard limit, so worker IDs must be recycled safely.
  • โ€ขThe ID column alone is terabytes a year. Halving its size (8 bytes against 16) also halves every index that includes it.
  • โ€ขA real ID passes 2^53 within about 25 days of the epoch. From then on JavaScript clients lose digits, so IDs must travel as strings.
๐ŸŽค
Say it out loud
โ€œLet me do the maths. 10,000 IDs a second is 864 million a day and about 315 billion a year. Spread over 200 servers that is only 500 a second per server at peak, while one worker with a 12-bit counter can make 4,096 per millisecond, about 4 million a second, so speed is not a concern. 41 bits of milliseconds last about 69.7 years, and 10 worker bits name 1,024 generators. At 8 bytes the ID column is about 2.5 terabytes a year, half of a 16-byte UUID. The takeaway is that this is a correctness problem: clocks, worker IDs and restarts.โ€

Step 3Define the API and the data modelabout 4 min

๐Ÿค”
Pause. Try it yourself first
What does a caller need? Write the one call you cannot do without. What do you need to store, and where? (Hint: almost nothing.)

Endpoints

MethodPathRequestResponseNotes
GET/v1/idsoptional ?count=N (up to 1,000)200 { ids: ["1088725353078775809"] }Only if a network call is needed. Return IDs as strings, never as JSON numbers. 503 with Retry-After if the node cannot guarantee uniqueness (clock or lease problem).
GET/v1/ids/{id}none200 { createdAt, datacentre, worker, sequence }Optional, for debugging. Pure maths, no storage. Never use it to authorise anything.
POST/v1/workers/lease{ nodeId, hostname }201 { workerId, leaseTtlSeconds, fencingEpoch }Called when a node starts, not per ID. The node must renew before expiry. 409 if no worker ID is free.
PUT/v1/workers/{workerId}/lease{ lastTimestamp }200 { leaseTtlSeconds }Heartbeat. Carries the last timestamp used, so a replacement node can start later than it.

Data model

Part of the IDBitsRangeMeaning
Sign1always 0Keeps the number positive in signed 64-bit types (Java long, SQL BIGINT).
Timestamp410 to 2,199,023,255,551 msMilliseconds since our custom epoch. About 69.7 years.
Datacentre50 to 31Where the node runs.
Worker50 to 31Which node inside that datacentre.
Sequence120 to 4,095Counter inside one millisecond on one worker. Reset to 0 each new millisecond.
Stored in the lease storeHoldsKey
worker leasenodeId, expiry time, last timestamp used, epoch numberworkerId (0 to 1,023)
configcustom epoch, bit widths, the rules for clock errorsone row, read at start
nothing per IDIDs are never stored by the generator-
Making one ID (the arithmetic)
id = ((now_ms - EPOCH) << 22)     // 41 bits of time, shifted past 22 low bits
   | (workerId       << 12)     // 10 bits of worker (datacentre * 32 + worker)
   |  sequence                  // 12 bits, 0..4095

time     = (id >> 22) + EPOCH
workerId = (id >> 12) & 1023
sequence =  id        & 4095
A worked example (64-bit decimal)
epoch   = 2024-01-01T00:00:00Z
now     = epoch + 2,592,000,020 ms   (30 days and 20 ms later)
worker  = datacentre 1, worker 5     -> 1 * 32 + 5 = 37
counter = 1

id = (2,592,000,020 << 22) | (37 << 12) | 1
   = 10,871,636,052,037,633          (about 10.9 quadrillion: above 2^53, so send it as a string)
๐Ÿ“Which store, and why
The generator stores nothing per ID. It needs a tiny, strongly consistent store only for worker leases (etcd or ZooKeeper, or a database row with a transaction). That store is touched when a node starts and then once every few seconds to renew, never per ID. The databases that use the IDs just keep them in a BIGINT primary key. Because the high bits are the time, new rows land near the end of the index, which keeps inserts fast.
๐ŸŽค
Say it out loud
โ€œThe main interface is simply nextId() inside a library, and if we need a network call, GET /v1/ids returns IDs as strings. A node takes a worker lease from etcd when it starts and renews it with a heartbeat that also records the last timestamp it used. The ID itself is one sign bit, 41 bits of time since a custom epoch, 10 bits of worker, and a 12-bit counter. The generator stores nothing per ID, so the only shared state is a small lease table.โ€

Step 4Draw the high-level designabout 6 min

๐Ÿค”
Pause. Try it yourself first
Draw the pieces. Where does an ID get made? What does a node need from outside, and how often? What happens when a node starts?
Unique ID generator: high-level design
๐Ÿ–ฅ๏ธApp serverorder service, tweet service...
โ†’โ†“nextId() in memory
ID library (inside every server)
๐Ÿ•’Clockwall time + monotonic
๐Ÿ”ขGeneratortime | worker | counter
๐Ÿ’พLast-time filesurvives restarts
โ†’โ†“ID
๐Ÿ—„๏ธDatabaseBIGINT primary key
Worker IDs (rare)
๐Ÿ”Lease storeetcd or ZooKeeper, 3 or 5 nodes
on start, then a heartbeat every few seconds
Time source
๐Ÿ“กNTP / chrony3 or more sources, offset alerts
Optional wrapper
๐ŸŒID servicefor clients that cannot embed the library
stateless, same library inside
The hot path is entirely inside the server. The lease store is touched on start and on heartbeat only.
ComponentWhat it does
ID libraryRuns inside each app server. Builds IDs from the clock, the worker ID and a counter. Keeps the last timestamp and refuses to go backwards.
Clock and time sourceThe server clock, kept close to true time by NTP or chrony from several sources. A monotonic clock measures waits.
Last-time recordA small local file (or the lease record) with the highest timestamp used. A restart can never reuse a time that was already used.
Lease storeA small consistent store (etcd, ZooKeeper, or a database row) that hands out worker IDs as leases that expire if not renewed.
ID service (optional)A stateless HTTP or gRPC wrapper around the same library, for clients that cannot embed it. It adds a network hop and a dependency.
DatabasesUse the ID as the primary key. The high time bits keep inserts near the end of the index.
MonitoringTracks clock offset, backwards-jump events, waits, refusals, counter overflows and lease renewals.
Write path (follow one request)
  1. A server starts. It reads its saved last timestamp and asks the lease store for a worker ID (a lease, with an epoch number).
  2. It checks its clock. If the clock reads earlier than the saved last timestamp, it waits, or refuses to start and raises an alert.
  3. A request calls nextId(). The library reads the clock in milliseconds.
  4. Same millisecond as the last ID? Add 1 to the counter. If the counter passes 4,095, spin until the next millisecond.
  5. New millisecond? Set the counter back to 0 and remember the new last timestamp.
  6. Shift and combine: (time - epoch) << 22 | worker << 12 | counter. Return the 64-bit number.
  7. In the background the node renews its lease every few seconds. If it cannot renew before the lease ends, it stops making IDs.
Read path (follow one request)
  1. An ID is read by anyone who has it: a database lookup by primary key, or a client showing it.
  2. To find when it was made: take (id >> 22) and add the custom epoch. No lookup, no storage.
  3. To find where it was made: take (id >> 12) & 1023 and split it into datacentre and worker.
  4. To sort by creation time: sort by the ID itself. It is roughly time-ordered, to the millisecond across servers.
  5. To send it to a browser: format as a string. A JSON number loses digits above 2^53.
๐ŸŽค
Say it out loud
โ€œHere is the picture. Every server has a small ID library with a clock, a generator and a saved last timestamp. It makes IDs in memory, so there is no network call and no single point of failure. The only shared piece is a small lease store like etcd that gives each node a worker ID when it starts and renews it with a heartbeat. NTP keeps the clocks close, and an optional stateless service wraps the same library for clients that cannot embed it. The databases just use the ID as the primary key.โ€

Step 5Deep dive into the hard partsabout 17 min

๐Ÿง The pattern for every deep dive
Problem โ†’ options โ†’ pick one โ†’ say why โ†’ say what it costs. Interviewers score the reasoning more than the choice.
5.1

Choosing the scheme and the bit layout

The problem: We need unique 64-bit IDs from many servers, roughly sorted by time, with no bottleneck. Every obvious answer has a catch, and the interviewer wants to hear the catch.

OptionHow it worksGoodBad
UUID v4 (random)128 random bits (122 usable), made on any machine with no coordination.Nothing to run. Collisions are practically impossible. Easy to start with.128 bits, so it does not fit a BIGINT. Not sortable. Random inserts scatter across a B-tree, causing page splits and a cold index. Twice the index size.
UUID v7 or ULID (time-ordered)48 bits of milliseconds then random bits. Still 128 bits.No coordination. Sorts by time. Good index behaviour.Still 128 bits, so it does not fit a 64-bit column. Needs a trusted clock. Order inside one millisecond is random.
One database auto-incrementA single table with an AUTO_INCREMENT key hands out 1, 2, 3...Strictly increasing, gap-free in normal operation, tiny IDs.Every write waits on one machine, which is a bottleneck and a single point of failure. Hard to span datacentres.
Multi-master auto-increment (step k)k databases, each adding k: server 1 gives 1, 4, 7...; server 2 gives 2, 5, 8...No single machine. Simple to explain.Not sorted by time across servers. Painful to add a server (the step changes). Gaps. Hard across datacentres.
Ticket server (Flickr style)Two databases, one giving odd IDs and one even, that nothing else uses. Clients ask for an ID with a tiny insert.Small IDs, simple, works with ordinary databases.A network call for every ID. The ticket servers are a bottleneck and a dependency. Odd and even sets drift apart.
Range or segment allocationEach server takes a block of, say, 10,000 numbers from a database and hands them out from memory.Few calls to the database. Small IDs. Easy to reason about.Not time-ordered across servers. A crash wastes the rest of a block. The database is still a dependency every few seconds.
Snowflake (time + worker + counter)41 bits of time, 10 bits of worker, 12 bits of counter, built locally.64 bits. Roughly time-sorted. No network call. Millions of IDs per second per node. No central bottleneck.Depends on clocks. Needs a unique worker ID per live node. Only roughly ordered across servers.
Pick
A Snowflake-style 64-bit layout: 1 sign + 41 time + 10 worker + 12 counter

It is the only option that is 64 bits, time-sorted and free of any hot-path coordination. The three fields close three different ways of clashing: different time, different worker, different counter. UUIDs are the right answer when a 128-bit ID is allowed and you want zero setup, and I would say so. A ticket server or ranges are the right answer if you want small, dense numbers and can accept a database dependency.

The numbers fit: 2^41 milliseconds are about 69.7 years, 2^10 gives 1,024 workers, and 2^12 gives 4,096 IDs per millisecond per worker, which is about 4.096 million a second. Our peak is only 500 a second per server, so the counter has thousands of times more room than we need.

Why three fields are enough
๐Ÿ•’Different millisecondtime bits differ
โ†”
๐Ÿ–ฅ๏ธSame ms, different nodeworker bits differ
โ†”
๐Ÿ”ขSame ms, same nodecounter differs
Each field closes one way two IDs could be equal.
Design choiceWhat to say
Custom epochStart counting from the launch date (for example 2024-01-01), not 1970. Using the Unix epoch would already have spent more than 50 of the 69.7 years before the first ID.
Counter overflowIf more than 4,096 IDs are needed in one millisecond on one worker, wait (spin) until the next millisecond. At our rates this is never reached, but it must be handled.
Counter resetReset the counter to 0 at each new millisecond. Optionally start at a random low number so the last bits are not always 0 for low-traffic workers (this helps even sharding by ID modulo N).
Ordering across nodesIDs from different workers in the same millisecond are ordered by worker ID, which is arbitrary. So order is correct to the millisecond, not inside it.
VariantsInstagram: 41 time + 13 shard + 10 counter, so an ID also tells you the database shard. Sonyflake: 39 bits of 10 ms units, 16 bits of machine ID, 8 bits of counter, which lasts about 174 years but makes only 256 IDs per 10 ms.
JSON and JavaScriptAbove 2^53 (about 9 quadrillion) a JavaScript number loses precision. A real ID passes that about 25 days after the epoch. Send IDs as strings.
๐ŸŽค
Say it out loud
โ€œI will compare seven ways. UUID v4 needs nothing, but it is 128 bits, unsortable and bad for indexes. UUID v7 sorts, but is still 128 bits. One auto-increment database is a bottleneck and a single point of failure. Multi-master with a step, ticket servers and ranges avoid that but are not time-ordered or add a database call. I would pick a Snowflake-style 64-bit ID: 41 bits of time since a custom epoch, 10 bits of worker, 12 bits of counter. It is made locally in microseconds, roughly sorted, lasts about 70 years, and one worker can make about four million a second.โ€
5.2

When the clock goes backwards

The problem: The ID contains the time, and the counter resets whenever the millisecond changes. If the wall clock steps back, the generator revisits milliseconds it has already used, restarts the counter at 0, and can produce the same ID a second time. A duplicate primary key is a production incident.

OptionHow it worksGoodBad
Ignore itRead the clock, build the ID.Simplest code.Duplicates, out-of-order IDs, and silent data corruption. Never acceptable.
Wait it outIf now is less than the last timestamp, sleep (using a monotonic clock) until the clock catches up, then continue.No duplicates, IDs stay ordered. Simple.Requests stall for as long as the gap. Fine for 5 ms, a disaster for 5 minutes.
Wait if small, refuse and alert if bigAllow a small gap (for example up to 5 to 10 ms). Above that, return an error, raise an alert, and take the node out of rotation.Bounded delay. A big jump is treated as the serious fault it is.Needs a tuned limit, and callers must handle an error (retry elsewhere).
Keep the last timestamp and carry onUse max(now, last timestamp) as the time and keep counting.No wait and no error. IDs stay unique and ordered.The time field runs ahead of the real clock. A long jump at a high rate can use up 4,096 counter values per millisecond and force a wait anyway.
Change the worker IDOn a big jump, switch to a spare worker ID, so old and new IDs cannot clash.Works even when time is badly wrong.Needs spare worker IDs and a safe way to take one. More moving parts.
Pick
Persist the last timestamp, wait for small jumps, refuse and alert for big ones

The rule is simple: the timestamp in an ID may never go backwards on one worker. Keep the last timestamp in memory and on disk (or in the lease record). On every call compare the clock with it. A small gap (a leap-second smear, an NTP step of a few ms) is waited out, measured with a monotonic clock, which cannot go backwards. A large gap means something is wrong: stop, alert, and let a healthy node take the traffic.

Persisting the last timestamp covers the restart case too. A node that crashes and comes back with a clock that is behind refuses to start, or waits, instead of replaying old milliseconds. Keeping NTP healthy (several sources, small steps, alerts on offset) makes the whole problem rare. Systems like Twitter's Snowflake throw an error when they see a backwards clock, rather than guess.

The core of nextId() (sketch)
now = wallClockMs()
if (now < lastTs) {
    gap = lastTs - now
    if (gap <= MAX_WAIT_MS)  sleepMonotonic(gap);  now = wallClockMs()
    else                     throw ClockMovedBackwards(gap)    // alert, stop serving
}
if (now == lastTs) {
    seq = (seq + 1) & 4095
    if (seq == 0)  now = waitForNextMs(lastTs)      // counter used up this ms
} else {
    seq = 0
}
lastTs = now;  persistLastTsEvery(~1 s)              // restart safety
return ((now - EPOCH) << 22) | (workerId << 12) | seq
CauseWhat happensDefence
NTP steps the clock backWall time jumps back by a few ms (or more after a long drift).Small steps: wait. Prefer slewing (gradual change) over stepping. Alert on large offsets.
Leap secondA second repeats or is smeared. Some systems go back by one second.Use a smeared time source, and treat a one-second jump as a large gap: refuse, do not guess.
VM pause or live migrationThe clock stops, then jumps. Can go backwards after a restore from a snapshot.Refuse until the clock is past the saved last timestamp. Never restore a snapshot with a live worker ID.
Restart with a stale clockMemory is lost, the clock is behind the old last timestamp.Read the saved last timestamp at startup, and wait or refuse until now is greater.
Manual clock changeSomeone sets the date by hand.Same as any big jump. The check does not care why.
๐Ÿ’กTry it
The visualizer below makes the clock step back by up to 20 ms. Run each policy and watch which one produces duplicates.
๐ŸŽค
Say it out loud
โ€œThe danger is that the time is part of the ID and the counter resets each millisecond. If the clock goes back, the generator can revisit a millisecond it already used and make the same ID twice. So the rule is that the timestamp on one worker never goes back. I keep the last timestamp in memory and on disk. For a small gap, a few milliseconds, I wait, using a monotonic clock. For a big gap I refuse, alert, and let healthy nodes take the traffic. At startup I check the clock against the saved timestamp. And I keep NTP healthy so this is rare.โ€
5.3

Giving every node its own worker ID

The problem: Uniqueness depends on no two live generators sharing a worker ID. With only 1,024 values, IDs must be reused when nodes come and go, and a node that was thought dead may still be running.

OptionHow it worksGoodBad
Static configurationPut the worker ID in a config file or environment variable, one per host.No dependency. Easy to start.Human error: copy a config and two nodes share an ID. Breaks with autoscaling and containers that start with identical settings.
Lease from etcd or ZooKeeperOn start, create an ephemeral or leased key such as /workers/17. If it succeeds, you own 17 until the lease expires.Safe against two owners. Freed automatically when a node dies. Works with autoscaling.A dependency at start and on heartbeat. If the store is down, new nodes cannot start.
Database row with a transactionUPDATE workers SET owner = me, expires = now + 30s WHERE id = 17 AND expires < now.No new system if you already have a database. Simple to read.Relies on the database clock and your own care. Easy to get wrong without a fencing epoch.
Derive from the networkUse bits of the IP address or hostname as the worker ID.Zero coordination.Collisions in a big network. IPs get reused. Fragile in containers and NAT.
Pick
A lease from etcd or ZooKeeper, with a heartbeat, a fencing epoch, and a cooldown before reuse

The node takes a lease with a time to live (say 30 seconds) and renews it every 10 seconds. If it cannot renew, it must stop generating IDs before the lease runs out, not after. It must not rely on hearing back from the store. Two things stop the dangerous case, a paused node waking up after its lease went to someone else:

  • A fencing epoch. Each grant carries a growing number. Later steps, such as the last-timestamp record, reject a writer with an old number.
  • A cooldown. A freed worker ID is not handed out again until longer than the biggest clock skew plus the lease time. A new owner then starts with time that is later than anything the old owner could have used, so the same (time, worker, counter) cannot repeat.
DangerHow it happensStop it with
Two live nodes, one worker IDA config copy, or a lease that expired while its owner was paused (a long GC pause or VM freeze).The owner stops before its lease ends. A fencing epoch. A store that grants each ID once.
Reuse right after a crashNode A dies at time T having made IDs up to T. Node B takes the same ID with a clock slightly behind A.Save the last timestamp in the lease record. B must start later than it. Add a cooldown.
Running out of IDs1,024 values, with many short-lived containers.Release on a clean shutdown. Long enough leases. Recycle oldest first. Or widen the worker field and shorten the time field.
Lease store downetcd or ZooKeeper is unreachable.Running nodes keep their lease until its end, then stop. New nodes wait. Run the store with 3 or 5 members.
๐Ÿ“Link to the concept pages
The lease and the epoch are the same ideas as Fencing Tokens, and the store is the kind of thing described in ZooKeeper and etcd.
๐ŸŽค
Say it out loud
โ€œUniqueness depends on no two live nodes sharing a worker ID. I would get it from etcd or ZooKeeper as a lease with a time to live, renewed by a heartbeat. The node must stop making IDs before its lease ends, even if it cannot hear from the store, because a paused node could wake up after its ID went to someone else. I add a fencing epoch and a cooldown before an ID is reused, longer than the largest clock skew, and I save the last timestamp in the lease record, so a new owner always starts later than the old one.โ€
5.4

Library or service, and how the IDs are used

The problem: Making the ID is easy. Deciding where the code runs, how it works across regions, and what the ID does to the database is where designs differ.

OptionHow it worksGoodBad
Library in every serviceEach service embeds the generator and owns a worker ID.Microseconds, no network call, no extra point of failure.Every language needs a library. Every service needs a lease. Many more worker IDs in use.
Central ID serviceA small group of nodes serve GET /ids over the network. Clients call it.One place to run and fix. Works from any language. Few worker IDs.A network hop for every ID (about 1 ms). A shared dependency: if it is down, writes are down.
Hybrid: batches from a serviceClients ask the service for 1,000 IDs at once and use them locally.Cheap on the network. Survives short outages from the batch.IDs are made earlier than they are used, so they are less time-accurate. A crash wastes a batch.
Shard ID in the ID (Instagram style)Reserve bits for the database shard: 41 time + 13 shard + 10 counter.The ID tells you which shard holds the row. No lookup table.A fixed number of logical shards (8,192). Moving a row means a new ID, or a mapping from logical to physical.
Pick
A library inside each service, with an optional stateless service wrapper for clients that cannot embed it

ID generation sits on the path of every write, so it should add as little latency and as few failure modes as possible. A library does that. The wrapper service is the same code behind HTTP, so any client can use it, and because it is stateless, you can run it in every zone. For multiple regions, give each region its own datacentre bits, so regions never need to talk.

A time-ordered primary key also changes the database. New rows land at the end of the index, so inserts are fast and the page cache stays warm. But on a range-partitioned or single-leaf-hot table, all new writes hit the newest partition, a hot spot. To spread them, hash-shard by ID (or by a different key) and keep the time order within each shard.

QuestionAnswer
Do IDs reveal information?Yes: creation time and, with sequential counters, roughly how busy a node is. Do not use the ID as a secret, and check access rights on every request.
Can I sort events by ID?To the millisecond across nodes, yes. Inside a millisecond, and with clock skew, the order is arbitrary. For real causal order use a logical or hybrid clock.
Hash or range shard on the ID?Hash (ID modulo N or consistent hashing) spreads load evenly. Range keeps time-ordered scans cheap but creates a hot newest range.
What about the public ID?Keep the internal ID, and show users an encoded or random public ID (for example a short code) when you must not expose counts.
Migration from auto-increment?Add a new BIGINT column or a mapping table, run both generators for a while, keep old IDs as they are, and make the new generator start above the largest old value.
๐ŸŽค
Say it out loud
โ€œI would embed the generator as a library in each service, so there is no network call and no extra point of failure, and offer a stateless service wrapper for clients that cannot embed it. Each datacentre gets its own bits, so regions never coordinate. I would also mention the effect on the database: a time-ordered key keeps inserts at the end of the index, which is fast, but on a range-partitioned table all new writes hit the newest partition, so I would hash-shard to avoid a hot spot. And IDs reveal creation time, so access is always checked separately.โ€
VisualizerWhen the clock goes backwards: four ways to copeSlide the clock jump up, then switch between ignoring it, waiting, refusing, and keeping the last time. Watch for red duplicate rows. Then paste an ID into the decoder to split it into time, datacentre, worker and counter.
What does the generator do when the clock goes back?
A 64-bit ID is a sign bit, then three fields. The two 5-bit boxes together are the 10-bit worker ID.
0
41 bits: time (ms since our epoch)
5
5
12 bits: counter
1 sign (always 0)5 datacentre (amber)5 worker (purple)2^41 ms is about 69.7 years2^12 = 4,096 IDs per ms per worker
IDs made
56
of 56 requests
Duplicates
10
same ID twice
Out of order
0
smaller than the one before
Refused
0
errors to the caller
Furthest ahead
n/a
ignore does nothing
10 duplicate ID(s). The clock went back 5 ms and revisited milliseconds that were already used. The counter restarted at 0, so the same time, worker and counter came out a second time. Two different orders now share one ID. Look at the red rows.
Requests 37 to 55 (3 before the jump, then the rest). Totals above count all 56. Times are in ms from the start of the run. Two requests arrive each millisecond. The clock steps back before request 40.
#Clock readsIDTime fieldWorkerCounterResult
37+18 ms10871636043649025+18 ms371ok
38+19 ms10871636047843328+19 ms370ok
39+19 ms10871636047843329+19 ms371ok
40+15 ms10871636031066112+15 ms370DUPLICATE
41+15 ms10871636031066113+15 ms371DUPLICATE
42+16 ms10871636035260416+16 ms370DUPLICATE
43+16 ms10871636035260417+16 ms371DUPLICATE
44+17 ms10871636039454720+17 ms370DUPLICATE
45+17 ms10871636039454721+17 ms371DUPLICATE
46+18 ms10871636043649024+18 ms370DUPLICATE
47+18 ms10871636043649025+18 ms371DUPLICATE
48+19 ms10871636047843328+19 ms370DUPLICATE
49+19 ms10871636047843329+19 ms371DUPLICATE
50+20 ms10871636052037632+20 ms370ok
51+20 ms10871636052037633+20 ms371ok
52+21 ms10871636056231936+21 ms370ok
53+21 ms10871636056231937+21 ms371ok
54+22 ms10871636060426240+22 ms370ok
55+22 ms10871636060426241+22 ms371ok
Decode an ID

Paste or type a number to split it back into its fields. It uses our custom epoch (2024-01-01) and exact 64-bit maths.

Time
2024-01-31T00:00:00.020Z
Datacentre
1
Worker
5
Counter
1
Careful: this ID is above 2^53. As a JavaScript number it becomes 10871636052037632, which is not the same ID. Send IDs as strings in JSON.

A simplified, deterministic model: two requests per millisecond, one worker (ID 37), and a single clock step back. A real generator also persists its last timestamp across restarts and uses a monotonic clock for the time it waits.

Step 6Scale, bottlenecks and failuresabout 8 min

๐Ÿค”
Pause. Try it yourself first
Ask yourself: what is the worst thing that can happen to an ID generator? (A duplicate.) Then: what if traffic grows 10 times, a node is paused, the lease store goes down, or a whole datacentre fails?

What breaks first, and the fix

BottleneckFix
More than 4,096 IDs in one millisecond on one workerSpin until the next millisecond, which costs under 1 ms. If it is sustained, spread load over more workers, or give the counter more bits and the time less.
More than 1,024 live generatorsRecycle worker IDs safely, run fewer, larger generators (a small ID service), or move bits from the time field to the worker field.
The lease store at start-up (a deploy restarts 500 nodes at once)Stagger the restarts, retry with random delay, and keep the store at 3 or 5 members. It is touched only on start and heartbeat.
A hot spot in the database from time-ordered keysHash-shard by ID or another key, or add a shard field to the ID. Keep time order inside each shard.
An ID service on the critical path adding latencyPrefer the in-process library. If a service is needed, batch (1,000 IDs per call), run it in every zone, and cache a batch in the client.
Time runs out after about 69.7 yearsPlan the move years ahead: a new layout with a new version bit or a new epoch. Old IDs stay valid and remain comparable by a version field.
Clock quality across datacentresSeveral NTP sources per site, alerts on offset, and a rule to take a node out when its offset grows.

What if a part fails?

FailureHow the design copes
The clock goes backwardsCompare with the last timestamp on every call. Wait for small gaps, refuse and alert for large ones. Never generate with an older time.
A node restarts with a clock behind its old last timestampRead the saved last timestamp at start and wait or refuse until the clock is past it.
Two live nodes share a worker IDPrevent it with leases, a fencing epoch, and a cooldown. Detect it with a unique index on the ID column (the database rejects the second one) and an alert.
The lease store is downRunning nodes continue until their lease ends and then stop. New nodes wait and retry. The store is small and replicated, so this is rare.
A node is paused for 40 seconds (GC or VM freeze)On waking it checks its lease and its clock before every call. A stale lease means stop and re-acquire. The fencing epoch rejects it elsewhere.
A whole datacentre failsEach datacentre has its own bits and nodes, so others carry on. New servers elsewhere take free worker IDs. No cross-datacentre talk is needed for IDs.
The counter overflowsWait for the next millisecond. Count and alert on this, because it means a generator is overloaded.
What to monitor
  • โ€ขClock offset from the NTP source on each node, and any step or backwards jump
  • โ€ขCount of waits, refusals and errors from the generator (should be about zero)
  • โ€ขCounter overflows per second per worker
  • โ€ขLease renewals: age of the last heartbeat and time left on each lease
  • โ€ขDuplicate-key errors from databases on primary keys (the final safety net)
  • โ€ขIDs per second per node, and free worker IDs left
Security and abuse
  • โ€ขIDs are not secrets: never use one as proof of access. Check the caller's rights on every object.
  • โ€ขAn ID shows creation time and, if sequential, roughly how many were made. Use a separate random public ID where that matters.
  • โ€ขProtect the lease store and the generator service with authentication, since a forged worker ID could cause a duplicate.
  • โ€ขDo not accept IDs made by clients. A client could pick an ID that clashes. Generate on the server.
  • โ€ขRate limit the optional ID service, so one caller cannot drain the counter or a batch pool.

Step 7Wrap upabout 3 min

A Snowflake-style generator in a library inside each server. Each ID is a 64-bit number made of 41 bits of time since a custom epoch, 10 bits of worker and 12 bits of counter. It is made in memory in microseconds, with no central bottleneck, and it is roughly sorted by time. Uniqueness depends on two things we protect with care: the timestamp never goes backwards on a worker, and no two live nodes share a worker ID.

Trade-offs you made

DecisionWhat we gainWhat it costs
A 64-bit Snowflake layout instead of a 128-bit UUIDHalf the size, fits a BIGINT, roughly time-sorted, and fast inserts.Needs a clock and a worker ID, which a UUID does not.
Generating locally instead of from a central serviceMicroseconds, no network hop, no single point of failure.Every service embeds a library and needs a worker ID lease.
Refuse on a large backwards jumpNo duplicate ever leaves the node.A node may return errors until the clock is fixed, so callers need retries and failover.
Leases with a cooldown before reuseTwo live nodes cannot share a worker ID.A small dependency on etcd or ZooKeeper at start, and a short delay before an ID is reused.
Roughly sorted, not strictly sortedNo coordination between nodes.Order inside a millisecond and across skewed clocks is arbitrary, so it is wrong for causal ordering.
Time in the high bitsSequential inserts and cheap range scans by time.IDs reveal creation time, and a range-partitioned table gets a hot newest partition.
If we had more time, we wouldโ€ฆ
  • โ€ขMulti-region: confirm the datacentre bits, and test region failover and the lease store across zones.
  • โ€ขA kill-and-pause test: freeze a node for 40 seconds, step its clock back, and check that no duplicate is ever made.
  • โ€ขA plan for the time field running out in about 70 years, and a version bit to allow a new layout.
  • โ€ขA public ID layer (short or random) for anything shown to users, so internal IDs stay hidden.
  • โ€ขA strict-order option, using a hybrid logical clock, for the few cases that need it.
๐ŸŽค
Say it out loud
โ€œTo recap: a Snowflake-style 64-bit ID, with 41 bits of time since a custom epoch, 10 bits of worker and 12 bits of counter, made locally in each server. That gives microsecond latency, no single point of failure, and roughly time-sorted IDs. The two risks are a clock going backwards and two nodes sharing a worker ID, and I handle them with a saved last timestamp, refusing on large jumps, and worker IDs from leases with a fencing epoch and a cooldown. The main trade-offs are that order is only approximate, and that IDs reveal when they were made. With more time I would test node pauses and plan the move away from this layout before the 70 years run out.โ€

Q&ACross-questions (23)

๐Ÿ’กHow to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Why this design, and not another

Expect to defend the choice against the obvious alternatives.

Clocks, workers and failures

The part that separates a memorised answer from an understood one.

Scale, ordering and limits

Security, product and curveballs

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
IDs must be strictly increasing across the whole systemA single sequencer (one leader, or a replicated log) numbers events. Throughput and availability now depend on it. Consider batching, and a standby that takes over with a fencing epoch.
IDs must fit in 53 bits (JavaScript numbers)Shorten the layout: for example 31 bits of seconds, 10 bits of worker, 12 bits of counter, with fewer IDs per second. Or send strings. Say which lifetime and rate you give up.
IDs must be unguessable (for example invite codes)Use a random value from a secure source (at least 128 bits for tokens), and check it in the database. Time ordering is gone, which is the trade.
Tens of thousands of short-lived containersWorker IDs run out. Use a small ID service with batches, widen the worker field, or take worker IDs per pod from a lease with fast recycling and a cooldown.
Several regions that must never talk to each otherGive each region its own datacentre bits and lease store. IDs stay unique with no cross-region traffic. Keep clocks synced inside each region.
The ID must say which database shard holds the rowReserve bits for a logical shard instead of the worker (the Instagram layout), and map logical shards to physical servers.
We cannot trust any server clockTake time from a logical counter: hybrid logical clock, or a central time oracle. Or use ranges from a database. Say what you give up: real-time meaning, or independence.
Gap-free numbers (invoice numbers)A different problem. Use one transactional counter per business series, allocated inside the same transaction as the document, and accept that it limits throughput.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts with UUID or Snowflake without asking anything.Asks about size, sortability, rate and lifetime.Asks the questions that rule options out (64 bits, rough or strict order, guessability, gaps), and says what is out of scope.
EstimationNo numbers, or says it needs to be fast.IDs per second, per year, and bits needed.Derives 69.7 years, 1,024 workers, 4.096 million per second per worker, and shows that speed is not the limit, correctness is.
OptionsKnows one scheme.Compares UUID, auto-increment and Snowflake.Adds ticket servers, ranges, UUID v7, and says when each is the right answer, with the cost of each.
Failure casesNever mentions clocks or duplicate worker IDs.Mentions a backwards clock and a shared worker ID.Explains why duplicates happen, gives wait, refuse and persist rules, and uses leases, epochs and cooldowns.
Limits and trade-offsClaims the IDs are strictly ordered and secure.Says IDs are roughly ordered.States what the IDs cannot do (event order, secrecy, gap-free), the leak of time, the hot partition, and what to use instead.
CommunicationDraws bits in silence.Follows the steps and explains the layout.Summarises each step, checks in, and states which numbers are assumptions.

AvoidCommon mistakes on this question

MistakeDo this instead
Describing Snowflake from memory with no reasonsDerive each field: time for ordering, worker for different nodes, counter for the same millisecond, and the numbers each gives.
Never mentioning clock problemsSay that the time is in the ID, and that a backwards clock can duplicate IDs. Give the wait, refuse and persist rules.
Giving worker IDs from a config file with no safetyUse leases with an expiry and a fencing epoch. Say what happens to a paused node.
Claiming the IDs are strictly orderedSay they are ordered to the millisecond, and name logical or hybrid clocks for real ordering.
Treating the ID as a secretSay it shows creation time and can be guessed. Check access on every request, and use a separate random public ID if needed.
Putting a network call on the hot pathGenerate in the library. Use a service only as a wrapper, with batching.
Returning IDs as JSON numbersSend strings. A JavaScript number loses digits above 2^53, which a real ID passes within weeks.
Forgetting the epoch and the lifetimeUse a custom epoch at launch and state the end date of the layout, about 69.7 years later.

Revise60-second revision sheet

  • โœ”Layout: 1 sign + 41 time + 10 worker (5 datacentre + 5 node) + 12 counter = 64 bits.
  • โœ”Capacity: 2^41 ms is about 69.7 years. 1,024 workers. 4,096 IDs per ms, 4.096 million per second, per worker.
  • โœ”Epoch: use a custom start date at launch, not 1970.
  • โœ”Why not UUID v4: 128 bits, random, no sort, scatters inserts, doubles the index. v7 or ULID fix the sort, not the size.
  • โœ”Why not auto-increment: one writer is a bottleneck and a single point of failure. Ticket servers and ranges help but add a database call.
  • โœ”Clock back: the timestamp may never go down. Wait if small, refuse and alert if big, and persist the last timestamp for restarts.
  • โœ”Worker IDs: leases from etcd or ZooKeeper, stop before the lease ends, fencing epoch, and a cooldown before reuse.
  • โœ”Order: roughly time-sorted, not strictly. For real event order use a hybrid logical clock or a single log.
  • โœ”Limits: IDs leak time, are guessable, and have gaps. Check access separately. Send as strings (above 2^53).
  • โœ”Safety net: a unique index on the ID column, an alert on duplicate-key errors, and chaos tests with clock steps and pauses.

Read these topics next

Distributed Unique ID Generation (Snowflake, UUID)โ†’

The schemes compared in more detail, with a playground.

NTP: Network Time Protocolโ†’

Why clocks step, and how accurate they really are.

Clock Synchronization Problemโ†’

Why two machines never agree on the time.

ZooKeeper and etcdโ†’

The small, reliable stores used to lease worker IDs.

Fencing Tokensโ†’

The growing number that stops a paused owner from doing harm.

Hybrid Logical Clocks (HLC)โ†’

What to use when you need cause before effect.

Lamport Timestampsโ†’

A simple counter that respects cause and effect.

Shard Keys, Hot Shards and Reshardingโ†’

What time-ordered IDs do to a sharded database.

โ† Previous
Design a Rate Limiter
Next โ†’
Design a Key-Value Store