Unique ID generation in distributed systems: snowflake
A database hands out IDs from one counter, and one counter cannot serve a fleet. Snowflake, built at Twitter, stops generating an ID and starts composing one — so every machine mints IDs that sort by time without asking anyone's permission.
64 bitsSplit five ways. The whole design is that split (§3)
4,096 / msPer machine, from 12 sequence bits — 4.1M per second
69 yearsBefore the 41-bit timestamp overflows (§3)
Key points
Auto-increment needs one writer. Split the writes and the counter either becomes a bottleneck or stops producing a shared order — and servers can no longer join or leave freely.
Snowflake composes an ID from parts instead of counting up: time, node, sequence. No coordination, no central allocator, no round trip.
Time occupies the highest bits, so plain integer comparison sorts IDs by creation time. That is not a coincidence — it is the reason for the layout.
The design trades coordination for clock discipline. A clock that runs backwards is a correctness bug, not a monitoring nicety.
Outcomes
01Name the requirement each rejected approach breaks: multi-master, UUID, ticket server.
02Decompose a snowflake ID into its five fields and say what each one tells you.
03Derive the three capacities from the bit widths, and re-derive them for a different split.
04Explain what breaks when clocks drift, and what the system must do about it.
01
One counter cannot feed a fleet
A traditional primary key uses AUTO_INCREMENT on one database: each insert takes the next integer. This works perfectly while one server holds all writes. Split the writes across databases and three things break at once — the single counter becomes a bottleneck, the shared ordering disappears because each database numbers alone, and adding or removing a server forces the whole scheme to change.
The interview states six requirements up front, and every candidate below is judged against exactly these:
#
Requirement
1
IDs are unique
2
Numeric only
3
Fits in 64 bits
4
Ordered by date
5
Over 10,000 IDs per second
6
Keeps working as servers join and leave
Interview line
Recite the six requirements before proposing anything. Graders are checking whether you design against constraints or against vibes — and every rejection below is “this one breaks requirement n”, which is only a sentence you can say if you listed them first.
02
Four candidates, three rejections
Multi-master replication staggers AUTO_INCREMENT by server count, so with two servers one mints odd numbers and the other even. It fails three ways: it is painful across data centres, because every mint needs cross-datacentre agreement; IDs do not rise with time across servers, because each numbers alone; and a membership change means renumbering all of them.
UUIDs need no coordination whatsoever, which is genuinely attractive. But they are 128 bits, not sortable, and contain non-numeric characters.
Ticket servers centralise the counter in one allocator. Simple at small scale — Flickr shipped this — but it is a single point of failure, and adding more allocators reintroduces exactly the synchronisation problem you were avoiding.
Approach
How it works
Requirement it breaks
Multi-master
Each of k servers steps its counter by k
(4) across servers; (6) on membership change
UUID, 128-bit
Each server mints randomly, zero coordination
(2) numeric, (3) 64-bit fit, (4) ordering
Ticket server
One central allocator hands out IDs
(6) single point of failure
Snowflake
Each machine composes time + node + sequence
None — it needs clock discipline instead
Notice the shape of the final row. Snowflake does not avoid the cost; it relocates it, from coordination at request time to clock synchronisation as an operational requirement.
03
Divide the 64 bits
Snowflake stops generating an ID and starts composing one. The 64 bits are five fields, and the figure below draws all of them to scale at 10 pixels per bit.
How to read: Read left to right as most significant to least significant. The shift amounts along the bottom are literally the << operators in the code in §6 — a field's shift is the bit position where it starts.
The 41 green bits dominate, and they sit at the top. That is the single design decision everything else follows from.
Field
Bits
Capacity
Why that width
Sign
1
always 0
Reserved. Keeps the value non-negative so signed 64-bit integers work everywhere
Timestamp
41
≈ 69 years
241−1 ms = 2,199,023,255,551 ms. Divide by 1000/60/60/24/365 → 69.7 years
Datacentre ID
5
32
25. Assigned at startup, never changed at runtime
Machine ID
5
32
25. 32 × 32 = 1,024 minting nodes in total
Sequence
12
4,096 / ms
212. 4,096 × 1000 = 4.1M per second per machine. Zero unless a millisecond carries more than one ID
The custom epoch
The 41-bit counter measures milliseconds since an epoch you choose. Twitter used 1288834974657 — 4 November 2010. Using the Unix epoch instead would spend 40 years of the counter's range on time before the system existed, cutting the runway roughly in half for free. Pick the date your service launched.
Try it: 64 bits, one of them the sign bit. Spend the other 63 and watch the three capacities trade against each other. There is no setting that makes all three large — that is the point.
buys years of runway
buys minting machines
whatever is left: 63 − timestamp − node. Buys burst headroom per node
runway before overflow
69 years
minting nodes
1,024
IDs per node
4,096/ms
whole fleet
4.2B/s
theoretical ceiling
Push timestamp to 48 bits and watch nodes or burst capacity collapse. This is the shape of the answer when an interviewer says “now design it for 5,000 machines” — you are not inventing, you are reallocating a fixed budget.
Interview tip — the widths are negotiable
If you are asked to design for a different shape, re-derive rather than recite. Need more than 1,024 nodes? Take bits from the sequence — 10 node bits and 7 sequence bits gives you 1,024 nodes but only 128 IDs per millisecond each. Need a longer horizon? Take a bit from the sequence for the timestamp and double the 69 years. The total is fixed at 64; everything else is a budget you allocate.
04
Mint one ID, live
Datacentre and machine IDs are chosen at startup and then frozen. Only the timestamp and sequence move at request time. When a request arrives the generator reads the wall clock in milliseconds; if that millisecond matches the previous ID it bumps the sequence, and if the clock has advanced it resets the sequence to zero. Then it packs the five fields into one integer.
How to read: Three real requests through the same fields, with dc=3 and mc=9. Each row spells its ID in binary field by field, then in decimal. A white outline marks what changed since the row above.
Request 2 lands in the same millisecond, so only the purple sequence ticks from 0 to 1 — and its decimal ID is exactly one greater. Request 3 lands in a new millisecond, so the timestamp advances and the sequence resets. The ID still rises, because the bits that grew are far more significant than the bits that reset.
Read the clock
Current time in milliseconds, minus the epoch. If it is behind the last timestamp, refuse or wait. Never mint on a stale clock.
Same millisecond?
Increment the sequence. If it reaches 4,096 the 12-bit field is full, so block until the next millisecond.
New millisecond?
Take the new timestamp and reset the sequence to 0.
Pack
Shift and OR: time at bit 22, datacentre at 17, machine at 12, sequence at 0. The shifts are the running totals of the widths below each field.
Return
One 64-bit integer. Evening IDs exceed morning IDs by construction, with no coordination anywhere.
05
Where the model lies
Four weaknesses, each with a price tag.
Weakness 1 — the big one
Clock synchronisation
The design assumes every machine agrees on the time. Clocks drift, and virtual machines drift badly.
NTP plus monitoring is part of the system, not an afterthought.
A machine whose clock moves backwards mints IDs that sort before rows created earlier. Your cursor-based pagination silently skips records.
The only safe behaviour is to stall or reject until the clock catches up.
Weakness 2
Sequence exhaustion
More than 4,096 IDs in one millisecond on one machine fills the 12-bit field.
The generator must block into the next millisecond.
You trade latency for uniqueness, which is the right trade — but it is a latency spike under exactly the burst conditions you care about.
Weakness 3
Node IDs are load-bearing
Two machines booting with the same (dc, machine) pair mint genuinely identical IDs.
Allocation needs a registry and human review, not a config file someone copies.
Better: assign at boot from ZooKeeper or etcd so duplication is structurally impossible.
Weakness 4
The horizon ends
69 years from your chosen epoch, the timestamp overflows.
A new epoch means new IDs sort before old ones — so a migration has to handle it.
Not your problem, but saying it out loud shows you read the bit widths rather than memorised them.
Gotcha — leap seconds and VM pauses
Clocks do not only drift slowly. A leap second can be smeared or stepped, a virtual machine can be paused and resumed, and ntpd can step the clock backwards to correct a large error. Each of those produces a backwards jump with no warning. This is why the generator compares against its own last timestamp on every call — it does not trust the clock to be monotonic.
In the field: Twitter mints tweet IDs this way because timelines and paging cursors sort directly on the ID. Flickr chose ticket servers instead, because photo uploads fit a central allocator at their scale and they preferred a single point of failure to a clock-synchronisation obligation. Same problem, different price accepted. Either way the ID generator is mission-critical, so high availability is a requirement rather than a stretch goal.
Where this goes next: bounding the uncertainty instead of ignoring it
Snowflake's weakness is that it assumes clocks agree and hopes NTP delivers. Two designs take the problem seriously instead. Hybrid logical clocks (HLC) combine a physical timestamp with a logical counter: the timestamp tracks wall time closely enough to be meaningful, while the counter guarantees the value never goes backwards even when the clock does — so you get causality and roughly-real timestamps, with no special hardware. Google's TrueTime goes further: GPS receivers and atomic clocks in every data centre let the API return an interval rather than an instant — “the true time is somewhere in these 7 ms”. Spanner then simply waits out that uncertainty window before committing, which is why it can offer externally consistent global transactions. The lesson generalises past ID generation: you cannot remove clock uncertainty, so either bound it and wait, or design so that being wrong about time is survivable.
A rule this lesson implies for all your code
Snowflake must read the wall clock, because the output has to mean a real date. Almost nothing else should. Timeouts, retry backoff, rate-limiter windows and latency measurements must use a monotonic clock (time.monotonic(), System.nanoTime()) — a clock that only ever moves forward and is unaffected by NTP steps. Measure a duration with the wall clock and an NTP correction mid-measurement can produce a negative elapsed time, an instant timeout, or a sleep that never ends. This is a real and recurring production bug, and it is the practical takeaway from the clock discussion above.
06
Code it: a snowflake in 30 lines
The lines that matter are the clock guard, the sequence overflow wait, and the bit shifts. Everything else is argument plumbing.
Runnable, standard library onlypython
import time
EPOCH = 1288834974657 # 4 Nov 2010 — a custom epoch saves range
SEQ_BITS, M_BITS, DC_BITS = 12, 5, 5
MAX_SEQ = (1 << SEQ_BITS) - 1 # 4095
MAX_NODE = (1 << M_BITS) - 1 # 31
class ClockBackwardError(Exception):
pass
class Snowflake:
def __init__(self, datacenter_id, machine_id):
assert 0 <= datacenter_id <= MAX_NODE and 0 <= machine_id <= MAX_NODE
self.dc, self.mc = datacenter_id, machine_id
self.last_ms, self.seq = -1, 0# -1 sits behind every real clock,# so the first ID takes the fresh-ms path
def _now_ms(self):
return int(time.time() * 1000) - EPOCH
def next_id(self):
ms = self._now_ms()
if ms < self.last_ms:raise ClockBackwardError(ms, self.last_ms)# never mint on stale time
if ms == self.last_ms:
self.seq += 1
if self.seq > MAX_SEQ:
ms = self._wait_next_ms(self.last_ms) # burst: trade latency
self.seq = 0
else:
self.seq = 0 # fresh ms, fresh sequence
self.last_ms = ms
return (ms << 22) | (self.dc << 17) | (self.mc << 12) | self.seq# 22 / 17 / 12 / 0 are the running totals of the widths: 12, 12+5, 12+5+5
def _wait_next_ms(self, last):
ms = self._now_ms()
while ms <= last:
ms = self._now_ms()
return ms
g = Snowflake(3, 9)
ids = [g.next_id() for _ in range(5)]
print(ids)
print('sorted by time:', ids == sorted(ids))
print('all unique:', len(set(ids)) == len(ids))
Interview line
When asked for extra depth, offer three things in this order: clock synchronisation (the real risk), bit-width tuning (shows you understand the budget), and high availability of node-ID assignment (shows you have thought about operations). Candidates who only describe the bit layout have described the easy half.
Q&A
Check yourself
Q1You are told to support 5,000 minting nodes instead of 1,024, keeping 64 bits and the 69-year horizon. What do you change, and what does it cost?
Widen the ID to 72 bits
Take 3 bits from the sequence: 13 node bits (8,192 nodes), 9 sequence bits (512 IDs/ms per node)
Shorten the epoch window to free up timestamp bits
✓ Take 3 bits from the sequence. 64 is fixed and the 41 timestamp bits are fixed by the horizon requirement, so the only budget available is the 22 bits below them. Moving 3 from sequence to node gives 213 = 8,192 nodes and drops per-node throughput to 512 per millisecond — still 512,000 per second per node, far above the 10,000/s requirement. State the new per-node ceiling out loud; that is the part being tested.
Q2Your snowflake service runs on autoscaled containers that come and go every few minutes. What is the first thing that breaks, and how do you fix it?
Nothing — snowflake is designed for nodes joining and leaving
Machine-ID assignment: two containers can boot with the same ID and mint identical IDs
The sequence counter resets on every container start
✓ Machine-ID assignment. Snowflake tolerates nodes joining and leaving only if each one holds a distinct node ID, and a static config file cannot guarantee that under autoscaling. The standard fix is to lease the ID at boot from ZooKeeper, etcd or a database row with a unique constraint, and release it on shutdown. There are only 1,024 IDs, so you also need to reclaim leases from crashed nodes — which is why some teams widen the node field or shorten the lease TTL.
Q3A colleague suggests using UUIDv7 (time-ordered UUID) instead of snowflake. Give the strongest argument for each side.
Snowflake always wins because it is 64-bit
UUIDv7: no node-ID coordination and no clock-skew correctness bug. Snowflake: half the storage, and it fits a BIGINT primary key
They are equivalent
✓ UUIDv7 removes coordination; snowflake halves the storage. UUIDv7 puts a timestamp in the high bits and random data below, so it sorts roughly by time with no node registry at all — the entire weakness-3 problem disappears, and clock skew degrades ordering rather than breaking uniqueness. The price is 128 bits: double the index size on every primary key and every foreign key referencing it, which at billions of rows is real money. Pick snowflake when index size matters and you can run a registry; pick UUIDv7 when you cannot. Interviewers increasingly ask this because UUIDv7 was standardised after most system-design books were written.
Q4Your API returns snowflake IDs to clients. A security reviewer objects. What is their objection, and is it valid?
No valid objection — the IDs are opaque integers
They leak creation time and node identity, and consecutive IDs are guessable — enabling enumeration and business-intelligence inference
64-bit integers overflow in JavaScript
✓ They leak time and are enumerable — and the JavaScript point is also real. Anyone can decode a snowflake back into a millisecond timestamp and a node ID, so a competitor can measure your signup rate by minting two accounts an hour apart and subtracting. Sequential IDs also invite enumeration if authorisation is weak. Mitigations: never rely on unguessable IDs for access control, and expose an opaque external identifier (a hashid or a separate random UUID) while keeping the snowflake internal. Separately: JSON numbers are IEEE doubles, so a 64-bit ID loses precision in JavaScript — serialise IDs as strings. This bites real APIs constantly.
Q5Monitoring shows one generator raising ClockBackwardError for 400 ms every few hours. A teammate proposes catching the exception and minting with last_ms instead. What happens?
Fine — the timestamp is only approximate anyway
It works until the sequence for that millisecond exhausts, then you mint duplicates
It breaks time ordering but uniqueness is preserved
✓ It works until the sequence exhausts, then you mint duplicates. Reusing last_ms keeps incrementing the sequence within one millisecond's field. At high throughput 4,096 slots are consumed quickly, and after that the sequence wraps and starts re-emitting bit patterns already handed out — genuine collisions on a supposedly unique primary key. The correct behaviours are to block until the clock catches up (if the skew is small) or to take the node out of rotation and alert (if it is large). The 400 ms figure also deserves investigation on its own: that is usually NTP stepping rather than drifting, which means the host's time source is misconfigured.
In practiceWhat production adds, and the questions that come next optional
This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.
Clocks and ordering
Total order broadcast and its equivalence to consensus
Consensus and leader election
Raft in outline: terms, leader election, log replication, commit index, and safety restriction on voting
Terms used
Snowflake
A 64-bit ID composed of timestamp, node identity and a per-millisecond sequence. From Twitter, now a generic pattern.
Custom epoch
The reference date the timestamp counts from. Choosing your launch date rather than 1970 buys decades of range.
Monotonic
Never decreasing. Wall clocks are not monotonic, which is why the generator tracks its own last timestamp.
Clock skew
Disagreement between machines' clocks. Here it is a correctness problem, not a performance one.
NTP
Network Time Protocol. Keeps machine clocks aligned — and can step a clock backwards while doing it.
Ticket server
A central allocator handing out sequential IDs. Simple, and a single point of failure.
UUIDv7
A 128-bit UUID with a leading timestamp, so it sorts by time without any node registry.
Sequence exhaustion
Running out of per-millisecond slots, forcing the generator to block into the next millisecond.
What breaks next. You can now mint a unique, sortable 64-bit number anywhere in the fleet without coordination. Day 9 puts that to work: a URL shortener needs a short unique code, and the cleanest way to get one is to take an ID like this and change its base.
Source: System Design Interview, Ch. 7 — Design a unique ID generator in distributed systems (pp. 110–118). Bit diagrams regenerated on-palette with the arithmetic computed rather than transcribed. UUIDv7, node-ID leasing and the ID-leakage discussion are added here as common modern follow-ups.