Part 7 · Blueprint 37
Distributed Unique ID Generator (Twitter Snowflake Scale)
12 min reading · Sources · Editorial review pending
A sortable bit layout does not guarantee uniqueness if workers share an identity or clocks roll back.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Database Sharding & Consistent Hashing, Time, Clocks & Distributed Ordering: Lamport to TrueTime.
Sixty-second mental model
Problem: A sortable bit layout does not guarantee uniqueness if workers share an identity or clocks roll back.
Use: Budget the identifier space and refuse unsafe allocation.
Design boundary: Allocate unique structured identifiers under clock and worker-assignment failures. Uniqueness and chronological order are different promises.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing distributed identifiers. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one identifier means and which component owns the worker identity and clock policy.
Think of numbered ticket rolls assigned to different desks. Separate the requester from worker identity and clock policy, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
Architecture and worked reasoning
Design boundary: Allocate unique structured identifiers under clock and worker-assignment failures. Uniqueness and chronological order are different promises.
Responsibilities on the request path
Workload and limiting resource
A hypothetical 64-bit layout reserves one sign bit, 41 time bits, 10 worker bits and 12 sequence bits: 1 + 41 + 10 + 12 = 64. The sequence field permits 2¹² = 4,096 IDs per worker per chosen time unit; 10 bits allow 1,024 worker identities.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Obtain an exclusive worker identity.
- Apply the declared clock-rollback rule.
- Allocate a sequence within the current time bucket.
Observation and recovery path
- Decode fields only under the documented layout.
- Do not infer causality from numeric order.
- Reject exhausted buckets rather than wrapping silently.
Failure that changes the decision
Hypothetical scenario: A replacement worker reuses an identity while the previous process still emits IDs. Fence worker assignment and address clock rollback; random restart timing is not a uniqueness proof.
Attempt this decision before reading the explanation
Are timestamp-ordered IDs a substitute for a committed transaction sequence?
No. Worker clocks and sequence fields do not establish a shared commit order or causality across machines.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
A generation or sorting rule does not by itself establish an information dependency. State what the identifier guarantees before using it to decide event order or authority.
A product edit, a scheduled occurrence, a publication intent and a delivery attempt are different things. Each may need an identifier, but those identifiers answer different questions. A retry should retain the original logical operation identity while optionally acquiring a new attempt identity for diagnostics.
A schedule occurrence similarly retains the intended scheduled instant and schedule identity. A delayed start time belongs to the attempt record. Replacing occurrence identity with the time at which a worker happened to run makes recovery create new logical obligations instead of continuing the old one.
RFC 9562 defines UUID formats and relevant generation considerations. A UUID is not automatically a timestamp, an authorization token or a universal proof that a business action has never occurred before. The application still needs to bind it to the operation’s meaning.
Hypothetical scenario. Start two processes with scalar clocks at zero and vector clocks [0,0]. Process A emits event a: scalar 1, vector [1,0]. Independently B emits b: scalar 1, vector [0,1]. Neither event contains information about the other, so they are concurrent.
A scalar tie-breaker such as process identity can choose a total presentation order for a and b, but it does not manufacture a causal edge. Likewise, a larger Lamport timestamp does not prove that its event learned about every smaller timestamp. Physical-time uncertainty and logical clocks answer different questions; retain an operation identity independently from whichever order the display uses.
Each pair has matching probability 1 ÷ 256 under the selected model. The expected number of matching pairs is 45 ÷ 256 = 0.17578125. This is an expected pair count, not the probability that at least one collision occurs. Several matching pairs can belong to the same repeated value, and the events are not all disjoint.
Physical timestamps describe readings from clocks. Clocks can disagree, be adjusted or be observed at different points in a workflow. A producer’s event timestamp and the consumer’s processing timestamp can legitimately differ. Sorting one field cannot by itself reconstruct every dependency between events.
For a selected example, process A has clock 3 and advances to 4 when sending. Process B has clock 7 when receiving that message, so it sets max(7, 4) + 1 = 8. The send’s 4 is less than the receive’s 8. Another independent event with timestamp 5 is not proven to precede the receive merely because five is smaller than eight.
A’s message reaches B. B merges by componentwise maximum, giving max([0, 1], [1, 0]) = [1, 1], then increments its own component for the receive event to obtain [1, 2]. Now [1, 0] is componentwise no greater than [1, 2], with at least one strict inequality. The later event incorporates a’s history. A version comparison has gained information that sorting scalar timestamps cannot recover.
Lamport’s ordering paper gives the underlying happens-before relation: local order, matching send/receive, and their transitive consequences. A scalar clock preserves causal precedence in one direction. Vector comparison can expose concurrency under the stated tracking model, but neither clock decides what concurrent business edits mean. If a withdraw action and a description change are concurrent, the application must define whether to merge fields, retain competing versions or reject a transition pending review.
It can choose a reproducible order, but that does not establish that b observed a or is permitted to reverse it. In this example [1, 0] and [0, 1] are incomparable. State a merge policy for that concurrency instead of inventing a causal relationship.
RFC 9562 supplies a public format and generation reference for UUIDs. Use it to check what an identifier encodes and what the selected version promises. It does not specify Northwind’s retry-retention duration, product-version policy or worker-authority protocol.
Preserve logical identity across attempts and compare source versions according to the selected projection contract. Record attempt timestamps for diagnosis without granting them authority over the business history. Two useful metadata fields became harmful only when the application asked them to answer the wrong question.
Layer 3 · Internals
A Snowflake-style identifier partitions a fixed-width integer into time, worker and sequence fields. In a hypothetical 64-bit layout, reserve one sign bit, 41 timestamp bits, 10 worker bits and 12 sequence bits. The total is 1 + 41 + 10 + 12 = 64. There are 2^10 = 1,024 worker identities and 2^12 = 4,096 sequence values per worker per millisecond. The timestamp range is 2^41 milliseconds; dividing by 1,000 × 60 × 60 × 24 × 365 gives approximately 69.7 non-leap years from the chosen epoch. These are format-derived bounds, not measured generation rates.
Uniqueness requires exclusive worker identity and a policy for exhausted sequence values or backward time. A paused worker cannot safely keep using an identity reassigned to another process. Time-sortability is also weaker than causal order: two operations on different workers can be numerically sorted without proving which observed the other. UUIDv7 offers a standardized time-oriented alternative, but its timestamp does not create distributed transaction ordering.
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| UUIDv7 | Standardized time-oriented format without a central per-ID coordinator. | Randomness and timestamp semantics still need the specified implementation contract. |
| Worker-and-sequence layout | Explicitly bounds each worker's allocation space. | Exclusive worker identity and backward-clock handling become operational dependencies. |
Recovery decision
Hypothetical scenario: A replacement worker reuses an identity while the previous process still emits IDs. Fence worker assignment and address clock rollback; random restart timing is not a uniqueness proof.
No. Worker clocks and sequence fields do not establish a shared commit order or causality across machines.
Write your design before revealing the review
Are timestamp-ordered IDs a substitute for a committed transaction sequence?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
No. Worker clocks and sequence fields do not establish a shared commit order or causality across machines.
A replacement worker reuses an identity while the previous process still emits IDs. Fence worker assignment and address clock rollback; random restart timing is not a uniqueness proof.
Check your understanding
Are timestamp-ordered IDs a substitute for a committed transaction sequence?
No. Worker clocks and sequence fields do not establish a shared commit order or causality across machines.
How would you recover from this failure: A replacement worker reuses an identity while the previous process still emits IDs. Fence worker assignment and address clock rollback; random restart timing is not a uniqueness proof.
Start with the exact boundary that failed. Obtain an exclusive worker identity. Apply the declared clock-rollback rule. Allocate a sequence within the current time bucket. Then recover evidence through the observation path: Decode fields only under the documented layout. Do not infer causality from numeric order. Reject exhausted buckets rather than wrapping silently. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
A hypothetical 64-bit layout reserves one sign bit, 41 time bits, 10 worker bits and 12 sequence bits: 1 + 41 + 10 + 12 = 64. The sequence field permits 2¹² = 4,096 IDs per worker per chosen time unit; 10 bits allow 1,024 worker identities. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Allocate unique structured identifiers under clock and worker-assignment failures. Uniqueness and chronological order are different promises.
Which component in this topology could be removed from a smaller first deployment?
Worker lease, Clock policy, Sequence counter, ID allocator name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Obtain an exclusive worker identity.
What evidence must a caller have before relying on the observation path?
Decode fields only under the documented layout. Do not infer causality from numeric order. Reject exhausted buckets rather than wrapping silently. No. Worker clocks and sequence fields do not establish a shared commit order or causality across machines.
45-minute interview rubric
- 00–05: scope identifier and worker identity and clock policy.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw worker identity and clock policy, numbered writes and reads.
- 28–40: challenge recovery: Budget the identifier space and refuse unsafe allocation.
- 40–45: defend timestamp_ms placement, observations and remaining assumptions.
Go deeper
- RFC 9562: Universally Unique IDentifiers (UUIDs) · Primary document · www.rfc-editor.org. Budget the identifier space and refuse unsafe allocation. Verified 2026-10-26.
- Supporting primary reference · Primary document · www.cl.cam.ac.uk. Budget the identifier space and refuse unsafe allocation. Verified 2026-10-26.
Decision log
Budget the identifier space and refuse unsafe allocation.
Preserve identifier identity and worker identity and clock policy ownership.
Revisit changed workload, observations or recovery objectives.