System DesignOct 4, 2026⏱️ 3 min read
Design a Distributed Unique ID Generator: Twitter Snowflake, ULID & Clock Drift

Design a Distributed Unique ID Generator: Twitter Snowflake, ULID & Clock Drift

Why Auto-Increment Breaks at Scale

Single-database 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.
We need IDs that are 64-bit numeric, globally unique, loosely time-sortable (k-sorted), and generated at > 10,000 IDs/sec per node with zero cross-node locking.
64-Bit Snowflake ID Structure

64-Bit Snowflake ID Structure


1. Comparing Distributed ID Strategies

ApproachSizeSortable by Time?Coordination Needed?B-Tree Index Friendly?
Multi-Master Auto-Increment (+N)64-bitPartiallyHard to rescale $N$Yes
UUIDv4 (Random)128-bit❌ NoNone❌ Very poor (random B-Tree writes)
Database Ticket Server (Flickr)64-bitYesSingle/Dual DB SPOFYes
ULID / UUIDv7128-bitMillisecond sortedNoneYes
Twitter Snowflake64-bitMillisecond sortedStartup node ID only** Optimal (BIGINT)**

2. Inside the 64-Bit Snowflake Architecture

A Snowflake ID packs four components into a single signed 64-bit integer:
| 1 bit |        41 bits        |   5 bits   |   5 bits   |   12 bits   |
| Sign  |   Timestamp (ms)      | Datacenter | Machine ID |  Sequence   |
  • 1 bit (Sign): Always 0 so 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 0 each millisecond, supporting $4,096$ IDs per millisecond per worker (~4 million IDs/sec per node!).

3. Clean Snowflake Generator in Python

python
import 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

  1. 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.
  2. 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.
  3. Node ID Assignment: Lease worker IDs via ZooKeeper, etcd, or Kubernetes StatefulSet ordinals at startup.

Share this article

Comments