Sub topic 9
Snowflake-style IDs: timestamp, worker, sequence
This chapter assumes you know what a B-tree index is, can read bit shifts in Python, and understand that distributed nodes can fail independently. Earlier chapters showed that random IDs need no coordination but sort poorly, and that time-ordered IDs fix much of that. Snowflake-style IDs go further. They fit in 64 bits and guarantee uniqueness by construction instead of by probability.
The idea
A Snowflake ID splits a 64-bit integer into three fields:
| Field | Bits | Purpose |
|---|---|---|
| Timestamp | 41 | Milliseconds since a custom epoch |
| Worker ID | 10 | Identifies the generator, so up to 1024 workers |
| Sequence | 12 | Counter within one millisecond, so up to 4096 IDs |
The leading bit is left at zero so the value stays positive in signed 64-bit columns. This is the layout in the code below, with the sign bit unused.
Two workers never share a worker ID, so they never produce the same ID. One worker never repeats a (timestamp, sequence) pair, so it never repeats itself. No network call is needed at generation time.
A working generator
The class below packs the three fields with shifts. It uses a lock so that threads in one process cannot read the same sequence number.
import threading
import time
class Snowflake:
WORKER_BITS = 10
SEQUENCE_BITS = 12
MAX_SEQUENCE = (1 << SEQUENCE_BITS) - 1
def __init__(self, worker_id, epoch_ms=1_700_000_000_000):
if not 0 <= worker_id < (1 << self.WORKER_BITS):
raise ValueError("worker_id must fit in 10 bits")
self.worker_id = worker_id
self.epoch_ms = epoch_ms
self.last_ms = -1
self.sequence = 0
self.lock = threading.Lock()
@staticmethod
def _now_ms():
return time.time_ns() // 1_000_000
def next_id(self):
with self.lock:
now = self._now_ms()
if now < self.last_ms:
raise RuntimeError("clock moved backwards; refusing to generate IDs")
if now == self.last_ms:
self.sequence = (self.sequence + 1) & self.MAX_SEQUENCE
if self.sequence == 0:
# Sequence exhausted for this millisecond: wait for the next one.
while now <= self.last_ms:
now = self._now_ms()
else:
self.sequence = 0
self.last_ms = now
return ((now - self.epoch_ms) << (self.WORKER_BITS + self.SEQUENCE_BITS)) \
| (self.worker_id << self.SEQUENCE_BITS) \
| self.sequence
gen = Snowflake(worker_id=7)
print(gen.next_id())
print(gen.next_id())The key steps in next_id are:
- Read the current millisecond.
- If it equals the last millisecond used, increment the sequence. If the sequence wraps to 0, all 4096 values are used, so spin until the next millisecond.
- If it is a new millisecond, reset the sequence to 0.
- Shift the timestamp left by 22 bits (10 + 12), shift the worker ID left by 12 bits, and combine the three with bitwise OR.
The default epoch is a custom start date, not 1970. Subtracting it gives the 41-bit field more usable time. 2^41 milliseconds is about 69.7 years, so the IDs last until roughly the year 2093 with this epoch.
Properties and limits
- Size: 64 bits fits a
BIGINTcolumn and is half the size of a UUID. - Ordering: IDs from one worker increase strictly. IDs from different workers are ordered by millisecond, but within one millisecond the worker ID decides the order, not the real creation order. This is "roughly sorted", not a total order.
- Throughput: each worker can issue at most 4096 IDs per millisecond, about 4 million per second.
- Coordination: none at generation time, but every worker needs a unique ID assigned beforehand. The next chapters cover that and the clock problems the code above only partly handles.
The RuntimeError on a backwards clock is a safe default. Continuing would risk reusing a (timestamp, sequence) pair that was already issued.
Exercise
A Snowflake worker has issued 4096 IDs in millisecond T, and the sequence has wrapped to 0. What does the generator in this chapter do, and why does it not simply keep issuing IDs with sequence 0?
Show answer
It waits (spins) until the clock reaches millisecond T+1 before returning. Issuing sequence 0 again within millisecond T would repeat the exact same (timestamp, worker, sequence) combination as the first ID of that millisecond, producing a duplicate.