Design a Unique ID Generator
Understanding the Problem
🔢 What is a unique ID generator? Every new tweet, order, message and payment needs an identifier that no other object will ever have. On one database, an auto-increment column does the job. Once writes are spread across many database shards and many service instances, there's no single counter to ask, so we need a way for many machines to create IDs independently that are still guaranteed never to collide, and ideally still sort by the time they were created.
You may also be asked for a service that hands out "ascending auto-increment" numbers, or for an idempotency key service that makes client retries safe. The first is the same problem with a stricter ordering rule. The second is a close relative: it uses a unique ID chosen by the client to recognize a request it has already seen. We'll cover both.
Functional Requirements
Core Requirements
- Services should be able to get a new ID that is unique across the whole system, forever.
- IDs should fit in 64 bits and sort roughly by creation time, so "newest first" queries can sort by ID.
- Some callers should be able to get numbers from a strictly ascending sequence, such as order or invoice numbers.
- Clients should be able to attach an idempotency key to a request so that retrying it doesn't perform the action twice.
Below the line (out of scope)
- Human-friendly short codes (like
bit.ly/x7Kp2). That's an encoding on top of an ID; see /system-design/url-shortener. - Globally ordered IDs across all regions to the millisecond.
- Hiding business volume from people who can see IDs, beyond a short note.
Non-Functional Requirements
Ask how many IDs we need and how fast. For our design: 100,000 IDs per second at peak across the system, generated by a few thousand service instances in several data centers.
Core Requirements
- The system must never produce a duplicate ID, even across crashes, restarts and clock problems.
- Generating an ID should take well under a millisecond, since it happens on the write path of almost everything.
- ID generation must be highly available: if it stops, every write in the company stops.
- IDs should be 64-bit integers, so they fit in a
BIGINTcolumn and index efficiently.
Below the line (out of scope)
- Making IDs unguessable. If an ID must be secret, use a separate random token.
Do the bit math, because it decides the design. Suppose we put a millisecond timestamp in the ID. 41 bits of milliseconds covers 2^41 ms, which is about 69 years from whatever start date (epoch) we choose. That leaves 22 of our 63 usable bits (the sign bit is kept at 0 so IDs are positive in languages without unsigned integers). Spend 10 bits on a machine ID (1,024 machines) and 12 bits on a per-millisecond sequence (4,096 IDs per millisecond per machine). One machine can then produce about 4 million IDs per second, and the whole fleet many billions. We need 100,000. So throughput is a non-issue. The hard part is making sure no two machines ever use the same machine ID and no machine ever reuses a timestamp.
The key insight: if each machine owns a slice of the ID space, it can generate IDs with no network call at all. Uniqueness then comes from how you hand out the slices, not from coordinating on every ID.
The Set Up
Planning the Approach
We'll start from the simplest thing (a database counter), see why it breaks, compare the standard alternatives (UUIDs, ticket servers, Snowflake-style IDs), and then handle strictly ascending sequences and idempotency keys. The deep dives cover worker ID assignment, clock problems and the idempotency store.
Defining the Core Entities
- ID: a 64-bit integer, unique forever, made of a timestamp, a machine ID and a sequence number.
- Worker: one process that generates IDs. Each live worker owns exactly one worker ID.
- Sequence: a named, strictly ascending counter (such as
order_number) for callers that need one. - Idempotency record: a client-supplied key, the fingerprint of the request it came with, the request's status and its stored response.
API or System Interface
The best version of this "service" is often a library linked into every service, so the main interface is a function call. Sequences and idempotency keys are network services.
// In-process library
nextId() -> int64
// Sequence service
POST /sequences/{name}/next?count=1 -> { values: [10000452] }
// Idempotency, as seen by API clients
POST /v1/payments
Idempotency-Key: 4f1c2a9e-8b7d-4e21-9a63-2d0f5c7e1b88
{ amount: 4200, currency: "usd", ... }
High-Level Design
1) Services should be able to get an ID that is unique across the system
The starting point: one database's auto-increment. Every service calls one database that runs INSERT INTO ids () VALUES () and returns the new auto-increment value. It's unique and strictly ascending. It's also a single point of failure on the write path of every service, and a round trip per ID. A single database handles thousands of these per second; we need 100,000 with headroom, and we need it to never go down.
Ticket servers. Run two (or N) counter databases and set their auto-increment to step by N with different offsets: server A hands out 1, 3, 5, … and server B hands out 2, 4, 6, …. In MySQL that's auto_increment_increment = 2 and auto_increment_offset = 1 or 2. Callers use whichever server answers. Either server can die and the other keeps going. This was a well-known production setup for years and it's still a fine answer at moderate scale. The downsides: it's still a network call per ID (callers fetch blocks of IDs to soften that), the servers drift apart so IDs aren't time-ordered, and adding a third server means changing the step on all of them.
UUIDs. Each service generates a 128-bit random UUID v4 locally. With 122 random bits, collisions are not a practical concern: you'd need to generate on the order of 10^18 of them before a collision becomes likely. No coordination, no network call, no single point of failure. The problems are size and order. 128 bits doesn't fit a BIGINT, and random values are terrible as a B-tree primary key: every insert lands in a random page of the index, so the working set is the entire index rather than the right-hand edge, and pages split constantly. Random UUIDs also don't sort by time.
The newer UUID v7 fixes the ordering: it puts a 48-bit Unix millisecond timestamp first and fills the rest with random bits, so values sort by creation time and insert near the end of the index. It's a good choice when 128 bits is acceptable. Our requirement is 64 bits, though.
| Approach | Size | Time-ordered | Network call | Coordination |
|---|---|---|---|---|
| DB auto-increment | 64-bit | Yes, strictly | Every ID | Single node |
| Ticket servers | 64-bit | No | Every ID or block | Fixed set of servers |
| UUID v4 | 128-bit | No | None | None |
| UUID v7 | 128-bit | Yes, roughly | None | None |
| Snowflake-style | 64-bit | Yes, roughly | None | Worker ID assignment only |
2) IDs should fit in 64 bits and sort roughly by creation time
This is the layout from the back-of-the-envelope section, popularized by Twitter's Snowflake:
- 1 bit unused (always 0, so the ID is a positive signed integer).
- 41 bits of milliseconds since a custom epoch (pick one near when the system launched, not 1970, to get the full 69 years).
- 10 bits of worker ID. Often split as 5 bits of data center and 5 bits of machine.
- 12 bits of sequence, reset every millisecond.
Each worker generates IDs entirely in memory:
def next_id(self):
now = current_millis() - EPOCH
if now < self.last_ms:
raise ClockMovedBackwards(self.last_ms - now) # see deep dive 2
if now == self.last_ms:
self.seq = (self.seq + 1) & 0xFFF # 12 bits
if self.seq == 0: # used all 4,096 this ms
now = wait_until_next_millis(self.last_ms)
else:
self.seq = 0
self.last_ms = now
return (now << 22) | (self.worker_id << 12) | self.seq
The function runs under a lock (or uses an atomic compare-and-swap on a packed last_ms + seq value) so two threads in one process don't produce the same sequence number. Generating an ID takes well under a microsecond.
Because the timestamp is in the high bits, sorting by ID sorts by creation time, so a query like ORDER BY id DESC LIMIT 20 gives the newest rows, and inserts go to the right-hand edge of a B-tree index. The order is only rough: two IDs generated within the same millisecond on different workers sort by worker ID, not by which came first, and clocks on different machines differ by a few milliseconds. For feeds, timelines and pagination, that's fine.
We can ship this as a library in every service (no network call at all) or as a small ID service that a few hundred instances call over gRPC. The library is faster; the service makes worker ID assignment simpler because there are fewer workers. Either is a good answer, and saying why is what matters.
3) Some callers should get numbers from a strictly ascending sequence
Snowflake IDs are unique and roughly ordered, but not strictly ascending: worker 7 can hand out an ID at 10:00:00.005 that's smaller than one worker 3 handed out at 10:00:00.004. Some things need a real sequence: order numbers that customers see, invoice numbers that accountants require to be increasing, or a log offset.
The simplest correct option is a single database sequence (Postgres CREATE SEQUENCE, or a counter row updated with UPDATE ... SET value = value + 1 RETURNING value). It's strictly ascending, but throughput is bounded by one row on one primary.
The standard fix is segment leasing. The sequence service doesn't fetch one number per request; it takes a whole range from the database at once:
UPDATE sequences
SET max_value = max_value + 1000
WHERE name = 'order_number'
RETURNING max_value; -- e.g. 15000, so this node owns 14001..15000
The node then serves numbers from that range in memory. One database write per 1,000 numbers turns a thousand-per-second bottleneck into a million-per-second service. To avoid a stall when a range runs out, each node fetches the next range in the background when the current one is, say, 20% used (double buffering).
There's a catch you should name. With several sequence nodes, each owns a different range, so numbers are ascending per node but interleaved across nodes: node A hands out 14,001 while node B hands out 15,001. If a sequence must be strictly ascending in time across all callers, route all requests for that sequence to one node (the leader), with a standby that takes over on failure and starts from a fresh range. When a node crashes, the unused part of its range is lost, so the sequence has gaps. Gaps are almost always acceptable, and you should ask. A "no gaps ever" requirement (some invoice rules) forces one number per transaction on one serialized counter, and it can't scale past that.
"Do you need it strictly ascending, or just unique and roughly ordered?" is the best clarifying question in this problem. Most callers say "ascending" when they mean "sortable," and the answer changes the design from a free local function to a coordinated service.
4) Clients should be able to retry safely with an idempotency key
A client calls POST /payments, the network drops the response, and the client retries. Without protection, the customer is charged twice. The fix is for the client to generate a unique key (a UUID v4 works well here, since it never needs to be sorted) and send it as an Idempotency-Key header. The server records each key it has processed. On a retry with the same key, it returns the stored result instead of running the action again.
The high-level flow:
- Atomically insert a record for the key with status
IN_PROGRESS. If a record already exists, don't run the action. - Run the action (charge the card, create the order).
- Save the response on the record and mark it
COMPLETED. - On a retry: if the record is
COMPLETED, return the saved response; if it'sIN_PROGRESS, return409 Conflictand let the client retry later.
The details of that store are the subject of deep dive 3.
Potential Deep Dives
1) How do we make sure no two workers have the same worker ID?
Two workers with the same worker ID will eventually produce the same ID in the same millisecond. This is the one way a Snowflake design produces duplicates, so it deserves the most care.
Bad Solution: Hard-code Worker IDs in Config
Approach
Give each machine a worker ID in its config file or environment.
Challenges
It works for a fixed fleet, and fails the first time someone copies a config to a new machine, or an autoscaling group starts a tenth instance from the same template. Nothing detects the mistake. Duplicates appear silently, and often only show up as constraint violations or, worse, two objects sharing an ID in systems without a unique constraint.
Good Solution: Derive It from the Deployment
Approach
Use something the platform already guarantees is unique. In Kubernetes, a StatefulSet gives each pod a stable ordinal (idgen-0, idgen-1, …) that can serve as the worker ID. Combine it with a data center number for the upper bits.
Challenges
It ties the ID scheme to one deployment model. It works well for a dedicated ID service with a few dozen pods, but not for a library embedded in thousands of pods across many deployments, each of which would need its own range of ordinals.
Great Solution: Lease Worker IDs from a Coordination Service
Approach
On startup, a worker claims a free worker ID in ZooKeeper or etcd, attached to a lease (a session in ZooKeeper, a lease with a TTL in etcd). It keeps the lease alive with heartbeats. If the worker dies, the lease expires and the ID becomes free again.
etcd: put /idgen/workers/417 "pod-a83f" --lease=<30s lease> (only if key absent)
The coordination service is only needed at startup and for heartbeats, never per ID. If it's briefly unavailable, workers that already hold a lease keep generating IDs.
Challenges
A worker that's paused (a long garbage collection, a VM freeze) can lose its lease without knowing it, while another worker claims the same ID. The worker must stop generating IDs as soon as it can't confirm its lease is still live, and the system should wait a little longer than the lease TTL before handing a freed ID to someone else. With 1,024 IDs and only a few thousand workers fleet-wide, you may also run out; that's when you take bits from the sequence (most workers never use 4,096 IDs per millisecond) or run a dedicated ID service with fewer workers.
2) What happens when a machine's clock goes backwards?
Clocks drift, and NTP corrects them. Usually it slews the clock gradually, but it can step it backwards, and a VM migration or a misconfigured server can jump it by seconds. If the clock goes back 5ms, a worker would generate timestamps it has already used, and with the same worker ID and a reset sequence, it would repeat IDs.
The generator above already detects this (now < self.last_ms). The options for handling it:
- Small jumps: wait. If the clock is behind by a few milliseconds, sleep until it catches up to
last_ms. A 5ms pause is invisible to callers. - Large jumps: refuse. If it's behind by more than a threshold (say 100ms), throw an error and take the worker out of service. Callers retry on another worker. Alert, because the machine's time is broken.
- Keep going on the logical clock. Instead of reading the wall clock again, keep using
last_msand keep incrementing the sequence, carrying into the timestamp when the sequence wraps. IDs stay unique and increasing; timestamps decoded from them are slightly ahead of real time until the wall clock catches up. - Persist the high-water mark. On restart, a worker doesn't remember
last_ms. If the clock went backwards while it was down, it would reuse timestamps. Writinglast_msto local disk every second or so, and refusing to start until the clock passes it, closes that gap. Leasing worker IDs from etcd with a delay before reuse also helps, since a restarted worker usually gets a different ID.
Also configure the time daemon (chrony or ntpd) to slew rather than step after boot. That makes backward jumps rare, but you still need the check.
Interviewers often ask "what if the clock goes backwards?" as the first follow-up. Detecting it with
last_msand waiting for small jumps is the expected answer; mentioning restarts is what makes it complete.
3) How do we build the idempotency key store?
The flow in the high-level design has three subtle points: the insert must be atomic, a retry might come with a different body, and keys can't be kept forever.
Bad Solution: Check, then Insert
Approach
SELECT the key; if it doesn't exist, run the action and then INSERT the key with the result.
Challenges
Two retries arriving at the same time both see "no key," both run the action, and the customer is charged twice. Clients often retry quickly after a timeout, so this race is common, not theoretical.
Good Solution: Atomic Claim with a Unique Constraint
Approach
Make claiming the key the first, atomic step. In Postgres:
INSERT INTO idempotency_keys (key, account_id, request_hash, status, created_at)
VALUES (:key, :account, :hash, 'IN_PROGRESS', now())
ON CONFLICT (account_id, key) DO NOTHING
RETURNING key;
-- a row returned: we own the request, run it
-- nothing returned: someone already did; read the existing row
Scope keys by account, so one customer's key can't collide with another's. Store a hash of the request body; if a retry comes with the same key but a different body, return 422 instead of replaying a result that doesn't match the request. When the action finishes, update the row with status = 'COMPLETED' and the response code and body. Expire rows after a fixed period (24 hours is a common choice) with a scheduled delete or TTL.
Even better: if the action's own writes are in the same database, do the key claim, the action and the completion in one transaction. Then a crash can't leave a charge recorded without its key, or a key without its result.
Challenges
The action often isn't local. Charging a card calls an external payment provider. If the server crashes after charging but before writing COMPLETED, the key is stuck in IN_PROGRESS. The fix is to pass the same idempotency key (or one derived from it) to the downstream provider, so a recovery job can safely retry the call or ask the provider what happened. Idempotency has to be carried all the way through the chain of calls, or it only protects the first hop. /system-design/idempotency covers this end to end.
Great Solution: Redis in Front, Database as Record
Approach
For very high request rates, claim the key in Redis first with SET idem:{account}:{key} IN_PROGRESS NX EX 86400. NX makes the claim atomic, EX gives the TTL for free, and the check takes well under a millisecond. Store the final response in Redis too, so most retries are answered from memory. Keep the database row (or the action's own unique constraint, like a unique payment_request_id on the payments table) as the final guard.
Challenges
Redis replication is asynchronous, so a failover can lose a recent claim, and a retry arriving right then would get through the Redis check. That's why the database constraint stays: Redis is the fast path, the database is the guarantee. For most systems, the Postgres version alone is plenty, and saying that is a reasonable call.
4) Should we expose these IDs publicly?
Time-ordered IDs leak information. Anyone can decode the creation time from a Snowflake ID, and sequential order numbers reveal how many orders you take a day (a competitor places one order on Monday and one on Friday and subtracts). Sequential IDs also invite enumeration: GET /invoices/10001, /10002, and so on.
None of that breaks uniqueness, but it's worth raising. Common mitigations are to keep authorization checks on every lookup (always needed anyway), to expose a separate random public ID or slug for sensitive objects, or to encode IDs with a reversible keyed permutation before showing them to users.
Final Design
- When an ID library or ID service instance starts, it leases a unique worker ID from etcd and keeps the lease alive.
- Services generate 64-bit Snowflake IDs in-process (timestamp, worker ID, sequence), with no network call per ID and a check that the clock hasn't moved backwards.
- Callers that need strictly ascending numbers ask the Sequence Service, which leases ranges of 1,000 from a database row and serves them from memory, routing each sequence to a single leader if strict order across callers is required.
- Mutating API calls carry an
Idempotency-Key. The API claims it atomically (RedisSET NXand a unique constraint in the database), runs the action once, stores the response, and replays it on retries.
What is Expected at Each Level?
Mid-level
You should explain why a single auto-increment database doesn't scale and compare UUIDs with a Snowflake-style layout, including the bit allocation and why the timestamp goes in the high bits. With a nudge, you should see that worker IDs must be unique and that clocks can go backwards.
Senior
You should work the bit math out loud (69 years, 1,024 workers, 4,096 per millisecond) and explain why random UUIDs hurt B-tree indexes. Expect to design worker ID assignment with leases, handle backward clock jumps including restarts, and distinguish "roughly ordered" from "strictly ascending," with segment leasing as the scalable way to get the latter. For idempotency keys, you should insist on an atomic claim and know what to do with an in-progress key.
Staff+
You should push on which callers actually need which guarantees and steer most of them to the cheap local option, reserving coordinated sequences for the few that need them. Expect to discuss the operational edges: lease expiry versus paused workers, gaps after failover, how idempotency is carried through downstream calls, and the information IDs leak when they're public.