Sub topic 11
Clock Skew and Backwards Clocks
This chapter assumes you know how a Snowflake-style ID packs a timestamp, a worker ID, and a sequence number into 64 bits. It also assumes you know what a B-tree index is. Snowflake generators depend on the wall clock, so they inherit every clock problem the machine has.
Why the clock is a risk
A Snowflake ID is unique only if no worker issues the same (timestamp, worker, sequence) triple twice. The sequence field separates IDs within one millisecond. If the clock returns to a millisecond the worker has already used, the sequence restarts at zero and the worker can repeat IDs it has already issued.
Two different clock problems matter here:
- Clock skew is the difference between two machines' clocks. Skew does not break uniqueness, because the worker ID separates the machines. It does weaken ordering. An ID from a machine that is 200 ms ahead sorts after an ID created later on a correct machine.
- A backwards clock is a single machine's clock moving to an earlier time. This is the dangerous case, because it can produce duplicates.
How clocks go backwards
- NTP (Network Time Protocol) corrections can step the clock back if the machine has drifted ahead. Most NTP daemons prefer to slew (slow the clock down) for small errors, but they step for large ones.
- A virtual machine that is paused and resumed, or live-migrated, can wake up with a stale or corrected time.
- Leap-second handling can repeat a second on some systems.
- An administrator or a bad configuration sets the time by hand.
Detecting the problem
The Snowflake class from the earlier chapter stores last_ms and compares each new reading against it:
if now < self.last_ms:
raise RuntimeError("clock moved backwards; refusing to generate IDs")Failing loudly is the safe baseline. It turns a silent duplicate into a visible error. The cost is availability: the worker issues no IDs until the clock catches up to last_ms.
Responses
| Strategy | How it works | Trade-off |
|---|---|---|
| Refuse | Raise an error while `now < last_ms`. | Safe, but the caller sees failures. |
| Wait | Sleep until the clock passes `last_ms`. | Fine for small steps. A large step blocks the worker for a long time. |
| Keep the last timestamp | Keep issuing IDs using `last_ms` and keep incrementing the sequence. | Stays available, but when the sequence overflows you must wait or fail. IDs no longer match real time. |
| Use a monotonic clock | Measure elapsed time with a clock that never goes back, added to a start time read once. | Immune to steps, but it can drift from real time and does not survive a restart. |
A bounded wait is a common compromise. The code below waits for small regressions and refuses for large ones:
import time
MAX_WAIT_MS = 5
def wait_for_clock(last_ms, now_ms_fn):
now = now_ms_fn()
if now >= last_ms:
return now
offset = last_ms - now
if offset > MAX_WAIT_MS:
raise RuntimeError(f"clock moved back {offset} ms; refusing")
time.sleep(offset / 1000)
now = now_ms_fn()
if now < last_ms:
raise RuntimeError("clock still behind after waiting")
return now
print(wait_for_clock(1000, lambda: 1000))The restart gap
The in-memory last_ms is lost when the process restarts. If the clock was stepped back while the process was down, a new instance has no record of the timestamps the old one used. Two defenses help:
- Persist the last used timestamp periodically, for example every few seconds, and on startup wait until the clock passes the stored value.
- Make sure a restarted worker does not reuse a worker ID that is still in use elsewhere (see the previous chapter).
Ordering under skew
Do not treat Snowflake order as exact event order across machines. Skew of a few milliseconds is normal even with NTP. If you need a strict causal order, use a logical clock or a database sequence. Time-ordered IDs are good for index locality and for rough sorting, and nothing more.
Exercise
A Snowflake worker issued its last ID at 5000 ms. After an NTP step the clock reads 4996 ms, and the worker's maximum allowed wait is 5 ms. What should it do, and what happens if the step was 30 ms instead?
Show answer
With a 4 ms regression (5000 - 4996), the worker can sleep about 4 ms until the clock passes 5000 ms, then continue safely. With a 30 ms regression the offset exceeds the 5 ms limit, so the worker should refuse to issue IDs and raise an error, and an alert should fire for operators.