The Runtime Theory

Snowflake ID Generation: Time, Worker, Sequence

See a snowflake ID assembled: timestamp bits, worker identifier bits, and a sequence counter that keeps IDs unique and ordered within the same millisecond.

The Runtime Theory Team08 stages

trace / request.md

ID IS REQUESTEDTIME GOES INTHE HIGH BITSWORKERIDENTIFIES ITSELFSEQUENCE COUNTSPER MILLISECONDBITS AREASSEMBLEDUNIQUENESS BYCONSTRUCTIONIDS SORT BY TIMECLOCK PROBLEMSARE HANDLED

readyA service needs a unique 64-bit ID — for a row, an event, a URL code. The snowflake scheme mints IDs locally, with no central coordination on the per-request path.

The snowflake ID is a timestamp with a serial number attached. This diagram shows the three fields packed into 64 bits: 41 bits of milliseconds since a custom epoch, 10 bits of worker identity, and 12 bits of sequence — the counter that disambiguates IDs minted in the same millisecond. The scheme's power is that uniqueness needs no coordination: workers never overlap because their bits differ, and a single worker never duplicates because its sequence increments.

The ordering of the stages mirrors the bit layout — time first, then worker, then sequence — and the layout is the semantics. Time in the high bits makes IDs roughly monotonic, which is what makes them better than UUIDs for B-tree primary keys: new rows insert at the hot end of the tree instead of spraying random pages. The two failure modes live at the edges: clock rollback, handled by freezing, and sequence exhaustion, handled by waiting. Everything else is arithmetic.