Make billions of unique, roughly time-ordered IDs on many machines with no central bottleneck.
โDesign a unique ID generator for a distributed system.โ
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Asking before drawing | The 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 honestly | UUID, 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 maths | Why 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 cases | This 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 limits | IDs 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. |
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.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Size of the ID, sortable or not, rate, lifetime, guessability. Say what is out of scope. |
| 2. Estimate | 3 | IDs per second, per year, per server, and the years a 41-bit time field lasts. |
| 3. API and data | 4 | nextId(), an optional batch call, and the worker lease record. |
| 4. High-level design | 6 | Library in each server, lease store, time source, and the databases that use the IDs. |
| 5. Deep dives | 17 | Scheme and bit layout, then clocks going backwards, then worker IDs, then how it is deployed. |
| 6. Scale and failures | 8 | Duplicates, lease loss, restarts, hot keys, monitoring, leaks. |
| 7. Wrap up | 3 | Recap, trade-offs, what you would do next. |
| Ask | Why you ask it | Typical answer | How 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. |
| Assumption | Value |
|---|---|
| Average IDs per second (whole company) | 10,000 |
| Peak IDs per second | 100,000 (10 times the average) |
| Servers that generate IDs | 200 now, up to 1,000 later |
| Datacentres | 3 |
| Target lifetime | at least 50 years |
| Layout we will propose | 1 sign + 41 time + 10 worker + 12 counter = 64 bits |
| A service for batches (if used) handles | about 50,000 requests per second per node |
| Typical request over the network | about 100 bytes |
| What | Maths | Result |
|---|---|---|
| IDs per day (average) | 10,000 ร 86,400 s | 864 million per day |
| IDs per year | 864M ร 365 | about 315 billion per year |
| Peak IDs per server | 100,000 รท 200 servers | 500 per second per server |
| What one worker can make | 2^12 per ms = 4,096 ร 1,000 ms | 4.096 million per second |
| Headroom over our peak per server | 4,096,000 รท 500 | about 8,200 times |
| Years in 41 bits of milliseconds | 2^41 ms = 2.2 ร 10^12 ms รท (1,000 ร 31.6M s per year) | about 69.7 years |
| Workers we can name | 2^10 = 32 datacentres ร 32 workers | 1,024 workers |
| Space used by IDs in a table (ID column only) | 315 billion ร 8 bytes | about 2.5 TB per year (5 TB per year if 16-byte UUIDs) |
| Bandwidth if clients call a central service at peak | 100,000 ร 100 bytes | about 10 MB per second |
| Nodes for that central service | 100,000 รท 50,000, then 3 for zones | 2 needed, so 3 |
| When does an ID pass 2^53 (JavaScript limit)? | 2^53 รท 2^22 = 2^31 ms | about 25 days after the epoch |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| GET | /v1/ids | optional ?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} | none | 200 { 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. |
| Part of the ID | Bits | Range | Meaning |
|---|---|---|---|
| Sign | 1 | always 0 | Keeps the number positive in signed 64-bit types (Java long, SQL BIGINT). |
| Timestamp | 41 | 0 to 2,199,023,255,551 ms | Milliseconds since our custom epoch. About 69.7 years. |
| Datacentre | 5 | 0 to 31 | Where the node runs. |
| Worker | 5 | 0 to 31 | Which node inside that datacentre. |
| Sequence | 12 | 0 to 4,095 | Counter inside one millisecond on one worker. Reset to 0 each new millisecond. |
| Stored in the lease store | Holds | Key |
|---|---|---|
| worker lease | nodeId, expiry time, last timestamp used, epoch number | workerId (0 to 1,023) |
| config | custom epoch, bit widths, the rules for clock errors | one row, read at start |
| nothing per ID | IDs are never stored by the generator | - |
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
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)
| Component | What it does |
|---|---|
| ID library | Runs 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 source | The server clock, kept close to true time by NTP or chrony from several sources. A monotonic clock measures waits. |
| Last-time record | A small local file (or the lease record) with the highest timestamp used. A restart can never reuse a time that was already used. |
| Lease store | A 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. |
| Databases | Use the ID as the primary key. The high time bits keep inserts near the end of the index. |
| Monitoring | Tracks clock offset, backwards-jump events, waits, refusals, counter overflows and lease renewals. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| 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-increment | A 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 allocation | Each 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. |
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.
| Design choice | What to say |
|---|---|
| Custom epoch | Start 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 overflow | If 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 reset | Reset 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 nodes | IDs 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. |
| Variants | Instagram: 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 JavaScript | Above 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. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Ignore it | Read the clock, build the ID. | Simplest code. | Duplicates, out-of-order IDs, and silent data corruption. Never acceptable. |
| Wait it out | If 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 big | Allow 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 on | Use 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 ID | On 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. |
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.
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| Cause | What happens | Defence |
|---|---|---|
| NTP steps the clock back | Wall 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 second | A 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 migration | The 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 clock | Memory 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 change | Someone sets the date by hand. | Same as any big jump. The check does not care why. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Static configuration | Put 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 ZooKeeper | On 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 transaction | UPDATE 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 network | Use 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. |
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:
| Danger | How it happens | Stop it with |
|---|---|---|
| Two live nodes, one worker ID | A 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 crash | Node 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 IDs | 1,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 down | etcd 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. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Library in every service | Each 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 service | A 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 service | Clients 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. |
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.
| Question | Answer |
|---|---|
| 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. |
| # | Clock reads | ID | Time field | Worker | Counter | Result |
|---|---|---|---|---|---|---|
| 37 | +18 ms | 10871636043649025 | +18 ms | 37 | 1 | ok |
| 38 | +19 ms | 10871636047843328 | +19 ms | 37 | 0 | ok |
| 39 | +19 ms | 10871636047843329 | +19 ms | 37 | 1 | ok |
| 40 | +15 ms | 10871636031066112 | +15 ms | 37 | 0 | DUPLICATE |
| 41 | +15 ms | 10871636031066113 | +15 ms | 37 | 1 | DUPLICATE |
| 42 | +16 ms | 10871636035260416 | +16 ms | 37 | 0 | DUPLICATE |
| 43 | +16 ms | 10871636035260417 | +16 ms | 37 | 1 | DUPLICATE |
| 44 | +17 ms | 10871636039454720 | +17 ms | 37 | 0 | DUPLICATE |
| 45 | +17 ms | 10871636039454721 | +17 ms | 37 | 1 | DUPLICATE |
| 46 | +18 ms | 10871636043649024 | +18 ms | 37 | 0 | DUPLICATE |
| 47 | +18 ms | 10871636043649025 | +18 ms | 37 | 1 | DUPLICATE |
| 48 | +19 ms | 10871636047843328 | +19 ms | 37 | 0 | DUPLICATE |
| 49 | +19 ms | 10871636047843329 | +19 ms | 37 | 1 | DUPLICATE |
| 50 | +20 ms | 10871636052037632 | +20 ms | 37 | 0 | ok |
| 51 | +20 ms | 10871636052037633 | +20 ms | 37 | 1 | ok |
| 52 | +21 ms | 10871636056231936 | +21 ms | 37 | 0 | ok |
| 53 | +21 ms | 10871636056231937 | +21 ms | 37 | 1 | ok |
| 54 | +22 ms | 10871636060426240 | +22 ms | 37 | 0 | ok |
| 55 | +22 ms | 10871636060426241 | +22 ms | 37 | 1 | ok |
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.
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.
| Bottleneck | Fix |
|---|---|
| More than 4,096 IDs in one millisecond on one worker | Spin 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 generators | Recycle 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 keys | Hash-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 latency | Prefer 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 years | Plan 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 datacentres | Several NTP sources per site, alerts on offset, and a rule to take a node out when its offset grows. |
| Failure | How the design copes |
|---|---|
| The clock goes backwards | Compare 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 timestamp | Read the saved last timestamp at start and wait or refuse until the clock is past it. |
| Two live nodes share a worker ID | Prevent 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 down | Running 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 fails | Each 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 overflows | Wait for the next millisecond. Count and alert on this, because it means a generator is overloaded. |
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.
| Decision | What we gain | What it costs |
|---|---|---|
| A 64-bit Snowflake layout instead of a 128-bit UUID | Half 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 service | Microseconds, no network hop, no single point of failure. | Every service embeds a library and needs a worker ID lease. |
| Refuse on a large backwards jump | No 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 reuse | Two 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 sorted | No coordination between nodes. | Order inside a millisecond and across skewed clocks is arbitrary, so it is wrong for causal ordering. |
| Time in the high bits | Sequential inserts and cheap range scans by time. | IDs reveal creation time, and a range-partitioned table gets a hot newest partition. |
Expect to defend the choice against the obvious alternatives.
The part that separates a memorised answer from an understood one.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| IDs must be strictly increasing across the whole system | A 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 containers | Worker 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 other | Give 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 row | Reserve bits for a logical shard instead of the worker (the Instagram layout), and map logical shards to physical servers. |
| We cannot trust any server clock | Take 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. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts 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. |
| Estimation | No 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. |
| Options | Knows 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 cases | Never 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-offs | Claims 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. |
| Communication | Draws bits in silence. | Follows the steps and explains the layout. | Summarises each step, checks in, and states which numbers are assumptions. |
| Mistake | Do this instead |
|---|---|
| Describing Snowflake from memory with no reasons | Derive each field: time for ordering, worker for different nodes, counter for the same millisecond, and the numbers each gives. |
| Never mentioning clock problems | Say 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 safety | Use leases with an expiry and a fencing epoch. Say what happens to a paused node. |
| Claiming the IDs are strictly ordered | Say they are ordered to the millisecond, and name logical or hybrid clocks for real ordering. |
| Treating the ID as a secret | Say 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 path | Generate in the library. Use a service only as a wrapper, with batching. |
| Returning IDs as JSON numbers | Send strings. A JavaScript number loses digits above 2^53, which a real ID passes within weeks. |
| Forgetting the epoch and the lifetime | Use a custom epoch at launch and state the end date of the layout, about 69.7 years later. |
The schemes compared in more detail, with a playground.
Why clocks step, and how accurate they really are.
Why two machines never agree on the time.
The small, reliable stores used to lease worker IDs.
The growing number that stops a paused owner from doing harm.
What to use when you need cause before effect.
A simple counter that respects cause and effect.
What time-ordered IDs do to a sharded database.