Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Distributed
Unique ID Generator.

A Snowflake-style 64-bit distributed ID generator packs a 41-bit custom-epoch timestamp, 10-bit worker ID, and 12-bit per-ms sequence counter to mint 4.09M+ unique, time-sortable IDs/sec per node with zero network consensus.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, use a 64-bit Snowflake layout with a custom epoch for B-Tree index locality and zero runtime coordination, and guard against NTP clock rollbacks and 4,096/ms sequence overflows.

TL;DR30-second simplified summary
▾

Core Mechanics: Distributed databases (10,000+ IDs/sec per node, 100,000+ IDs/sec cluster-wide) need globally unique primary keys without a central auto-increment bottleneck.

Visual & Structural Flow: Depicts 1b Sign | 41b Timestamp (69y) | 10b Worker | 12b Sequence (Custom Epoch -> Bit-Packer -> Worker ID -> Sequence); Normal Mint -> Sequence Overflow -> Clock Rollback Protection (MINT_ID -> SPIN_NEXT_MS -> CLOCK_GUARD).

Trade-Offs & Production: Teams often start with UUID.randomUUID() or a central MySQL REPLACE INTO tickets64: UUIDv4 Write Amplification: Random inserts dirty random 16 KB InnoDB pages, exhausting the buffer pool. Production Snowflake generators run locally on each worker with strict edge-case handling: Startup Worker Lease: Obtain a unique 10-bit worker_id (0..1023) from.

Failure Modes & Application: Snowflake-style IDs are foundational wherever sharded databases need sortable primary keys: Social Feeds & Messaging (Twitter / Discord): Ordering tweets and chat messages chronologically by id without a separate timestamp index.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Database Sharding & Range Partitioning
Horizontally partitioning a dataset across independent database nodes by a shard key—using either contiguous key ranges or consistent hashing—to scale write throughput and storage beyond a single primary's CPU, IOPS, and memory ceiling.
Consistency & Consensus Replication (Raft / Paxos)
Fault-tolerant replication protocols (Raft, Multi-Paxos, Quorum) that keep distributed state consistent across node crashes and network partitions using majority quorums (2f+1) and monotonic term numbers.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why 64-bit time-sortable IDs matter for distributed databases.

Why this matters: The mechanism: understand how Why 64-bit time-sortable IDs matter for distributed databases works from first principles.

Distributed databases (10,000+ IDs/sec per node, 100,000+ IDs/sec cluster-wide) need globally unique primary keys without a central auto-increment bottleneck.

Random 128-bit UUIDv4 keys are twice as wide and cause random B-Tree page splits in InnoDB/Postgres, degrading write IOPS by 3×–5×.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens with UUIDv4, central DB sequences, or naive clocks.

Why this matters: The problem: see what breaks without What happens with UUIDv4, central DB sequences, or naive clocks under real concurrency or scale.

Three common ID schemes fail under distributed scale:

  1. Central DB AUTO_INCREMENT: Becomes a single point of failure and cross-AZ latency bottleneck.
  2. Random UUIDv4: 128-bit random keys fragment B-Tree indexes and bloat secondary indexes.
  3. NTP Clock Rollback: If a node's system clock steps backward by 50 ms, a naive timestamp+counter generator emits duplicate IDs.
64-Bit Snowflake Anatomy

1b Sign | 41b Timestamp (69y) | 10b Worker | 12b Sequence

Custom Epoch41b ms (69.7 yrs)Bit-PackerZero network RTTWorker ID10b = 1,024 nodesSequence12b = 4,096 / ms

1.41-Bit Timestamp: Milliseconds since custom epoch (e.g. 2026-01-01) gives ~69.7 years.

2.10-Bit Worker ID: 5-bit datacenter + 5-bit machine ID assigned at boot via ZooKeeper/etcd.

3.12-Bit Sequence: Supports 4,096 IDs/ms (4.09M IDs/sec) per node before spin-waiting next ms.

