Design a Distributed Unique ID Generator: Twitter Snowflake, ULID & Clock Drift
Why Auto-Increment Breaks at Scale
AUTO_INCREMENT integers work great on one machine, but break down immediately in distributed systems:- Sharded Databases: Two independent PostgreSQL shards both generate
id = 1001, causing collisions. - UUIDv4 Fails DB Indexing: Standard 128-bit random UUIDs (
uuid4) are completely unordered. Inserting random UUIDs into a B-Tree primary key causes constant random page splits, destroying cache locality and write throughput.
64-Bit Snowflake ID Structure
1. Comparing Distributed ID Strategies
| Approach | Size | Sortable by Time? | Coordination Needed? | B-Tree Index Friendly? |
|---|---|---|---|---|
Multi-Master Auto-Increment (+N) | 64-bit | Partially | Hard to rescale $N$ | Yes |
| UUIDv4 (Random) | 128-bit | ❌ No | None | ❌ Very poor (random B-Tree writes) |
| Database Ticket Server (Flickr) | 64-bit | Yes | Single/Dual DB SPOF | Yes |
| ULID / UUIDv7 | 128-bit | Millisecond sorted | None | Yes |
| Twitter Snowflake | 64-bit | Millisecond sorted | Startup node ID only | ** Optimal (BIGINT)** |
2. Inside the 64-Bit Snowflake Architecture
| 1 bit | 41 bits | 5 bits | 5 bits | 12 bits |
| Sign | Timestamp (ms) | Datacenter | Machine ID | Sequence |
- 1 bit (Sign): Always
0so IDs stay strictly positive in signed languages (Java/SQL). - 41 bits (Timestamp): Milliseconds since a custom epoch (e.g.,
2020-01-01). Gives $2^{41} \approx 69.7\text{ years}$ of lifespan. - 5 bits (Datacenter ID): Up to $2^5 = 32$ datacenters.
- 5 bits (Machine ID): Up to $2^5 = 32$ machines per datacenter ($1,024$ workers total).
- 12 bits (Sequence Counter): Resets to
0each millisecond, supporting $4,096$ IDs per millisecond per worker (~4 million IDs/sec per node!).
3. Clean Snowflake Generator in Python
pythonimport time import threading class SnowflakeGenerator: CUSTOM_EPOCH_MS = 1704067200000 # 2024-01-01T00:00:00Z def __init__(self, datacenter_id: int, worker_id: int): assert 0 <= datacenter_id < 32 assert 0 <= worker_id < 32 self.datacenter_id = datacenter_id self.worker_id = worker_id self.sequence = 0 self.last_timestamp = -1 self.lock = threading.Lock() @staticmethod def _current_ms() -> int: return int(time.time() * 1000) def next_id(self) -> int: with self.lock: now = self._current_ms() if now < self.last_timestamp: # Guard against NTP backwards clock skew offset = self.last_timestamp - now if offset <= 5: time.sleep(offset / 1000.0) now = self._current_ms() else: raise RuntimeError(f"Clock moved backwards by {offset} ms") if now == self.last_timestamp: self.sequence = (self.sequence + 1) & 0xFFF # 4095 mask if self.sequence == 0: # Wait for next millisecond while now <= self.last_timestamp: now = self._current_ms() else: self.sequence = 0 self.last_timestamp = now return ( ((now - self.CUSTOM_EPOCH_MS) << 22) | (self.datacenter_id << 17) | (self.worker_id << 12) | self.sequence )
4. Production Edge Cases to Watch
- NTP Clock Synchronization & Leap Seconds: If NTP steps the system clock backwards, duplicate IDs could occur. Use clock slewing (gradual drift adjustment) rather than hard jumps, and fail or pause if
now < last_timestamp. - Bit Allocation Tuning: Low-concurrency apps expecting $> 100$ years can shrink Sequence bits and expand Timestamp bits; high-throughput telemetry systems can swap DC/Machine bits for larger worker fleets.
- Node ID Assignment: Lease worker IDs via ZooKeeper, etcd, or Kubernetes StatefulSet ordinals at startup.