How it works
One example uses one reserved sign bit, 41 bits of milliseconds since a custom epoch, 5 data-center bits, 5 machine bits, and 12 sequence bits. A custom epoch is a start date you choose in place of 1970. That layout provides 32 data-center values, 32 machine values within each, and 4,096 sequence values per millisecond per worker. The 41-bit timestamp spans about 69.7 years: counted from 1970 it would run out in 2039, while counted from the start of 2024 it lasts until 2093. Record the epoch permanently because decoding old IDs depends on it.
Compose the value by shifting the timestamp into the high bits, then the worker fields, then the sequence. For timestamp 1,000, data center 3, machine 7, and sequence 5, the ID is (1000 << 22) | (3 << 17) | (7 << 12) | 5 = 4,194,725,893. Keep the sign bit zero so a signed 64-bit database field stores a positive number.
Treat field widths as a budget you can spend differently. This layout allows 4,096,000 IDs per second per worker, far more than a 25,000-per-second system needs, and real infrastructure may not deliver that figure anyway. Moving 2 bits from sequence to timestamp leaves 1,024 values per millisecond and stretches the span to about 279 years. Twitter’s original Snowflake used 41 time bits, 10 machine bits, and 12 sequence bits; Discord documents a 42-bit timestamp from a 2015 epoch. Never change a layout silently if IDs from two schemes share a namespace.
A design doubles sequence bits but keeps the ID at 64 bits. What must give way?
Another field loses bits, reducing time horizon or worker namespace. Recompute the lifetime and deployment capacity before changing the layout.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Field widths are a capacity budget that must fit the contract.
- The epoch and layout become durable compatibility rules.