Video in progress

How does a Snowflake-style ID generator work, and what are its clock-related risks?

A 64-bit ID holds the time (milliseconds), a worker number and a sequence within that millisecond. It produces roughly time-sorted IDs without central coordination. The main risks are duplicate IDs if the clock goes backward, and worker number collisions.

📖 Answer

The layout (classic variant):

| 1 bit 0 | 41 bit time (ms, from own epoch) | 10 bit worker | 12 bit sequence |

41 bits ≈ 69 years, 10 bits = 1024 workers, 12 bits = 4096 IDs per millisecond per worker.

synchronized long next() {
    long now = clock.millis() - EPOCH;
    if (now < lastTs) {
        throw new IllegalStateException("Soat orqaga ketdi: " + (lastTs - now) + " ms");
    }
    if (now == lastTs) {
        seq = (seq + 1) & 0xFFF;
        if (seq == 0) now = waitNextMillis(lastTs); // all 4096 in this ms are used up
    } else {
        seq = 0;
    }
    lastTs = now;
    return (now << 22) | (workerId << 12) | seq;
}

Risks:

  • The clock going backward. It happens when NTP adjusts, or when a VM is migrated. For a small difference, wait; for a big one, stop with an error and an alert. Carrying on silently means duplicate IDs.
  • Worker ID. In Kubernetes pods come and go, so assigning IDs by hand doesn't work. They're usually obtained with a lease in Zookeeper/etcd, or from a StatefulSet ordinal. Two pods getting the same worker ID is the worst case, because the failure is silent.
  • Information leakage. The creation time and rough volume are visible from the ID. In public URLs this can tell a competitor your daily order count.

Alternatives: UUIDv7 (128 bits, time-sorted, no coordination needed, but twice as big in an index), or a DB sequence with blocks (each instance takes 1000 at a time). If IDs must be in strict order down to the millisecond, Snowflake doesn't guarantee that either, since worker clocks differ.