Practical technical guides / Core IT: distributed systems (time-ordered ID generators and clocks)

Time-Ordered IDs When the Clock Steps Back: Duplicates, Waits and Logical Clocks in Snowflake-Style Generators

A 300 ms clock step made a naive Snowflake-style generator reissue 1,200 IDs in a model run. Compare ignore, refuse, wait and a logical clock, and persist the last timestamp.

By Sandeep Belgavi · Published 2026-11-10

A wall clock that steps back meets a time-ordered ID
Original explanatory diagram; synthetic values where shown.

A 300 ms clock step made a naive Snowflake-style generator reissue 1,200 IDs in a model run. Compare ignore, refuse, wait and a logical clock, and persist the last timestamp.

Two orders with the same ID

Belgavi's Book Store assigns order IDs with a Snowflake-style generator inside each order service instance: a 64-bit number made of milliseconds since an epoch, a worker id and a per-millisecond sequence. The IDs are unique without a central database, and they sort roughly by creation time, which makes them pleasant as primary keys and in logs.

Now imagine one instance's wall clock is wrong by 300 milliseconds and the time daemon corrects it with a step backwards. For the next 300 milliseconds that instance sees timestamps it has already used. If the generator simply reads the clock, it starts the sequence again at zero and reissues IDs it handed out a moment ago. Two orders share an ID; one insert fails with a unique-key violation, or, worse, a downstream system that keys on the ID merges two customers' orders.

This article works through what a time-ordered ID generator should do when the clock steps back, compares four strategies with a model, and sets out the design rules: a monotonic time source where possible, a persisted last timestamp, and an explicit policy for the rare cases that remain.

How the ID is built

The archived Twitter Snowflake implementation from 2010 uses 41 bits of milliseconds since a custom epoch, 5 bits of datacenter id, 5 bits of worker id and 12 bits of sequence. Within one millisecond a worker can issue 4,096 IDs. When the sequence runs out, the generator spins until the clock reaches the next millisecond. When it sees a timestamp smaller than the last one it used, it logs "clock is moving backwards" and throws an exception: it refuses to generate IDs until the clock catches up.

Uniqueness rests on one invariant: a worker never issues the same (timestamp, sequence) pair twice. The worker id separates workers, so a clock problem on one instance cannot collide with another. Ordering rests on a weaker property: IDs from one worker increase as long as its timestamps never go backwards.

Four strategies, one model

The companion model issues requests at a steady rate on a simulated wall clock that steps back by a chosen amount at a chosen time, and applies one of four strategies when the clock reads earlier than the last timestamp used.

  • ignore: use whatever the clock says and reset the sequence when the millisecond changes.
  • refuse: reject requests while the clock is behind, as the 2010 Snowflake code did.
  • wait: hold each request until the clock passes the last timestamp, then continue.
  • logical: use the larger of the clock and the last timestamp, so time never goes backwards, borrowing the next millisecond when a sequence is exhausted.

With 4 requests per millisecond, 12 sequence bits and a step back of 300 milliseconds at time 1,000, over two seconds:

StrategyDuplicatesRefusedRequests delayedWorst delayFurthest ahead of the wall clock
ignore1,200000 ms0 ms
refuse01,19600 ms0 ms
wait001,196299 ms0 ms
logical0000 ms299 ms

Ignoring the step duplicates every ID issued in the replayed 300 milliseconds: 1,200 IDs. The other three strategies all keep IDs unique, and they differ only in who pays. Refusing pushes the problem to callers as errors for 299 milliseconds. Waiting turns it into latency: each request in that window waits up to 299 ms. A logical clock pays nothing visible at the time, but the IDs it issues carry timestamps up to 299 ms in the future relative to the wall clock.

For a small correction, the logical clock is clearly the best choice. With a 5 millisecond step the model's IDs run at most 4 ms ahead, which nothing downstream will notice. RFC 9562, which defines UUID version 7, gives the same advice for its counters: when a new UUID is not greater than the previous one because of clock rollbacks, leap seconds or counter rollover, the application may reuse the previous timestamp and increment the counter.

The other failure: more requests than sequence numbers

A burst can exhaust the sequence even when the clock is perfect. With 2 sequence bits (4 IDs per millisecond) and 6 requests per millisecond, the model shows the two classic responses diverging.

