Full answer
Requirements
Functional:
- Return a new unique 64-bit integer ID on request, fast.
- IDs sort roughly by creation time, so newer rows have larger IDs.
Non-functional:
- 1M IDs per second in total, with low latency (a local call or a microsecond-level library function).
- No single point of failure; keeps working if one data centre is cut off.
- IDs are never reused, even after restarts.
Capacity estimates
Assumptions: 1M IDs per second at peak, generators embedded in application servers or run as a small service.
- Time bits: 2^41 milliseconds is about 69.7 years from the chosen epoch.
- Machine bits: 2^10 = 1,024 generators.
- Sequence bits: 2^12 = 4,096 IDs per millisecond per generator, about 4.1M per second per generator.
- So one generator could serve the whole 1M per second; many generators exist for availability and locality.
API
GET /v1/ids?count=100 -> {"ids": [7387719012345856001, ...]}
In practice most systems embed the generator as a library, so the "API" is next_id() with no network call.
Data model
No per-ID storage. The only state is:
machine_idper generator, leased from a coordination service (etcd or ZooKeeper) or derived from configuration (data centre bits plus worker bits).- The last timestamp and sequence in memory.
High-level design
flowchart LR
A[App server] --> G1[ID generator lib, machine 17]
B[App server] --> G2[ID generator lib, machine 18]
G1 -. "lease machine ID at start" .-> ZK[(Coordination service)]
G2 -. "lease machine ID at start" .-> ZKThe generator
import threading
import time
EPOCH_MS = 1_767_225_600_000 # 2026-01-01T00:00:00Z, a custom epoch
class Snowflake:
"""64-bit IDs: 41 bits time (ms) | 10 bits machine | 12 bits sequence."""
def __init__(self, machine_id, clock=lambda: int(time.time() * 1000)):
assert 0 <= machine_id < 1024
self.machine_id, self.clock = machine_id, clock
self.last_ms, self.seq = -1, 0
self.lock = threading.Lock()
def next_id(self):
with self.lock:
now = self.clock()
if now < self.last_ms:
raise RuntimeError("clock moved backwards; refuse to issue IDs")
if now == self.last_ms:
self.seq = (self.seq + 1) & 0xFFF
if self.seq == 0: # 4,096 IDs used this ms: wait
while now <= self.last_ms:
now = self.clock()
else:
self.seq = 0
self.last_ms = now
return ((now - EPOCH_MS) << 22) | (self.machine_id << 12) | self.seq
if __name__ == "__main__":
gen = Snowflake(machine_id=7)
ids = [gen.next_id() for _ in range(10_000)]
assert len(set(ids)) == len(ids) and ids == sorted(ids)
assert (ids[0] >> 12) & 0x3FF == 7 # machine bits round-trip
t = [1_767_225_600_005]
stuck = Snowflake(1, clock=lambda: t[0])
stuck.next_id()
t[0] -= 1
try:
stuck.next_id()
raise AssertionError("expected RuntimeError")
except RuntimeError:
pass
print("ok: 10000 unique, sorted IDs")Save as snowflake.py and run python3 snowflake.py (Python 3.13.5).
The time part makes IDs sortable across machines (to the millisecond); the machine part prevents collisions between generators; the sequence handles many IDs in one millisecond.
Bottlenecks and trade-offs
- Clock going backwards (NTP correction) could create duplicates. The generator refuses to issue IDs (or waits) until the clock passes the last timestamp; monitoring alerts on clock jumps.
- Machine ID reuse. If two processes get the same machine ID, they collide. Leases with expiry, and a delay before reusing a released ID, prevent this.
- Ordering is approximate. IDs from different machines in the same millisecond are not ordered by real time. That is fine for sorting feeds, not for strict sequencing.
- Alternatives. UUIDv4 needs no coordination but is 128 bits and random, which hurts index locality; UUIDv7 is time-ordered and 128 bits; a database sequence is simple but central. Snowflake gives 64-bit sortable IDs with no central service on the hot path.
- Information leak. IDs reveal creation time and roughly how many IDs a machine issues; do not use them where that matters, or scramble them for public display.
By level
Fresher: Explain how the ID is built from time, machine number and a counter, and why that makes IDs unique. A fresher should compute how many IDs fit in one millisecond.
Mid: Do the field arithmetic, handle clock moving backwards, and explain machine ID leasing. Compare with UUIDs.
Senior: Discuss clock monitoring, lease safety, information leakage, UUIDv7 and index locality, and multi-region assignment of machine bits. Expect clear limits on ordering guarantees.
Key points
- 41 bits time, 10 bits machine, 12 bits sequence
- No coordination per ID; only machine IDs are assigned
- 4,096 IDs per millisecond per generator
- About 69 years of time bits from a custom epoch
- Refuse or wait when the clock goes backwards
Common mistakes
- Using a single auto-increment database as the generator at 1M per second
- Ignoring clock moving backwards
- Hard-coding machine IDs that can be duplicated by autoscaling
- Claiming the IDs are strictly ordered across machines
Follow-ups
- How would you assign machine IDs in a Kubernetes cluster?
- When would you choose UUIDv7 instead?
- How do you hide creation time from public IDs?
Tips
- Draw the 64-bit layout
- Compute the limits of each field
- Mention clock skew handling
Evaluation rubric
- Correct bit layout and limits
- Explains uniqueness across machines
- Clock and machine ID failure handling
- Compares with alternatives