Video in progress
How do you generate unique 64-bit IDs that sort by time across many services and many instances, without a central coordinator?
Snowflake style: a timestamp (ms), a worker ID and a per-millisecond sequence counter are packed into one long. There is no central point, and the order is roughly by time. The main risks are the clock going backward, duplicate worker IDs, and running out of bits in the layout.
📖 Answer
The classic layout: 1 sign bit, 41 bits of milliseconds (from a custom epoch, ~69 years), 10 bits of worker (1024 instances), and 12 bits of sequence (4096 IDs per ms).
final class IdGenerator {
private static final long EPOCH = 1_735_689_600_000L; // 2025-01-01 UTC
private final long workerId;
private long lastMs = -1, seq = 0;
IdGenerator(long workerId) {
if (workerId < 0 || workerId > 1023) throw new IllegalArgumentException();
this.workerId = workerId;
}
synchronized long next() {
long now = System.currentTimeMillis();
if (now < lastMs) {
throw new IllegalStateException("Soat orqaga ketdi: " + (lastMs - now) + " ms");
}
if (now == lastMs) {
seq = (seq + 1) & 4095;
if (seq == 0) { // this millisecond is used up — wait for the next one
while ((now = System.currentTimeMillis()) <= lastMs) Thread.onSpinWait();
}
} else {
seq = 0;
}
lastMs = now;
return ((now - EPOCH) << 22) | (workerId << 12) | seq;
}
}
The algorithm is 30 lines. The staff-level question is the decisions around it:
The clock: an NTP correction can move the clock backward. Options: throw an exception (as above), continue from lastMs for a short step backward, or a hybrid logical clock. For a small shift (< 10 ms) I wait; for a larger one I alert and mark the instance as unhealthy.
The worker ID. In Kubernetes pods come and go. Where do you get the ID from: a StatefulSet ordinal, a lease table in the DB, or a Redis key with a TTL. If two pods get the same ID, you get duplicate IDs, the worst bug, because it's silent. An instance that can't renew its lease must stop issuing IDs.
Alternatives:
- UUIDv4 needs no coordination, but it's 128 bits and random: random writes into a B-tree index split pages;
- UUIDv7 (RFC 9562) is a time-stamped UUID, index-friendly, and needs no worker ID. In new systems I often pick this one, if 128 bits isn't a problem;
- allocating blocks with a DB sequence (hi/lo): each instance takes a block of 1000, the order is strict, but you depend on the DB.
One more thing: the ID reveals the time and the worker. A competitor can count your daily orders from IDs that are exposed externally. In public URLs I use a separate random identifier.
Sign up to mark studied questions and save your progress.