7 min readRishi

Designing Snowflake-Style IDs: Ordering, Workers, and Clock Rollback

Designing Snowflake-Style IDs: Ordering, Workers, and Clock Rollback

A random UUID is easy and it scatters across a B-tree. An auto-increment integer is ordered and it requires a single writer. A Snowflake-style id is the compromise Twitter published: a 64-bit value a machine can mint locally, roughly sorted by time, unique as long as you obey two rules. Break either rule and you mint duplicates that look valid until a unique index fires in production. A broader comparison with ULID and UUIDv7 is in distributed ID generation.

The 64 bits

One bit is left at zero so the value stays a positive signed integer. The rest, in the original layout:

BitsFieldWhat it buys
41Milliseconds since a custom epochAbout 69 years of range, and time order
10Worker id1024 machines issuing at once
12Sequence4096 ids per millisecond per worker

Some deployments split the 10 bits into a datacenter and a worker. The math is the same: those 10 bits must be unique among generators that can run at the same time. The sequence resets when the millisecond changes. If a worker needs a 4097th id in the same millisecond, it waits until the clock ticks. It does not overflow into the next worker's numbers, and it does not wrap to zero inside the same millisecond.

You can hit the per-worker ceiling on a hot process that mints in a tight loop. Wait for the next millisecond. Do not steal a future timestamp.

 63          62........22  21........12  11...........0
+---+---------------------+-------------+---------------+
| 0 |  timestamp (41 bit) | worker (10) | sequence (12) |
+---+---------------------+-------------+---------------+

Packing is a shift and OR. The timestamp you shift in is milliseconds since your epoch, not Unix milliseconds. Using Unix time wastes range on the decades before the service existed. Pick an epoch slightly before you start minting and write it down. Changing the epoch later reinterprets every stored id.

static long Pack(long timestampMs, int workerId, int sequence) =>
    (timestampMs << 22) | ((long)workerId << 12) | (uint)sequence;

Uniqueness is local. Two workers never share a worker id, and one worker never reuses a sequence inside a millisecond. No database round trip on the hot path.

The clock is part of the id

The timestamp is not decoration. If the clock steps backwards, the generator will hand out a timestamp it has already used, and the sequence may collide with an id that already left the process.

NTP stepping a VM backwards is a real way to do this. So is a hypervisor pause that looks like a jump when the guest resumes, followed by a correction.

The safe behavior is to refuse, or to wait until wall time catches the last timestamp you issued. Issuing into the past is a collision.

long NextId()
{
    var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - EpochMs;
    if (now < _lastTimestamp)
    {
        var behind = _lastTimestamp - now;
        if (behind > 5_000)
            throw new InvalidOperationException(
                $"Clock moved backwards {behind} ms; refusing to mint.");
        while (now < _lastTimestamp)
            now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - EpochMs;
    }

    if (now == _lastTimestamp)
    {
        _sequence = (_sequence + 1) & 0xFFF;
        if (_sequence == 0)          // overflow: wait for the next millisecond
            while (now <= _lastTimestamp)
                now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - EpochMs;
    }
    else _sequence = 0;

    _lastTimestamp = now;
    return Pack(now, _workerId, _sequence);
}

Small regressions wait. Large regressions throw and page. What you must not do is clamp now up to _lastTimestamp and keep issuing — that reuses a (timestamp, sequence) pair or invents a future timestamp that collides when the clock catches up. Serialize NextId per worker; two threads sharing _sequence will duplicate. Stay on UTC wall time and treat backward steps as a first-class branch.

Worker ids are a lease, not a random nibble

A random 10-bit number will collide. 1024 possibilities sounds large until you have rolling deploys and two replicas that both drew 417.

Lease the id: a row with a TTL that the process renews, or the ordinal of a StatefulSet whose size stays under 1024. Kubernetes StatefulSet pod foo-3 maps to worker 3. That works until someone scales the set to 1025, or until a Deployment (no stable ordinal) copies the same code.

When the process dies, the lease expires and the id can be reused, but only after any id it minted is already in the past. Reusing a worker id in the same millisecond is the collision. Reusing worker 7 a minute later is fine: the timestamp bits have moved on. Do not persist "last sequence" to disk as a substitute for a unique worker id. A new process with the same worker id is safe once wall time has moved on. A new process with a stolen worker id, while the old process is still alive, is not.

What the id is not

It is roughly ordered, not totally ordered. Two ids from different workers in the same millisecond compare by worker id, not by which request arrived first. Do not use id_a < id_b to decide which payment happened first across two replicas. Use a transaction or a ledger sequence.

It does not fit in a JavaScript number. IEEE-754 doubles are safe integers only up to 2^53 − 1 (Number.MAX_SAFE_INTEGER). A 64-bit Snowflake is larger than that once the timestamp has used enough bits, which it will. JSON APIs send it as a string. Clients that parse it into a number will silently round it, and the next GET will 404 on an id that never existed. C# long, Java long, Go int64, and Python int can hold it. The boundary is the JSON, the spreadsheet export, and the TypeScript type that says number.

It encodes the creation time to anyone who knows the epoch. That is fine for an order id. It is the wrong primitive for a secret, a password-reset token, or an invitation link.

It is also not an idempotency key. A retry that mints a new id is a second write. The key has to come from the client and stay stable across the retry, which is the design in idempotency keys for write APIs.

When not to use this

Stay with a database sequence if a single primary takes all writes. Stay with UUIDv4 (or v7, if you want time-order without minting infrastructure) if you cannot run a worker-id allocator you trust, or if you refuse to stringify ids in JSON. Do not use Snowflake ids as unguessable file names. Do not shrink the timestamp field without writing down the new overflow date — 31 bits is about 24 days. Do not mint in two regions with overlapping worker ids.

  • Epoch is a named constant, in the past, never changed after the first id is stored.
  • Worker id is leased or ordinal, unique among live processes, reused only after a delay.
  • Sequence increments under a lock, waits on overflow, never wraps inside a millisecond.
  • Clock rollback waits a small delta and refuses a large one. It never issues a timestamp older than _lastTimestamp.
  • JSON and any public API emit the id as a string. Database columns are bigint.
  • Ids are treated as public. Secrets use a random token.
  • Writes that can retry use a client idempotency key, not "the id we just minted."

The scheme is small. The failures are all in the two uniqueness rules. Obey them, or pick an id that does not depend on the clock.

Keep reading

7 min read

FOR UPDATE: No Row, No Lock

SELECT … FOR UPDATE locks tuples that exist. An empty scan is not a lock on the key. Two sessions both insert; a unique violation is the lucky case.

8 min read

SKIP LOCKED: Due Jobs, Empty Batch

SKIP LOCKED does not mean the next free job. It skips rows that currently have a conflicting lock. A forgotten transaction can make a full queue claim nothing until that session ends.

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.