Sub topic 11
Clock Skew and Backwards Clocks
This chapter covers what happens to time-based ID generators when the system clock misbehaves. It assumes you have read the Snowflake chapter and know the layout of timestamp, worker ID, and sequence. You should be comfortable with bit shifting and with the idea that machines in a cluster do not share a clock.
Why time-based IDs depend on the clock
A Snowflake-style generator guarantees uniqueness through one rule: for a given worker, no two IDs share the same (timestamp, sequence) pair. The sequence counter separates IDs created in the same millisecond. The timestamp separates IDs created in different milliseconds.
This only works if the timestamp never repeats an earlier value after the sequence has reset. If the clock returns to a time the worker has already used, the sequence restarts at 0 and the generator can produce an ID it has already issued.
Two different clock problems affect IDs:
- Clock skew is the difference between the clocks of two machines. Skew is normal. Every machine drifts, and synchronization only keeps the drift small.
- A backwards clock is a single machine's clock moving to an earlier value. This is the dangerous case for uniqueness.
The two have different effects, so treat them separately.
Clock skew between workers
Suppose worker A's clock is 40 ms ahead of worker B's. Both generate IDs at the same real moment. A's IDs carry a larger timestamp than B's, so sorting by ID puts B's IDs first, even though they were created at the same time.
Skew does not cause duplicates. The worker ID bits differ between A and B, so their IDs never collide, whatever their timestamps say. What skew damages is ordering across workers:
- IDs are only roughly time-ordered. The error is bounded by the skew between machines.
- "Sort by ID" is not the same as "sort by true event time". If your application needs the true order of events from different machines, an ID is not enough.
- Two events, one causing the other, can receive IDs in the wrong order if they run on different machines with skewed clocks.
Typical skew on a well-run cluster using NTP (Network Time Protocol) is a few milliseconds to tens of milliseconds. On poorly managed hosts it can reach seconds.
Clocks moving backwards
A single machine's clock can move backwards for several reasons:
- NTP step corrections. If a clock is far from the reference, the NTP daemon may jump it instead of slewing (gradually adjusting) it.
- Leap seconds. Some systems repeat a second, or smear it across hours, when a leap second is inserted.
- Virtual machine events. Pausing, migrating, or restoring a VM from a snapshot can resume the guest at an earlier time.
- Manual changes. An operator, or a misconfigured script, sets the date.
- Restarts with a bad hardware clock. A machine boots with an old time before NTP has corrected it.
Here is a concrete failure. A worker issued ID (t=1000, seq=5) and then the clock steps back to t=998. The worker has no memory that it already used 998 with sequences 0 to 20. It starts issuing (998, 0), (998, 1), and so on. Those IDs already exist, so the result is duplicates, and a unique-key constraint rejects the inserts or, without such a constraint, data is silently overwritten.
Detecting a backwards clock
The generator from the Snowflake chapter keeps last_ms, the timestamp of the last ID it issued. On every call it compares the current time with last_ms:
now > last_ms: new millisecond, reset the sequence.now == last_ms: same millisecond, increment the sequence.now < last_ms: the clock went backwards.
The code in that chapter handles the third case by raising an error. That is the safest default, because it never issues a duplicate. It has a cost: the worker is unavailable until the clock catches up to last_ms or an operator intervenes.
Detection only works while the process is running. last_ms lives in memory. If the process restarts and the clock is now behind the previous run, the generator has no record of what it issued before. We return to this below.
Strategies for handling a backwards clock
There are four common responses. They trade availability against safety and complexity.
| Strategy | Behavior | Strengths | Weaknesses |
|---|---|---|---|
| Refuse | Raise an error until the clock catches up | Never duplicates, simple | Worker unavailable during the gap |
| Wait | Sleep until the clock passes `last_ms`, then continue | Transparent to callers for small gaps | Blocks callers; unacceptable for large gaps |
| Use logical time | Keep using `last_ms` and advance the sequence, borrowing from the future | Always available | Timestamps drift from real time; sequence may run out |
| Persist state | Save `last_ms` durably and check it on startup | Survives restarts | Extra I/O and failure modes |
A common hybrid is to wait when the gap is small, for example up to 5 ms, and refuse when it is larger. Small steps are usually NTP adjustments that fix themselves quickly. Large steps suggest something is wrong, and failing loudly gets an operator involved.
A generator that waits for small gaps
This version extends the generator from the Snowflake chapter. It tolerates small backwards steps by waiting, and raises an error for large ones.
import threading
import time
class ClockMovedBackwards(RuntimeError):
pass
class Snowflake:
WORKER_BITS = 10
SEQUENCE_BITS = 12
MAX_SEQUENCE = (1 << SEQUENCE_BITS) - 1
def __init__(self, worker_id, epoch_ms=1_700_000_000_000, max_wait_ms=5):
if not 0 <= worker_id < (1 << self.WORKER_BITS):
raise ValueError("worker_id must fit in 10 bits")
self.worker_id = worker_id
self.epoch_ms = epoch_ms
self.max_wait_ms = max_wait_ms
self.last_ms = -1
self.sequence = 0
self.lock = threading.Lock()
@staticmethod
def _now_ms():
return time.time_ns() // 1_000_000
def _wait_until_after(self, ms):
now = self._now_ms()
while now <= ms:
time.sleep(0.0005)
now = self._now_ms()
return now
def next_id(self):
with self.lock:
now = self._now_ms()
if now < self.last_ms:
gap = self.last_ms - now
if gap > self.max_wait_ms:
raise ClockMovedBackwards(
f"clock is {gap} ms behind; refusing to generate IDs"
)
# Small step: wait until the clock passes the last used timestamp.
now = self._wait_until_after(self.last_ms)
self.sequence = 0
elif now == self.last_ms:
self.sequence = (self.sequence + 1) & self.MAX_SEQUENCE
if self.sequence == 0:
# Sequence exhausted: wait for the next millisecond.
now = self._wait_until_after(self.last_ms)
else:
self.sequence = 0
self.last_ms = now
return (
((now - self.epoch_ms) << (self.WORKER_BITS + self.SEQUENCE_BITS))
| (self.worker_id << self.SEQUENCE_BITS)
| self.sequence
)
gen = Snowflake(worker_id=7)
print(gen.next_id())
print(gen.next_id())
# Simulate a 3 ms backwards step by moving last_ms into the future.
gen.last_ms = gen._now_ms() + 3
print(gen.next_id()) # waits a few ms, then issues an ID
# Simulate a 500 ms step: this raises ClockMovedBackwards.
gen.last_ms = gen._now_ms() + 500
try:
gen.next_id()
except ClockMovedBackwards as exc:
print("refused:", exc)Two details matter. First, after waiting, the code resets the sequence to 0, because it is now in a new millisecond. Second, the wait happens while holding the lock, so other threads block too. That is deliberate: letting them proceed would risk issuing IDs from the old, already-used millisecond.
Backwards clocks across restarts
The in-memory check misses this sequence of events:
- The worker issues IDs up to
t=5000. - The process crashes and the host reboots.
- The host boots with a clock reading
t=4990, before NTP corrects it. - The worker starts with
last_ms = -1and issues(4990, 0).
Those IDs can duplicate ones from step 1. Mitigations:
- Persist a high-water mark. Periodically write a timestamp slightly ahead of the current time (for example, now plus a few seconds) to durable storage. On startup, refuse to issue IDs until the clock passes the stored value. This avoids a write on every ID.
- Delay startup. Wait a few seconds after boot so time synchronization can settle before accepting traffic.
- Check sync status. Read the time daemon's status and refuse to start while the clock is unsynchronized.
- Change the worker ID on restart. If each process incarnation gets a fresh worker ID, an old
(timestamp, sequence)pair cannot collide. This relies on the worker ID assignment scheme from the previous chapter, and it uses up worker IDs quickly if restarts are frequent.
Choosing a clock source
Python's time.time_ns() reads the wall clock, which NTP can adjust. The monotonic clock, time.monotonic_ns(), never goes backwards, but it has no fixed relationship to calendar time and usually resets at boot. It cannot supply the timestamp bits of an ID directly.
A useful pattern combines the two. Read the wall clock once at startup, record the monotonic reading at the same moment, then compute timestamps as that wall-clock base plus elapsed monotonic time. This protects a running process from NTP steps. The cost is that the generator slowly drifts from true time, because it ignores later NTP corrections, and the startup reading still has to be correct. Many production systems accept the simpler design (wall clock plus detection) and rely on operations to keep NTP healthy.
Other clock hazards
- Leap-second smearing differences. If some hosts smear leap seconds and others step, their clocks differ by up to a second for hours. This is skew, not a backwards step, but it widens the ordering error.
- Timestamp overflow. 41 bits of milliseconds last about 69 years from the custom epoch. A badly chosen epoch, or one set in the future, causes negative or overflowing values. Validate that
now >= epoch_msat startup. - Clocks far in the future. If a misconfigured host runs a year ahead and issues IDs, then is corrected, it will see its clock as moving backwards by a year. The refuse strategy catches this. It also means IDs with absurd timestamps already exist in your data. Some systems reject any ID whose timestamp is far ahead of the receiver's clock.
Summary of rules
- Skew harms ordering. A backwards step harms uniqueness.
- Always compare the current time with the last issued timestamp, and never issue an ID for an earlier timestamp.
- Prefer failing loudly to guessing. A short outage is cheaper than corrupted data.
- Survive restarts by persisting a high-water mark or by delaying startup until the clock is trustworthy.
- Alert on clock-backwards errors. They indicate a time synchronization problem that affects more than your ID generator.
Exercise
A worker issued its last Snowflake ID at timestamp 20000 ms with sequence 3. The host's clock then steps back to 19996 ms. The generator has maxwaitms=5. What does the generator from this chapter do, and what would happen if it instead set the timestamp to 19996 and reset the sequence to 0?
Show answer
The gap is 4 ms, which is within maxwaitms, so the generator waits until the clock passes 20000 ms, resets the sequence to 0, and issues an ID in the new millisecond. No ID repeats. If it had used 19996 with sequence 0 directly, it could reproduce IDs already issued for 19996 to 20000 with the same worker ID, producing duplicates.
Exercise
Worker A's clock runs 30 ms ahead of worker B's, and both are healthy and never step backwards. Can they generate the same ID? What does the skew affect instead?
Show answer
No. Their worker ID bits differ, so IDs never collide. The skew only affects ordering: IDs from A can sort after IDs from B that were created later in real time, by up to about 30 ms.
Exercise
A process crashes and the host reboots with a clock 10 seconds behind the time of the last issued ID. The generator keeps last_ms only in memory. Describe the risk and give two mitigations.
Show answer
After restart, last_ms is lost, so the generator can issue IDs for timestamps it already used, producing duplicates. Mitigations: persist a high-water timestamp and refuse to issue IDs until the clock passes it; delay startup until the clock is synchronized; or assign a new worker ID to each process incarnation.