Design a Distributed Unique ID Generator
Why auto-increment and UUIDs fall short in a distributed system, and how Snowflake-style IDs combine a timestamp, a machine ID and a sequence into a sortable 64-bit number.
Every order, message, payment and user needs an identifier that is unique. On a single database this is solved by an auto-increment column. Once the data is spread over many databases and the IDs are created by many servers, there is no longer one place that knows the next number.
A distributed unique ID generator produces identifiers that never collide, without the servers having to coordinate on each request. These notes compare the common approaches and explain the Snowflake design in detail.
1. Requirements
- Unique: no two IDs are ever the same, across all servers and data centres.
- Sortable by time: an ID generated later is larger than one generated earlier, at least approximately. This lets data be ordered by ID and keeps database indexes efficient.
- Compact: fits in 64 bits, so that it can be stored as a BIGINT and indexed cheaply.
- Fast and highly available: tens of thousands of IDs per second per server, with no network call and no single point of failure.
- Numeric: some systems prefer integers over strings for storage and comparison.
2. Database auto-increment
A single database with an auto-increment column produces unique, ordered, compact IDs. Its limits appear with scale. Every ID requires a round trip to that database, so it is a bottleneck. If it fails, nothing in the system can create new records, so it is a single point of failure. And once the data is sharded, each shard has its own counter and they produce the same numbers.
A partial fix is to run several databases with different offsets: with two servers, one generates odd numbers and the other even numbers. This works for a fixed, small number of servers, but adding a server later means changing the step size everywhere, and IDs are no longer ordered by time across servers.
Sequential IDs also expose information. An outsider who creates two orders a day apart can subtract the IDs and learn how many orders the business received.
3. UUID
A UUID is a 128-bit value that any machine can generate on its own, with a negligible probability of collision. No coordination is required, which makes it simple and fully available.
It fails two of the requirements. It is 128 bits, twice the target size, and is usually stored as a 36-character string. And the common random variant (version 4) has no order. Random primary keys are harmful to B-tree indexes: each insert lands on a random page, which causes page splits, poor cache locality and slower writes as the table grows. Newer time-ordered variants such as UUID version 7 and ULID fix the ordering problem by placing a timestamp first, but they remain 128 bits.
4. Range allocation (ticket server)
A central service hands out blocks of IDs, for example a thousand at a time, and each application server issues IDs from its block locally. This removes the per-ID round trip and was the approach used for the URL shortener earlier in this series. It gives compact numeric IDs, but they are only roughly ordered in time, and the allocation service must itself be made highly available.
5. Snowflake IDs
The Snowflake approach builds a 64-bit ID by concatenating three fields, so that each generator can create IDs independently and the result is still unique and time-ordered.
- Sign bit, 1 bit: always zero, so that the ID is a positive number in languages with signed integers.
- Timestamp, 41 bits: milliseconds since a custom epoch chosen by the system, such as the start of 2020. Forty-one bits cover about 69 years.
- Machine ID, 10 bits: identifies the generator, allowing 1,024 nodes. It is often split into 5 bits for the data centre and 5 bits for the machine.
- Sequence, 12 bits: a counter that increments for each ID generated within the same millisecond on the same machine, allowing 4,096 IDs per millisecond.
1 bit 41 bits 10 bits 12 bits +------+---------------------------+--------------+----------------+ | 0 | timestamp (ms since | machine ID | sequence | | sign | custom epoch) | (0 - 1023) | (0 - 4095) | +------+---------------------------+--------------+----------------+ Capacity : 4,096 IDs per millisecond per machine = ~4 million per second per machine Lifetime : 2^41 ms = ~69 years from the chosen epoch Ordering : the timestamp is in the high bits, so numeric order = time order
6. Why this layout works
Uniqueness is guaranteed by construction. Two IDs generated on different machines differ in the machine ID. Two IDs generated on the same machine in different milliseconds differ in the timestamp. Two IDs generated on the same machine in the same millisecond differ in the sequence. No communication between machines is needed at generation time.
Because the timestamp occupies the most significant bits, sorting by ID is the same as sorting by creation time, to millisecond precision. Across machines, IDs created in the same millisecond are not strictly ordered, so the property is described as roughly sortable, or k-sorted. That is sufficient for pagination, for range scans by time, and for append-friendly index inserts.
const EPOCH = 1577836800000n; // 2020-01-01T00:00:00Z
class Snowflake {
constructor(machineId) {
this.machineId = BigInt(machineId); // 0..1023, unique per running instance
this.lastTs = -1n;
this.sequence = 0n;
}
nextId() {
let ts = BigInt(Date.now());
if (ts < this.lastTs) {
throw new Error("Clock moved backwards; refusing to generate IDs");
}
if (ts === this.lastTs) {
this.sequence = (this.sequence + 1n) & 4095n; // 12 bits
if (this.sequence === 0n) {
// 4,096 IDs already issued in this millisecond: wait for the next one
while (ts <= this.lastTs) ts = BigInt(Date.now());
}
} else {
this.sequence = 0n;
}
this.lastTs = ts;
return ((ts - EPOCH) << 22n) | (this.machineId << 12n) | this.sequence;
}
}7. Assigning machine IDs
The scheme depends on every running generator having a different machine ID. If two instances share one, they can produce identical IDs. Machine IDs must therefore be assigned centrally, once, at startup: for example by a coordination service such as ZooKeeper or etcd that leases a free ID to each instance, or from static configuration tied to the host. This coordination happens only when a process starts, not on every ID, so it does not affect throughput or availability.
8. Clock problems
The design relies on the system clock, and clocks on different machines drift. Time synchronisation services correct drift, and a correction can move a machine's clock backwards. If the generator kept running with an earlier timestamp, it could reproduce an ID it has already issued.
- Detect it: the generator remembers the last timestamp it used. If the current time is earlier, it does not generate.
- For a small backward jump, wait until the clock catches up to the last timestamp.
- For a large jump, fail fast, take the node out of service and raise an alert.
- Configure time synchronisation to slew the clock gradually instead of stepping it.
- On restart, a node should not issue IDs until its clock has passed the last timestamp it used before stopping.
9. Trade-offs and variations
- The bit allocation can be tuned: more sequence bits for higher throughput per node, more machine bits for more nodes, or second-level timestamps for a longer lifetime.
- IDs reveal their creation time and are guessable in sequence. Where that matters, expose a separate random public identifier.
- Deployment: as a library embedded in each service (no network hop, but machine IDs must be managed for every instance) or as a small dedicated ID service.
- JavaScript numbers lose precision above 2^53, so 64-bit IDs should be sent to browsers as strings.
Approach Unique Time-sortable Size Coordination Main weakness ------------------------------------------------------------------------------------------- DB auto-increment yes yes 64 bit every ID bottleneck, single point of failure UUID v4 yes* no 128 bit none large, random index inserts UUID v7 / ULID yes* yes 128 bit none large Range allocation yes roughly 64 bit per block allocator must be highly available Snowflake yes yes (k-sorted) 64 bit machine ID at boot depends on clocks * probabilistic, with negligible collision chance
Interview summary
- Requirements: unique, time-sortable, 64-bit, fast, no single point of failure.
- Auto-increment: bottleneck and single point of failure; does not work across shards.
- UUID: no coordination, but 128 bits and (v4) unordered.
- Snowflake: 41-bit timestamp, 10-bit machine ID, 12-bit sequence.
- Handle clock drift: never generate with a timestamp earlier than the last one used.
Summary
A distributed ID generator must create unique identifiers without coordinating on each request. A Snowflake-style ID packs a millisecond timestamp, a machine ID and a per-millisecond sequence into 64 bits, which gives uniqueness by construction and ordering by time. Its two operational requirements are unique machine IDs and protection against clocks moving backwards.
Puneet Tiwari
Full Stack Developer