4.B-Tree Locality: Monotonic high bits append cleanly to the right edge of SQL B-Trees.

Packing timestamp, worker ID, and sequence into int64 yields sub-millisecond local generation with zero consensus on the hot path.

Engineering Decision Framework
Problem
How to implement Design a Distributed Unique ID Generator without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, use a 64-bit Snowflake layout with a custom epoch for B-Tree index locality and zero runtime coordination, and guard against NTP clock rollbacks and 4,096/ms sequence overflows.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Distributed Unique ID Generator experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why UUIDv4 or DB ticket servers break).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

Teams often start with UUID.randomUUID() or a central MySQL REPLACE INTO tickets64:

  • UUIDv4 Write Amplification: Random inserts dirty random 16 KB InnoDB pages, exhausting the buffer pool.
  • Central Ticket DB: Adds a network RTT to every write and fails if the ticket DB goes down.
Design Trade-Off

Naive solution (and why UUIDv4 or DB ticket servers break)

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Snowflake Bit-Packing + Clock-Rollback & Overflow Guards.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Production Snowflake generators run locally on each worker with strict edge-case handling:

  • Startup Worker Lease: Obtain a unique 10-bit worker_id (0..1023) from ZooKeeper/etcd/K8s StatefulSet ordinal—zero runtime consensus.
  • Sequence Overflow: When sequence hits 4,095 within the same millisecond, spin-wait (til_next_millis) until the clock advances.
  • Clock Rollback Guard: Use monotonic clock deltas anchored at boot, or if now < last_ts, wait out small drifts (<= 5 ms) and raise an alert / rotate worker ID on large backward jumps.
Generator Guardrails

Normal Mint -> Sequence Overflow -> Clock Rollback Protection

4096th ID in same msclock advances +1msbackward clock jumpMINT_IDseq < 4096, ts >= lastSPIN_NEXT_MSseq == 4095 overflowCLOCK_GUARDts < last_ts (NTP)

Explicit handling of sequence overflow and NTP clock rollbacks guarantees uniqueness without cross-node locks.

import threading, time

class SnowflakeGenerator:
    EPOCH_MS = 1767225600000  # 2026-01-01T00:00:00Z
    WORKER_BITS = 10
    SEQ_BITS = 12
    MAX_SEQ = (1 << SEQ_BITS) - 1

    def __init__(self, worker_id: int):
        if not (0 <= worker_id < (1 << self.WORKER_BITS)):
            raise ValueError("worker_id out of 10-bit range")
        self.worker_id = worker_id
        self.last_ms = -1
        self.seq = 0
        self._lock = threading.Lock()

    def _now_ms(self) -> int:
        return int(time.time() * 1000)

    def next_id(self) -> int:
        with self._lock:
            now = self._now_ms()
            if now < self.last_ms:
                if self.last_ms - now <= 5:
                    while now < self.last_ms:
                        now = self._now_ms()
                else:
                    raise RuntimeError("Clock moved backwards beyond 5ms tolerance")
            if now == self.last_ms:
                self.seq = (self.seq + 1) & self.MAX_SEQ
                if self.seq == 0:
                    while now <= self.last_ms:
                        now = self._now_ms()
            else:
                self.seq = 0
            self.last_ms = now
            return ((now - self.EPOCH_MS) << 22) | (self.worker_id << 12) | self.seq
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Distributed 64-Bit IDs are used in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Snowflake-style IDs are foundational wherever sharded databases need sortable primary keys:

  • Social Feeds & Messaging (Twitter / Discord): Ordering tweets and chat messages chronologically by id without a separate timestamp index.
  • Distributed Ledger & Order IDs: Partitioning orders across sharded MySQL/Postgres clusters with zero central coordination.
  • Observability Trace & Span IDs: Generating high-throughput unique IDs locally on every microservice pod.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why do 64-bit Snowflake IDs outperform random UUIDv4 primary keys in B-Tree databases like InnoDB or PostgreSQL?

Recommended Learning Flow