System design concepts · When Machines Disagree

Unique ID Generation in Distributed Systems: Snowflake, UUID, Clocks

In a distributed system there is no single "now". Wall clocks drift, messages arrive late, and two machines can't agree on what happened first without help.

What you'll be able to explain
  • Explain why wall-clock timestamps can't order events across machines
  • Use Lamport clocks and vector clocks
  • Compare ID strategies: auto-increment, UUID, ULID, Snowflake, ticket servers
  • Design a Snowflake-style 64-bit ID
  • Handle clock skew in ID generators

Why clocks lie

Server clocks synchronise with NTP but still drift by milliseconds, and sometimes jump (leap seconds, misconfigured NTP, VM pauses). If server A writes at 10:00:00.005 and server B at 10:00:00.003, B's write may actually have happened later. Using wall-clock timestamps for ordering or last-write-wins can silently pick the wrong winner.

  • Monotonic clocks measure durations safely on one machine (timeouts, latency). Use them for "how long", never for "when".
  • Logical clocks order events without trusting wall time.
  • Bounded-uncertainty clocks (Google's TrueTime) expose an error interval; Spanner waits out the uncertainty to give globally ordered commits.

Logical clocks

Lamport clock: each node keeps a counter; increment on every event; send it with messages; on receive, set counter = max(local, received) + 1. If A happened before B, then L(A) < L(B). (The reverse isn't guaranteed.)

Vector clock: one counter per node. Comparing two vectors tells you whether one event happened before the other or whether they were concurrent, which is exactly what conflict detection needs (CAP Theorem, PACELC and Consistency Models Explained).

Unique IDs: the options

Strategy Size Sortable by time? Coordination Notes
DB auto-increment 64-bit Yes Single DB Simple; bottleneck; leaks business volume
UUID v4 128-bit No None Random; poor B-tree locality
UUID v7 / ULID 128-bit Yes (ms) None Time-prefixed; great default today
Snowflake 64-bit Yes (ms) Worker IDs only Compact, fast, ordered
Ticket server / ranges 64-bit Roughly Hand out ID blocks Each node takes a block of 1,000
Tip

Random UUIDs (v4) as primary keys scatter inserts across the whole B-tree, causing page splits and poor cache use. Time-ordered IDs (UUIDv7, ULID, Snowflake) append near the end of the index, which is far friendlier.