StrategyWhat happens over two seconds of requests
wait (spin to the next millisecond)Every request is served, but the backlog grows: the last ID is issued at 2,999 ms instead of 1,999 ms
logical (borrow the next millisecond)Every request is served immediately, but timestamps run 1,000 ms ahead of the wall clock by the end

Both are correct in the sense that no ID repeats. Both are signs that the bit layout is wrong for the load. RFC 9562 describes the same choice for UUIDv7 counter rollover: freeze the counter and wait for the timestamp to advance, or increment the timestamp ahead of the actual time. A logical clock that drifts further and further ahead is a capacity alarm, not a solution; cap how far ahead it may run, and alert well before the cap.

Where the clock steps come from

Clocks step backwards for ordinary reasons: a virtual machine resumes from a pause and resynchronises, a container starts on a host whose clock was wrong and the time daemon makes a large correction, an operator sets the time by hand, or a leap second is applied by stepping rather than smearing. Time synchronisation daemons usually slew small offsets (run the clock slightly faster or slower until it is right) and step only large ones; chrony, for example, steps the clock only when its makestep directive allows it, typically in the first updates after start.

On Linux, CLOCK_REALTIME can jump in either direction when it is set, while CLOCK_MONOTONIC never goes backwards but has no relation to calendar time. Java's System.currentTimeMillis() follows wall-clock time; System.nanoTime() is monotonic within one process but meaningless across processes.

Design rules that survive real clocks

class Generator:
    def __init__(self, worker_id, seq_bits=12, max_lead_ms=5000, load_last=lambda: -1):
        self.worker_id, self.cap, self.max_lead = worker_id, 1 << seq_bits, max_lead_ms
        self.last, self.seq = load_last(), 0       # persisted across restarts

    def next_id(self, wall_ms):
        ts = max(wall_ms, self.last)               # never go backwards
        if ts == self.last:
            self.seq += 1
            if self.seq == self.cap:               # sequence exhausted: borrow the next millisecond
                ts, self.seq = ts + 1, 0
        else:
            self.seq = 0
        if ts - wall_ms > self.max_lead:
            raise RuntimeError('ID clock is too far ahead of wall time; check the time source and the load')
        self.last = ts
        return (ts << 22) | (self.worker_id << 12) | self.seq   # 10 worker bits, 12 sequence bits
  1. Never let the timestamp go backwards inside a process. Keep the last timestamp and use the larger of it and the clock. This turns small steps into a small, invisible lead.
  2. Persist the last timestamp across restarts. A process that restarts during a backwards step forgets its last timestamp, and the in-memory rule cannot protect it. Write the last timestamp (or a reserved block of future timestamps) to durable storage at startup and periodically, and refuse to start if the clock is earlier than the stored value by more than a threshold.
  3. Cap the lead and alert on it. A lead of a few milliseconds is normal; a lead of minutes means the clock or the load is wrong. Fail loudly at a threshold you choose, as the sketch does.
  4. Make worker ids unique for real. Two instances that share a worker id produce duplicates even with perfect clocks, and no clock rule can detect it. Assign worker ids from a lease in a coordination store, and release them only after the lease expires.
  5. Keep a unique constraint where IDs are stored. It is the last line of defence and turns a silent merge into a visible failure.

What to test

  • A unit test that feeds the generator a clock that steps back by 300 ms and asserts no duplicates and strictly increasing IDs.
  • A test for sequence exhaustion that asserts the lead stays below the cap at your peak rate, and that the generator fails rather than exceeding it.
  • A restart test: issue IDs, step the clock back, restart with the persisted timestamp, and assert the next ID is still larger than every earlier one.

The companion model and the interactive lab let you vary the step, the rate, the sequence bits and the number of workers and watch the four strategies trade duplicates for errors, delay or lead. A worker other than the stepped one never duplicates, which is the worker id doing its job.

When to use something else

If IDs do not need to be time-ordered, random 128-bit identifiers (UUID version 4) remove the clock from the uniqueness argument entirely. If they need ordering but not compactness, UUIDv7 gives a standard layout with millisecond time and well-specified counter guidance. If the database is the only writer, a sequence in the database is simpler than any of this. Time-ordered 64-bit IDs earn their complexity when many writers need short, sortable keys without coordinating on every insert.

Interactive experiment

Time-ordered IDs: a clock step back, sequence bits and four strategies. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/clock_step_id_generator. Views are my own and do not represent any employer, past or present.