Day 09 · System Design
Distributed Unique ID Generation (Twitter Snowflake & UUIDv7)
How to generate unique, roughly time-sortable IDs across many servers without a central database.
01Overview & core concept
In a single relational database, unique primary keys are easily generated using AUTO_INCREMENT or sequences. In a distributed, sharded architecture with hundreds of microservices writing concurrently, relying on a centralized database for ID generation creates a single point of failure (SPOF) and a severe throughput bottleneck. Distributed systems need IDs that satisfy four constraints.
Global Uniqueness
Zero collisions across all servers and regions.
Rough Time-Sortability (k-sortable)
IDs increase chronologically to maintain index clustering in B-trees, preventing random disk I/O and page fragmentation.
High Throughput & Low Latency
Generating an ID must be an in-memory operation (under 1 microsecond) with zero network hops per request.
Compact Size
Typically 64 bits (fits a standard unsigned BIGINT) or 128 bits.
02Architecture & request flow
0 1 42 52 63 ┌────────┬────────────────────────────────┬───────────────┬─────────────┐ │ 1 Bit │ 41 Bits Timestamp │ 10 Bits Node │ 12 Bits Seq │ │ Unused │ (Milliseconds since Epoch) │ (Machine ID) │ (Counter) │ └────────┴────────────────────────────────┴───────────────┴─────────────┘
The Twitter Snowflake algorithm generates 64-bit, roughly time-ordered IDs without inter-node network coordination.
Snowflake bit breakdown
1 Bit (Sign)
Always 0, to keep the integer positive.
41 Bits (Timestamp)
Millisecond precision from a custom epoch (e.g., system launch date). 2^41 ms is about 69.7 years of operational lifespan before the epoch must be reset.
10 Bits (Node / Machine ID)
Supports up to 1,024 distinct worker instances (often split into 5 bits Data Center ID + 5 bits Worker ID).
12 Bits (Sequence Number)
Incremented for every ID generated within the same millisecond on the same node: 4,096 IDs per millisecond per node (about 4.096 million IDs/second/node). Resets to 0 when the clock ticks to the next millisecond.
Other ID strategies
Ticket Server (Flickr pattern)
Uses dedicated MySQL instances with REPLACE INTO and LAST_INSERT_ID() with distinct increments. Limitation: network latency per ID, and it is difficult to scale writes past 10k/sec.
UUIDv7 (modern 128-bit standard)
Encodes 48 bits of Unix millisecond timestamp at the beginning, followed by 74 random bits. Ideal for systems that can afford 128-bit storage without central worker ID provisioning.
03Real-world example: Discord Message & Channel IDs
Snowflake IDs Across All Entities
Discord uses 64-bit Snowflake IDs for messages, guilds, channels, and users.
Efficient Pagination
Because Snowflake IDs are chronological, Discord paginates message queries with simple inequalities instead of heavy SQL offsets:
SELECT * FROM messages WHERE channel_id = :channel_id AND message_id < :oldest_seen_snowflake ORDER BY message_id DESC LIMIT 50;
Worker ID Allocation
Worker IDs are assigned automatically on startup using ZooKeeper, etcd, or Kubernetes StatefulSet ordinal indices (app-0, app-1, etc.).
04Architectural trade-offs
| Strategy | Size | Time-Ordered | Coordination | Index Efficiency |
|---|---|---|---|---|
| UUIDv4 | 128-bit | No (random) | None (decentralized) | Poor (B-tree splits) |
| UUIDv7 | 128-bit | Yes (ms) | None (decentralized) | High (sequential) |
| Ticket Server (MySQL) | 64-bit | Yes | Centralized DB | High |
| Snowflake ID | 64-bit | Yes (ms) | Worker ID config | Optimal (64-bit int) |
Failure modes & mitigations
Clock Drift & Backward Clock Shifts (NTP Sync)
If a server's clock adjusts backward (e.g., via NTP slew or step), generating an ID with a past millisecond can collide with earlier IDs. Mitigations: if the shift is under about 5 ms, pause and spin-wait until the clock catches up; if it is significant, refuse ID generation and trigger an alert, or borrow sequence bits to advance the virtual timestamp.
Sequence Overflow in 1 Millisecond
If a single worker generates more than 4,096 IDs within 1 ms, it must block or spin until the clock advances to the next millisecond.
05Interview question & approach
Design a globally distributed, high-performance unique ID generation service that produces 64-bit time-sortable IDs for an e-commerce order processing pipeline supporting 20 million order events per second across 3 cloud regions.
Algorithm & Architecture Selection
Propose an in-process Snowflake generator embedded as a shared library or sidecar daemon in application containers, eliminating remote network RPC overhead.
Bit Structure Customization
41 bits timestamp + 3 bits Region ID (up to 8 regions) + 8 bits Node ID (up to 256 worker nodes per region) + 12 bits sequence counter.
Provisioning Machine IDs
Explain dynamic registration of Worker IDs using etcd or Consul with ephemeral heartbeats and TTL leases, so IDs are recycled when pods restart.
Handling Clock Drift & High Concurrency
Use monotonic system clocks (CLOCK_MONOTONIC_RAW) where available, and define a fallback strategy for NTP step changes.