How would you generate unique IDs in a distributed system?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Options: UUID/GUID (random 128-bit, no coordination but large and unordered), database auto-increment (simple but a bottleneck and SPOF), and Snowflake-style IDs (timestamp + worker ID + sequence, roughly ordered and coordination-free). For most distributed systems, a Snowflake-style ID (or a ULID) gives you uniqueness, rough time-ordering, and no central coordinator.
Detailed explanation
Unique IDs at scale must be unique across many machines without coordination. UUID v4: 122 random bits, virtually zero collision risk, no coordination needed. Downsides: 128 bits (large index), not time-ordered (bad for B-tree insert locality), and unreadable. UUID v7 and ULID fix ordering by prefixing a timestamp. Database auto-increment: simple and ordered, but the single DB is a write bottleneck and single point of failure; composite (shard_id, local_increment) works but is fiddly. Snowflake (Twitter, 64 bits): 41 bits timestamp (milliseconds since epoch, good for ~70 years), 10 bits worker ID (up to 1024 machines), 12 bits sequence number (4096 IDs per millisecond per worker). Roughly time-ordered, fits in a bigint, coordination-free after worker-ID assignment. Worker IDs can be assigned via ZooKeeper, a config service, or (simplastically) from a machine's IP hash. Variants: Discord's Snowflake, Sony's Sonyflake, Instagram's ID scheme. The choice depends on whether you need ordering (Snowflake/ULID) versus pure simplicity (UUID v4) versus strict sequential (auto-increment).
Example
Snowflake 64-bit layout:
| 1 bit unused | 41 bits timestamp | 10 bits worker ID | 12 bits sequence |
Example ID: 138726354944
- Timestamp: 2024-01-15 10:30:00.000 UTC
- Worker: 42
- Sequence: 1000 (1000th ID this ms on this worker)
Roughly sortable by creation time, unique across 1024 workers.Interview tip
Name all three approaches (UUID, auto-increment, Snowflake) and the trade-off each optimizes. Then show the Snowflake bit layout — that concrete detail is what interviewers remember.
Common mistakes
- Only naming UUID without mentioning ordering trade-offs.
- Not knowing the Snowflake bit layout.
- Forgetting that auto-increment does not scale horizontally.