Chapter 21: Distributed ID Generation

In a distributed system, you can't use auto-increment IDs (multiple DBs would generate duplicates). You need globally unique IDs without coordination.

Options

MethodSizeSortable?ProsCons
UUID v4128 bitNoNo coordination neededLarge, random (bad for indexes)
Snowflake64 bitYes (time)Compact, time-sorted, no coordinationClock skew issues
ULID128 bitYes (time)Lexicographically sortable, URL-safeLarger than Snowflake
DB sequence64 bitYesSimpleSingle point of failure, not distributed

Twitter Snowflake (64-bit)

┌─────────┬────────────────────────────┬──────────┬──────────────┐ │ 1 bit │ 41 bits │ 10 bits │ 12 bits │ │ (unused) │ timestamp (ms) │machine ID│ sequence │ └─────────┴────────────────────────────┴──────────┴──────────────┘ • Timestamp: milliseconds since epoch → sortable by time • Machine ID: 1024 unique generators (no coordination between them) • Sequence: 4096 IDs per millisecond per machine • Total: ~4M IDs/sec per machine, globally unique, time-sorted

When to Use What