Sub topic 9
Snowflake-style IDs: timestamp, worker, sequence
This chapter assumes you know what a B-tree index is and how bit shifting and masking work. It also assumes you have met UUIDs and time-ordered IDs in the earlier chapters. Here you will build a Snowflake-style generator and learn how it fails.
The idea
A Snowflake-style ID is a single 64-bit integer built from three fields. Twitter introduced the design and called it Snowflake. Many systems now use variants of it, such as Discord, Instagram and Sonyflake.
Each field answers one question:
- The timestamp says when the ID was made.
- The worker ID says which generator made it.
- The sequence number says which ID within that millisecond on that worker it is.
Two IDs can only be equal if all three fields match. If every worker has a distinct ID, and each worker never repeats a (timestamp, sequence) pair, uniqueness holds with no network call at generation time.
| Field | Bits | Range | Meaning |
|---|---|---|---|
| Sign bit | 1 | always 0 | Keeps the value positive in signed 64-bit integers |
| Timestamp | 41 | 0 to 2^41 − 1 | Milliseconds since a custom epoch |
| Worker ID | 10 | 0 to 1023 | Which generator produced the ID |
| Sequence | 12 | 0 to 4095 | Counter within one millisecond |
The bit counts are a design choice, not a rule. A system with fewer, larger machines might use 5 worker bits and 17 sequence bits.
Why the timestamp comes first
The timestamp occupies the highest bits, so comparing two IDs as integers compares their timestamps first. IDs made in different milliseconds therefore sort by creation time. New rows land at the right-hand edge of a B-tree index, which gives the insert locality that random UUID v4 values lack.
Within one millisecond the order is looser:
- On one worker, the sequence increases, so IDs from that worker are strictly ordered.
- Across workers, IDs from the same millisecond sort by worker ID, not by real creation order.
- Worker clocks differ slightly, so the order across workers is only approximately chronological.
This property is called k-sortable: the order is correct up to a small window. Do not use Snowflake order to decide which of two events from different workers happened first.
Capacity
The sizes of the fields set the limits.
- Lifetime: 2^41 ms is about 2.2 × 10^12 ms, or roughly 69.7 years from the epoch.
- Per-worker rate: 4096 IDs per millisecond is about 4.1 million IDs per second.
- Cluster rate: 1024 workers at that rate is about 4.2 billion IDs per second.
The epoch is custom, not 1970, because the timestamp field stores the offset from it. A recent epoch makes the 69.7 years start now. Choose the epoch once, when you launch. Changing it later breaks the ordering of old and new IDs and can produce duplicates.
A working generator
The class below keeps the last timestamp and the sequence, and protects both with a lock.
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 generator makes three decisions on every call, shown below.
Walking through the packing
Suppose now - epoch_ms is 1000, the worker ID is 7, and the sequence is 0.
- The timestamp shifts left by 22 bits (10 worker bits plus 12 sequence bits): 1000 × 4,194,304 = 4,194,304,000.
- The worker ID shifts left by 12 bits: 7 × 4096 = 28,672.
- The sequence adds 0.
- The bitwise OR gives 4,194,332,672. OR is safe here because the fields occupy separate bit ranges.
Decoding an ID
Because the fields are plain bit ranges, you can take an ID apart. This helps with debugging and with inspecting production data.
def decode(snowflake_id, epoch_ms=1_700_000_000_000):
sequence = snowflake_id & 0xFFF # low 12 bits
worker_id = (snowflake_id >> 12) & 0x3FF # next 10 bits
timestamp_ms = (snowflake_id >> 22) + epoch_ms
return timestamp_ms, worker_id, sequence
print(decode(4_194_332_672)) # (1700000001000, 7, 0)Behavior to know about
- Sequence resets to 0 each millisecond. At low traffic nearly every ID ends in sequence 0. If you shard by
id % Nand N divides 4096, the shards become uneven, because the low bits are not random. Hash the ID, or shard by a higher field, instead. - A thread lock is not enough across processes. The lock only protects one generator object in one process. Two processes with the same worker ID are two generators that can collide.
- The busy-wait is short but real. When one worker exhausts 4096 IDs in a millisecond, the code spins for at most the rest of that millisecond.
- Large integers break some clients. JavaScript numbers are exact only up to 2^53 − 1. A 64-bit Snowflake ID can exceed that and be silently rounded. Send IDs as strings in JSON for such clients.
Failure modes
The scheme is only as safe as its two assumptions: worker IDs are unique, and each worker's clock never repeats a timestamp.
| Failure | What happens | Mitigation |
|---|---|---|
| Two live generators share a worker ID | Both can produce the same timestamp and sequence, so duplicate IDs appear | Assign worker IDs through a coordinator or lease |
| Clock steps backwards (NTP correction, VM restore) | The generator may reissue earlier timestamps with the same sequence values | Refuse or wait, and persist the last timestamp |
| Restart after a clock regression | The in-memory `last_ms` is lost, so the guard cannot see the regression | Store `last_ms` durably, or wait out the maximum expected skew at startup |
| Worker ID space exhausted | More than 1024 generators need IDs | Reallocate bits, or give each process an ID from a lease pool |
| Epoch overflow | After about 69.7 years the 41-bit field overflows | Plan a migration well before the limit |
Clock behavior
The sample generator raises an error when the clock moves backwards. That is the safe default, and the cost is that the worker stops issuing IDs until an operator or a retry resolves it. Two alternatives exist:
- Wait. If the regression is small, say a few milliseconds, sleep until the clock catches up to
last_ms. Cap the wait and fail beyond it. - Use a monotonic floor. Keep
last_msand never issue a timestamp below it, even when the wall clock is lower. This keeps IDs unique but lets the embedded timestamp drift from real time.
Assigning worker IDs
You need a way to give each live generator a distinct ID in 0 to 1023. Common approaches:
- Static configuration. Each host has a fixed ID in its deployment config. This is simple, but it fails when autoscaling or a copy-paste mistake duplicates an ID.
- A coordination service. A store such as ZooKeeper, etcd or a database row hands out IDs with a lease. The generator registers at startup and renews the lease. Coordination happens once per process, not once per ID.
- Derived from infrastructure. Some systems derive the ID from a pod ordinal or an IP address. This works only if the derived value is unique and fits in 10 bits.
If a lease can expire while the process keeps running, the ID can be reissued to a second process. Make the generator stop issuing IDs when it can no longer prove it holds the lease.
Snowflake compared with the alternatives
| Property | UUID v4 | UUID v7 | Snowflake |
|---|---|---|---|
| Size | 128 bits | 128 bits | 64 bits |
| Coordination | None | None | Worker ID assignment |
| Uniqueness | Probabilistic | Probabilistic | Guaranteed if assumptions hold |
| Time order | None | Millisecond | Millisecond |
| Index locality | Poor | Good | Good |
| Native database type | Often yes | Often yes | Integer |
The 64-bit size halves the storage in each index entry and in every foreign key that refers to the ID. Snowflake IDs also give a hard uniqueness guarantee instead of a very small probability. The price is the operational work of worker IDs and clock handling.
Predictability
Snowflake IDs leak information. Anyone can decode the creation time of a record, and from the sequence and worker fields they can estimate how many IDs are created. Sequential values are also easy to guess. Do not use them as secrets or as the only access control on a public URL. Check authorization on the server for every request.
Exercise
A service runs 300 Snowflake generators using the 41/10/12 layout. One generator is busy and needs to produce 6000 IDs within a single millisecond. What does the sample generator do, and what is the maximum rate it can sustain from that one generator?
Show answer
The generator issues 4096 IDs (sequence 0 to 4095) in that millisecond. When the sequence wraps to 0, it spins until the next millisecond begins, then continues with sequence 0 there. The remaining 1904 IDs come from the following millisecond. The sustained maximum is 4096 IDs per millisecond, or about 4.1 million IDs per second.
Exercise
An operator restores a VM from a snapshot taken 10 seconds ago. The Snowflake process starts with the same worker ID and its in-memory state is empty. Why can this produce duplicate IDs even though the clock check exists, and what should the generator do?
Show answer
The check compares the clock with last_ms, but last_ms starts at -1 after a restart, so the 10-second regression goes unnoticed. The generator can reissue timestamps it already used, with the same worker ID and sequence values. It should persist last_ms durably, or wait out the maximum possible clock regression at startup before issuing IDs, or take a fresh worker ID from the coordinator.