What you'll learn: By the end of this lesson you will be able to design an id service that issues unique, roughly time-ordered 64-bit ids with no call per id, choose its bit layout, explain how worker ids are leased and why a lease needs a safety margin, say what clock skew and a backwards clock do to uniqueness and ordering, compare the alternatives (database sequences, ticket servers, UUIDs and ULIDs, block allocation), and read the output of a Java model lab that shows each failure.
A chain of cinemas prints a ticket for every seat sold. If each box office invents numbers on its own, two customers in different cities can hold the same one. If each phones head office before every ticket, a bad line closes the cinema. The middle road gives each office a code, lets it count on its own, and prints code and count together. The catch: two offices must never get the same code, and an office must never count backwards.
That is the whole design of a distributed id generator, and this lesson works through it. It is an educational reference design, not the verified internal architecture of any company. It cites the README of Twitter's archived Snowflake project and Flickr's description of ticket servers only for what those pages say, and every capacity figure is an illustrative assumption. The comparison of formats (UUIDv4, UUIDv7, ULID and Snowflake-style) and the index-locality lab are in Unique ID Generation: UUID, ULID and Snowflake, and the clock vocabulary is in IDs, clocks and ordering and logical and vector clocks. This lesson is about the service around the format: who gets which worker id, what happens when a clock misbehaves, and how the system is run. The case-study format is introduced in the advanced overview.
The core idea
Uniqueness without a per-id conversation comes from building each id out of fields that cannot collide: a timestamp, a worker number and a sequence. Time keeps ids from different moments apart, the worker number keeps simultaneous ids from different processes apart, and the sequence keeps ids from the same process in the same millisecond apart. Three things can go wrong, and each one has a rule:
- Two processes hold the same worker number. Their ids collide. Rule: worker numbers are leased from a small coordination service, never copied from a config file.
- A clock moves backwards. A process could reuse a timestamp and a sequence it already issued. Rule: refuse to issue ids until the clock passes the last timestamp used.
- A process issues more ids than the sequence holds in one millisecond. Rule: wait for the next millisecond, never wrap.
Coordination is needed once per process lifetime (to get a worker number), not once per id. Three illustrations run through the lesson: a minimal example (the lab's first output, three processes and a few ids), a realistic example (ShopStream order ids) and a failure example (a lease that expires during a pause).
Requirements and scope
Functional
- Issue ids that are unique across the whole system.
- Roughly sortable by creation time, so a recent-first query and a cursor can use the id alone.
- Fit in 64 bits, so they are compact in indexes and foreign keys.
- Issue ids from many processes in many zones without a call per id.
Out of scope
- Gapless numbering (invoice numbers that legal rules require to have no holes). Sequences and generators leave gaps by design.
- Ids that must hide how many exist or when they were made (see the security note below).
- Strict global ordering. The design gives order within one worker and approximate order across workers.
Non-functional (illustrative assumptions)
- Generation adds microseconds, not a network round trip, to a request.
- Availability: a coordination-store outage must not stop processes that already hold a worker number.
- A restart, a pause or a clock correction must never produce a duplicate. Refusing to issue ids is acceptable, a duplicate is not.
Back-of-envelope estimate
All figures below are illustrative assumptions.
| Quantity | Assumption | Result |
|---|---|---|
| Peak id rate | 150,000 per second across the fleet | |
| Generator processes | 20 | 7,500 ids per second each at peak |
| Per-worker ceiling | 4,096 ids per millisecond (12 sequence bits) | 4,096,000 ids per second per worker |
| Worker numbers | 10 bits | 1,024 live workers at most |
| Timestamp range | 41 bits of milliseconds | about 69.7 years from the epoch |
| Epoch chosen | 2026-01-01 | range ends around 2095 |
| Average rate | 10,000 per second | about 864 million per day, about 315 billion per year |
| Storage in the id column | 8 bytes each | about 2.5 TB per year for the column alone, against about 5 TB for 16-byte ids |
The first lesson is that raw capacity is not the constraint. A single worker can issue about 550 times the per-process peak. The real constraints are the number of workers (1,024), the lifetime of the timestamp field, and above all the two correctness rules: unique worker numbers and a clock that does not go backwards. The 64-bit size matters because the id is repeated in every index and foreign key that references the row.
API design
Two ways to expose the generator, and the choice is a trade-off:
- An embedded library. Each service links the generator and calls
nextId()in process. No network hop, but every service needs a worker lease and a healthy clock. - A small id service. Callers ask a service for ids. One more hop, but only the id service needs leases, and callers cannot misconfigure them. Snowflake's README describes exactly this: a network service for generating unique ids at high scale.
GET /v1/ids?count=100
200 { "ids": ["4261412864000", "4261412864001", ...] } ids are STRINGS
503 { "type": "worker-lease-lost", "retryAfterSeconds": 5 }
GET /v1/ids/4261412864000/decode
200 { "timeOffsetMs": 1016000, "workerId": 0, "sequence": 0 }
Three rules keep it safe:
- Return ids as strings in JSON. JavaScript numbers represent integers exactly only up to 2^53 - 1 (
Number.MAX_SAFE_INTEGER, 9,007,199,254,740,991), and a Snowflake-style id is far larger than that, so a browser would silently round it. Strings avoid the problem. - Batch on request. Asking for 100 ids in one call lets callers amortise the network hop.
- An honest error when the generator refuses. A refusal (lease lost, clock behind) returns a retryable error. The generator never degrades to "issue something anyway".
Data model
The id is a 64-bit integer. The layout used by the lab, as in the Snowflake README, is a time field of 41 bits, a worker field of 10 bits and a sequence of 12 bits; the lab also reserves the top bit so the number is a positive long.
| Field | Bits | Meaning | Limit |
|---|---|---|---|
| Unused | 1 | Always 0, keeps the id positive | |
| Timestamp | 41 | Milliseconds since a custom epoch | about 69.7 years |
| Worker | 10 | Number leased by this process | 1,024 workers |
| Sequence | 12 | Counter within one millisecond | 4,096 per worker per millisecond |
An id is (timestamp << 22) | (worker << 12) | sequence. The shifts (22 = 10 + 12, then 12) are the whole format, and decoding is three shifts and masks. Because the timestamp is the most significant field, sorting ids as numbers sorts by time first.
The only shared data is the lease table:
Figure 1. Only leases are shared. How to read this: a worker slot is a number from 0 to 1,023. At most one lease is active on it. The slot remembers a high-water mark, so the next holder can refuse to start with a clock that is not past it. Ids themselves are never stored by the generator.
High-level design
Figure 2. Coordination happens at startup and renewal, not per id. How to read this: each generator holds a lease on one worker number from the registry and reads time from its own clock, kept in step by clock synchronisation. The ids it issues flow to the data stores; no generator talks to another.
The life of one process, in order:
Figure 3. Three checks guard every id. How to read this: the start check protects against a new process on a slow clock, the per-request checks protect against a lapsed lease and a backwards clock, and the renewal keeps the lease alive and tells the registry how far the process has got.
Deep dive 1: why Snowflake-style, and what the alternatives cost
| Approach | How it makes ids unique | Order | Cost | Use when |
|---|---|---|---|---|
| One database sequence | A counter in one database | Strict, within that database | A write path through one node; gaps after rollbacks | One database, modest volume |
| Ticket server | Dedicated database counters handing out ranges or numbers | Rising per server | A tiny service to run, one network hop per id or block | You can accept a hop and the pairs of servers |
| Random 128-bit (UUIDv4) | Randomness | None | 16 bytes; random index inserts | No ordering or size constraint |
| Time-ordered 128-bit (UUIDv7, ULID) | Timestamp plus random bits | By millisecond | 16 bytes; clock dependence | Want order without leases |
| Snowflake-style | Timestamp plus leased worker plus sequence | Per worker strict, across workers approximate | A lease registry; clock rules | 64 bits and order, many writers |
| Block allocation (hi/lo) | A central counter hands each process a block of numbers | Per block | A central counter touched once per block; unused numbers lost on restart | You want small sequential numbers |
Some of the facts behind the table:
- The PostgreSQL documentation states that
nextvalandsetvalcalls are never rolled back, so sequences cannot give gapless numbering, and that with aCACHEsetting above one each session preallocates numbers, so numbers allocated but unused when a session ends leave holes. Gaps are normal; do not build anything that needs none. - Flickr's write-up of ticket servers describes a MySQL
REPLACE INTOon a one-row table to get a new auto-incremented id, two servers handing out even and odd numbers (auto-increment offset and increment of two), and clients alternating between them. It calls the design not particularly elegant and admits the two sides drift a bit out of sync. - The Snowflake README lists the requirements the design answers: no coordination between machines, roughly time ordered ("k-sorted" within a bound that Twitter promises as one second and aims at tens of milliseconds), directly sortable, and compact (under 64 bits). Those are our needs too.
- RFC 9562 defines the time-ordered UUIDv7, with a 48-bit Unix millisecond timestamp, and its section on monotonicity says counters must handle rollover in the application to avoid sorting issues.
Figure 4. A decision, not a ranking. How to read this: each question removes a cost you may not need. The sequence is the cheapest correct answer when it is enough; the leased generator is the answer when 64 bits, order and many writers all apply.
Deep dive 2: the bit layout is a budget
The 63 usable bits are a budget split three ways, and shifting bits shifts the limits:
- More worker bits allow more processes but cut the time range or the sequence. The lab keeps one 10-bit field and takes it from a lease.
- More sequence bits allow more ids per millisecond per worker. At 12 bits a worker issues up to 4,096 per millisecond, far above the 7.5 per millisecond each process needs at peak here, so there is slack to give to workers.
- More time bits extend the lifetime. A recent custom epoch (here 2026-01-01) spends the 41 bits from the day the system starts, not from 1970.
Once ids are in storage, changing the layout means a mixed population, so pick it with room to grow.
Ordering is approximate, and the README says so. Because each worker stamps ids from its own clock, a worker whose clock runs behind produces ids that sort before ids made earlier by another worker. The lab measures it with three workers whose clocks differ by 0, -3 and +2 milliseconds: of 66 pairs of ids, 12 sorted in the wrong order, and the largest timestamp gap in a wrongly ordered pair was 3 ms. Use ids to sort and page, never to decide which of two events happened first (see logical and vector clocks for ordering that means something).
Deep dive 3: worker ids, leases and the safety margin
Why configured numbers are dangerous. The Snowflake README describes the machine id as configured. Configuration is copied, and copied configuration means two processes with the same worker number. Their ids are identical whenever they run in the same millisecond with the same sequence. The lab shows it: two processes both set to worker 5, issuing 3 ids per millisecond for 3 milliseconds, produced 9 distinct ids out of 18; with leased worker numbers all 18 were distinct.
A lease makes the number a loan. The registry hands out the lowest free worker number with an expiry time. The holder must renew before it expires and must stop issuing ids when it does. Three details make the design safe rather than merely plausible:
- The holder checks its own lease. Each
nextIdcall compares the clock with the lease expiry, and refuses once it is past. A process paused for a long time (a stop-the-world garbage collection, a throttled container, a suspended virtual machine) wakes up, notices, and does not issue ids under a number that may now belong to someone else. - The registry waits a margin after expiry before reusing the number. The holder stops at expiry by its clock; the registry reuses at expiry plus a margin by its own clock. The margin must cover clock difference between the two and any delay between the holder's check and the moment the id is used. In the lab the margin is 2,000 ms on a 10,000 ms lease; in production both are choices you measure, not constants to copy.
- The new holder starts after a floor. The registry hands over a floor timestamp: the larger of the reported high-water mark and the end of the previous lease. A process that finds its clock not past the floor refuses to start. This covers ids the old holder issued after its last renewal, and a new host whose clock is behind the old one.
The lab's fifth scenario walks through it with two worker numbers: a holder renews, then pauses past its lease and is refused (lease expired at +14000); a third process asks for a number and is told that none is free until +16000 (the earliest reuse time, expiry plus margin); at +16000 it gets worker 0 with a floor of +14000; and a host whose clock reads +2500 is refused when it starts with that lease.
What the registry store must give. Handing out a number is a compare-and-set on a small record, so any replicated store with leases and atomic conditional updates will do. Generation never depends on it once the lease is held; an outage blocks only new processes and renewals. Size the lease so that a realistic outage does not expire every lease at once (illustratively, a 30-second lease renewed every 10 seconds).
Deep dive 4: clocks, skew and going backwards
Two clock problems look alike and need different answers.
Skew between machines is normal. Clocks differ by small amounts even when synchronised, and the ids inherit it as the approximate ordering described above. The rule: treat the order as k-sorted, size the page boundaries and cursors for it (a cursor that is "ids after this one" can skip a late-arriving lower id, so keep a small overlap), and monitor the clock offset of every generator.
A clock that moves backwards on one machine is dangerous. If the clock steps back, the generator could reach a timestamp it has already used and, with the same worker and sequence, repeat an id. The Snowflake README says the service protects against non-monotonic clocks: if the clock is told to repeat a few milliseconds, it will refuse to generate ids until a time that is after the last time it generated an id, and it recommends running time synchronisation in a mode that does not move the clock backwards. The lab follows the same rule in a stricter form: it throws when the clock is behind the last timestamp, with no waiting, and a caller sees a retryable error. Waiting out a small step is an option (the older snowflake-id lab tolerates a configurable wait), but waiting out a large one means downtime as long as the step, so refuse and alert.
RFC 9562 gives the same advice for UUIDs: handle timestamp changes from the environment, including clock rollbacks.
Deep dive 5: bursts, rollover and capacity
At 12 sequence bits a worker issues at most 4,096 ids in a millisecond. If a burst exceeds that, the generator must not wrap: it waits for the next millisecond. The lab sends 10,000 ids with a frozen clock: 4,096 in the first millisecond, 4,096 in the next and 1,808 in the third, all 10,000 unique, with the fake clock advanced by 2 ms. The delay is under a millisecond per 4,096 ids and the alternative is a duplicate. Sustained rates near the ceiling need more worker numbers or sequence bits, not retries.
The other limit is the timestamp field, which ends about 69.7 years after the epoch. Put the end date in the runbook and make the generator refuse to issue past it instead of wrapping.
Security and privacy of ids
A Snowflake-style id contains the creation time and worker number, and neighbouring ids are easy to guess. RFC 9562 says implementations should not assume UUIDs are hard to guess and that embedded timestamps pose a very small attack surface; the reasoning is stronger here. Treat ids as identifiers, not secrets: authorise every request on the owning user, and use a separate random token for anything that works as a capability (a reset or share link).
Reference deployment topology
Figure 5. What to run and what to watch. How to read this: the generator is a library in the service pods, so the only new infrastructure is a small replicated registry and a disciplined clock source. The alerts watch the three things that go wrong: clock offset, lease renewals and generator refusals.
Bottlenecks and scaling
- Per-worker ceiling. About 4 million ids per second, rarely a limit. The limit that arrives first is the number of workers (1,024) if each pod takes a worker number; pods that restart often burn through leases until they expire, so give a pod a stable identity or release on graceful shutdown.
- Registry. Low traffic (acquire and renew only), but its availability decides whether new pods can start. Replicate it and cache the lease locally.
- Clock synchronisation. The hidden dependency. A fleet-wide clock step is a fleet-wide refusal. Alert on offset and on backwards steps.
- Hot index edge. Time-ordered ids insert at the right edge of an index, which is good for cache locality and can concentrate writes on one page range (see B-tree indexes).
- Consumers. JSON, JavaScript and spreadsheets mishandle 64-bit integers. Strings everywhere outside the database.
Failure modes
| Failure | Effect | Mitigation |
|---|---|---|
| Two processes with one worker number | Duplicate ids and primary-key errors | Leases, never configured numbers; unique constraint as the last line |
| Pause longer than the lease | Old process might issue under a number now reused | Holder checks expiry each call; registry waits a margin before reuse |
| Clock steps backwards | Possible repeated timestamp | Refuse until the clock passes the last timestamp; alert |
| New host on a slow clock | Ids below the previous holder's | Start check against the floor |
| Registry down | New pods cannot start, renewals fail | Replicas, long enough lease, local lease cache |
| Burst above the sequence | Duplicates if wrapped | Wait for the next millisecond |
| Timestamp field exhausted | Wrapping | Refuse and plan a layout change years ahead |
| Out-of-order ids from skew | Pagination skips or reorders | Treat order as approximate; overlap cursors |
Trade-offs worth stating
| Decision | Option A | Option B | How to choose |
|---|---|---|---|
| Where it runs | Embedded library | Separate id service | Library for speed, service to keep leases and clocks in one place |
| Worker numbers | Configured | Leased | Leased, always |
| Backwards clock | Refuse | Wait it out | Refuse for large steps, wait only for tiny ones |
| Size | 64-bit | 128-bit time-ordered | 64-bit when indexes and keys dominate cost; 128-bit when leases are unwelcome |
| Ordering | Approximate time order | Random ids | Time order for paging and index locality; random for opacity |
| Ids to clients | Numbers | Strings | Strings |
Interview cheat sheet
| Step | What to say |
|---|---|
| Requirements | Unique, roughly sortable, 64-bit, no call per id |
| Estimate | Capacity is not the constraint; workers and clocks are (4,096 per millisecond per worker, 1,024 workers) |
| Design | 41 bits time, 10 bits worker, 12 bits sequence; leased worker numbers; three checks |
| Deep dives | Alternatives, leases and margin, clock skew and rollback, rollover |
| Failures | Duplicate worker numbers, pause past the lease, clock step: refuse rather than duplicate |
Build it
The lab is examples/backend/labs/id-generator-workers, a plain Java 25 project with JUnit tests. It is a model: a Snowflake-style generator with an injectable clock, plus an in-memory lease registry. It is not a library to copy and it measures no timing: the clock is a fake that moves only when the demo says so, so nothing it prints says anything about real speed, real clock behaviour or a real coordination store. Its tests do not exercise concurrent callers; the older snowflake-id lab described in the comparison lesson does that for a plain generator.
Run it from examples/backend:
./gradlew :labs:id-generator-workers:test # 14 tests
./gradlew -q :labs:id-generator-workers:run # prints the five scenarios below
How it is built, in five lines:
IdGeneratorpacks(time << 22) | (worker << 12) | sequenceand checks three refusals: clock not past the lease floor at start, lease expired, clock behind the last timestamp.- After 4,096 ids in one millisecond it sleeps on the injected
Clockuntil the next millisecond. WorkerRegistryleases the lowest free worker number with a TTL, reuses it only after expiry plus a margin, and hands the next holder a floor timestamp.ManualClockis the fake clock; each worker in the skew scenario has its own.Orderingcounts pairs of ids that sort the wrong way and the largest timestamp gap among them.
Expected output, captured from a real run (Java 25, examples/golden/id-generator-workers.txt):
1. Three processes lease worker ids, then issue ids in the same millisecond
process 1 leased worker id 0
id 4194304000000 worker=0 sequence=0 time=epoch+1000000 ms
id 4194304000001 worker=0 sequence=1 time=epoch+1000000 ms
process 2 leased worker id 1
id 4194304004096 worker=1 sequence=0 time=epoch+1000000 ms
id 4194304004097 worker=1 sequence=1 time=epoch+1000000 ms
process 3 leased worker id 2
id 4194304008192 worker=2 sequence=0 time=epoch+1000000 ms
id 4194304008193 worker=2 sequence=1 time=epoch+1000000 ms
layout: 1 unused bit | 41 bits time | 10 bits worker | 12 bits sequence
2. A burst of 10000 ids while the clock stands still
millisecond +0: 4096 ids
millisecond +1: 4096 ids
millisecond +2: 1808 ids
unique ids: 10000, fake clock advanced by 2 ms
capacity per worker per millisecond: 4096
3. Clock skew between workers: ids sort by timestamp, not by true creation order
worker clock offsets in ms: worker 0: 0, worker 1: -3, worker 2: +2
true creation order, by worker: 0 1 2 0 1 2 0 1 2 0 1 2
order after sorting by id, as creation positions: 1 0 4 3 7 2 6 10 5 9 8 11
inverted pairs: 12 of 66, largest timestamp gap in an inverted pair: 3 ms
4. Two processes configured with the same worker id, then with leased ids
hand-configured worker id 5 on both: distinct ids 9 of 18
leased worker ids 0 and 1: distinct ids 18 of 18
5. Lease expiry, reuse margin and the high-water mark (lease 10000 ms, margin 2000 ms, 2 worker ids)
+0: node A holds worker id 0, node B holds worker id 1
+4000: node A issued an id at +3000 and renewed: its lease now ends at +14000
+9000: node B renewed: its lease now ends at +19000
+15000: node A was paused and missed its renewal -> lease for worker id 0 expired at +14000; refusing to generate ids
+15000: node C asks for a worker id -> none free, earliest at +16000
+16000: node C leases worker id 0 (must start after +14000)
a host whose clock reads +2500 starts with that lease -> clock +2500 is not after the previous holder's high-water mark +14000; refusing to start
id 4261412864000 worker=0 sequence=0 time=epoch+1016000 ms
How to read it: in scenario 1 the first id of worker 1 differs from worker 0's by exactly 4,096, the weight of the worker field, so simultaneous ids cannot collide. Scenario 2 spreads 10,000 ids over three milliseconds with no duplicate. Scenario 3 shows skewed clocks scrambling the order: 12 of 66 pairs sorted the wrong way. Scenario 4 shows 9 distinct ids of 18 with a hand-configured number and 18 of 18 with leased numbers. Scenario 5 shows the three refusals in sequence.
Limits, stated plainly: the registry is one in-memory object, so it models the lease rules and not the failure behaviour of a replicated store; it assumes the registry's and generators' clocks agree within the margin; and a pause between the lease check and the use of the id is not modelled. It shows the rules; it does not prove a production system safe.
In practice: ShopStream order ids after sharding
This is the realistic example, on the course's running example. Every figure is an illustrative assumption, and ShopStream is a teaching scenario, not a company.
This is a realistic scenario, not a case history.
The situation
ShopStream peaks at about 58 checkouts per second (shared course figure). In Stage 4 the orders database is sharded by shopper id, so a single database sequence can no longer number orders across shards, and the team wants order ids that are unique across shards, sortable by time for the "my orders" screen, and not a surprise to the mobile app.
Starting architecture
One PostgreSQL primary with a sequence for orders.id. After sharding there would be one sequence per shard, so ids from two shards collide unless a shard number is part of the id.
Options considered
| Option | Benefit | Cost | Risk |
|---|---|---|---|
| A. Per-shard sequences plus the shard number in a composite key | No new service | Two-part keys everywhere | Resharding changes keys |
| B. UUIDv7 | No coordination, time order | 16 bytes in every index and foreign key | Larger indexes, clock dependence |
| C. Snowflake-style ids from a library in the order service, with leased worker numbers | 8 bytes, time order, no hop | A small lease registry and clock monitoring | A misconfigured pod or a bad clock |
The decision
Option C. At 58 checkouts per second the rate is irrelevant (a worker's ceiling is about 4 million ids per second), so the decision rests on id size and the need for ids that do not change meaning when data moves between shards. The order service runs a handful of pods, each leasing a worker number at start and releasing it on graceful shutdown. A plain database sequence would be a perfectly reasonable answer at the previous stage, which is the point of the decision record: the trigger for change is sharding, not volume.
Rollout and verification
Before the first production id: a test that a restarted pod never starts below the floor, a staging drill that expires a lease and checks the generator refuses, and a unique constraint on orders.id as the last line of defence. Watch per pod the clock offset, the lease margin remaining and the count of refusals. Return ids to the mobile app as strings.
The 2 a.m. failure
Checkout errors spike. One pod has been throttled by its container limit and paused for longer than its lease; when it wakes, each nextId call is refused with a lease error and the order service returns 503 for requests that land on it. The checks: the generator refusal count by pod, the time since the pod's last renewal, and the pod's CPU throttling. The mitigation is to let the pod fail its readiness check so traffic moves away, and let it re-acquire a lease (it will receive the lowest free number after the margin). The wrong fix is to extend the lease to many minutes or to bypass the expiry check: either one reopens the duplicate window the check exists to close. The lasting fixes are to renew at a third of the lease length from a dedicated thread, remove the CPU limit that throttles the renewer, and alert when the margin on any pod falls below half.
Architect's notes
- State the correctness rule before the format. "No duplicates, ever, even if that means refusing" decides every later choice.
- Capacity is a distraction. The right questions are who owns the worker number and what the clock does.
- Keep a unique constraint. The primary key is the last line of defence and turns a silent duplicate into a loud error.
- Plan the layout change. Reserve a version bit so a future format can coexist with the old one.
- Decide what "sortable" means in writing. Paging, "since" queries and event ordering need different guarantees; only the first is met by approximate order.
Common mistakes
- Copying a worker number into configuration and deploying the same image twice.
- Wrapping the sequence instead of waiting for the next millisecond.
- Letting the clock go backwards without a refusal because "NTP never does that".
- Returning 64-bit ids as JSON numbers, or treating them as secrets or as proof of event order.
- Reusing a worker number the instant its lease expires, with no margin.
Key takeaways
- An id built from time, a worker number and a sequence needs coordination once per process, not once per id.
- The three correctness rules are unique worker numbers, a clock that does not go backwards, and no wrapping of the sequence.
- Worker numbers should be leased with an expiry, a reuse margin and a floor timestamp for the next holder.
- Refusing to issue ids is better than issuing a duplicate: make refusals loud, retryable and alertable.
- Order across workers is approximate. Use ids for paging, not for deciding what happened first.
- Return 64-bit ids as strings, and never treat them as secrets.
- A database sequence is enough until sharding or multiple writers make it not enough.
Practice exercises
Exercise 1 (30 min). Compute the timestamp range for 39, 41 and 43 time bits in years, and the worker and sequence limits left over from 63 bits in each case.
Exercise 2 (45 min). Choose a lease length, renewal interval and margin for a fleet whose clocks differ by up to 200 ms and whose longest pause is 5 seconds. Justify each number and name what you would measure to confirm it.
Exercise 3 (1 hour). Run the lab and read the five scenarios. Then predict, from the code, which tests fail if the start check against the floor is removed, and why. Do not leave the change in the code.
Exercise 4 (1 hour). Design the cursor for a "newest first" list that is robust to the 3 ms gap measured in scenario 3.
Exercise 5 (2 hours). Using WorkerRegistry.release, write a test that a worker number released at shutdown can be leased again at once and that a generator on a clock behind the released timestamp still refuses to start.
Related reading
- Unique ID Generation: UUID, ULID and Snowflake: the formats, bit by bit, and the index-locality lab.
- IDs, Clocks and Ordering: the clock problem in general.
- Logical and Vector Clocks: ordering that does not depend on wall clocks.
- Sharding and Partitioning: why a single sequence stops working.
- B-Tree Indexes and SQL Indexing: what ids do to an index.
- Pagination: Offset, Cursor and Keyset: using sortable ids as cursors.
- ShopStream Stage 4: scale writes: where order ids come from in the running example.
Official documentation
- Twitter, archived Snowflake README (2010 branch): requirements, bit layout, system clock dependency.
- IETF, RFC 9562: Universally Unique IDentifiers (UUIDs): UUIDv7, monotonicity and counters, timestamp considerations, security considerations.
- PostgreSQL documentation, CREATE SEQUENCE: gaps,
CACHEand rollback behaviour. - Flickr Engineering, Ticket Servers: Distributed Unique Primary Keys on the Cheap.
- MDN, Number.MAX_SAFE_INTEGER: why 64-bit ids go in JSON as strings.