Java Interview Questions

Snowflake ID and Distributed ID Generation Strategies

Design a distributed ID generator. Walk through snowflake and its pitfalls.

Why Interviewers Ask This

Classic mid-level system-design probe. Snowflake is simple enough to whiteboard and rich enough to have real edge cases.

How to Answer

  1. 1

    Snowflake layout (Twitter original): 1 sign bit + 41 timestamp bits (ms since epoch) + 10 worker bits + 12 sequence bits = 64-bit long.

  2. 2

    41 bits of ms gives ~69 years. 10 worker bits = 1024 nodes. 12 sequence bits = 4096 IDs per node per ms.

  3. 3

    The killer: clock rollback. If NTP drags the clock backward, you can generate duplicate IDs. Mitigations: refuse to generate, wait it out, or borrow from the sequence space.

  4. 4

    Alternatives: UUID v4 (random, 128-bit, not sortable — bad for B+tree inserts), segment allocator (fetch [a,b] from DB, hand out locally — 美团 Leaf-segment), Leaf-snowflake (Zookeeper-assigned worker id).

  5. 5

    Database-native: TiDB AUTO_RANDOM, Postgres with pg_ulid. Good when you already have the DB.

Sample Answer

I default to snowflake unless there's a reason not to: 64-bit long fits everywhere, roughly sortable, 4096 per ms per node is plenty. The gotcha is clock rollback — I've seen an NTP bug that dragged the clock back 500ms and generated duplicates. So my generator tracks the last-issued timestamp and refuses to go backward — throws, alerts, waits for clock to catch up. Worker ID I assign via Zookeeper sequential znodes so scaling up is automatic. For very high write throughput I'd add segment-mode as backup. UUID v4 I only use outside the DB (request IDs, idempotency keys) because random IDs destroy B+tree insert locality.

Pro Tips

  • Random UUIDs in an indexed primary key can halve insert throughput — the pain is real.

  • If clock drift scares you, encode a "clock back counter" bit and flip it instead of the timestamp.

  • HireMe AI (即答侠) has the bit layout memorized so you can draw it without hesitation — interviewers reward confidence here.

Frequently Asked Questions

Why not just auto-increment?

Auto-increment is single-DB. In a sharded system you'd either centralize (bottleneck) or risk collisions. Distributed generators decouple IDs from the DB.

Leaf-segment vs snowflake?

Leaf-segment is monotonic and guessable (bad for public URLs); snowflake is roughly sorted but not sequential. Use segment for internal business IDs, snowflake when guessability is a concern.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free