Sub topic 14
Time Sources and Clock Skew Across Nodes
This chapter assumes you know the fixed window, sliding window, and token bucket algorithms from earlier chapters. It also assumes you know how a shared Redis store holds limiter state and why updates must be atomic. Every algorithm so far depends on a notion of "now". This chapter covers where that value comes from and what goes wrong when it is wrong.
Why time matters to a limiter
A rate limiter turns elapsed time into a decision. The token bucket computes elapsed * refill_rate. The fixed window computes now // window to pick a counter. The sliding window counter weights the previous window by now % window. If now is wrong, the decision is wrong.
On one machine this is easy. In a distributed limiter, several application servers each have their own clock, and those clocks disagree. The disagreement is called clock skew: the difference between two clocks that should show the same time.
Wall clocks and monotonic clocks
Most operating systems offer two kinds of clock.
| Clock | Python call | What it measures | Can it jump? |
|---|---|---|---|
| Wall clock | `time.time()` | Seconds since the Unix epoch (1970-01-01 UTC) | Yes. NTP corrections, manual changes, and leap second handling can move it forwards or backwards. |
| Monotonic clock | `time.monotonic()` | Seconds since an arbitrary starting point, such as boot | No. It never goes backwards. |
The rule is to use the clock that fits the question you are asking.
- Measuring elapsed time inside one process (token bucket refill): use the monotonic clock. A wall clock that steps backwards would produce a negative
elapsed, and a step forwards would grant a large unearned refill. - Assigning requests to a calendar-aligned window (fixed window, sliding window counter): you need a value that means the same thing on every node, so you need a wall clock or a shared source. A monotonic value is meaningless on another machine, because each machine's starting point differs.
This is why the in-process TokenBucket from earlier uses time.monotonic(), while the window limiters take time.time() by default.
import time
# Monotonic: only differences are meaningful, and only within one process.
start = time.monotonic()
time.sleep(0.1)
print(f"elapsed: {time.monotonic() - start:.2f}s")
# Wall clock: comparable across machines, but only as well as they are synchronized.
print(f"wall clock seconds since epoch: {time.time():.0f}")How skew breaks each algorithm
Suppose two application servers, A and B, share one Redis counter per user, and B's clock runs 3 seconds ahead of A's. Each server computes the window index from its own clock.
- Fixed window. With a 60-second window, B moves to the next window 3 seconds before A. If the window index is part of the Redis key, requests from B land in a fresh counter while A still uses the old one. During those 3 seconds the user can spend the limit twice. The same effect as the boundary burst appears, but now at an extra boundary caused by skew.
- Sliding window counter. The fraction
now % windowdiffers per node, so each node weights the previous window differently. The estimate becomes inconsistent, but the error is bounded by the skew divided by the window size. - Token bucket with client-supplied timestamps. If each server writes its own
nowinto the shared bucket, a server with a slow clock writes an older timestamp than a server with a fast clock. The next caller then sees a large or negativeelapsed. A negative value reduces tokens, and a huge one refills them to capacity.
The size of the error matters. Skew of 50 ms against a 60-second window is negligible. Skew of 3 seconds against a 1-second window makes the limiter meaningless. Short windows and high refill rates are the most sensitive.
Fix 1: use the Redis server clock
The simplest remedy is to make every decision with one clock. The Lua token bucket in the earlier chapter does this by calling redis.call('TIME') inside the script.
local t = redis.call('TIME')
local now_ms = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)TIME returns two values: seconds and microseconds within the current second. Every application server that runs the script sees the same clock, so skew between application servers no longer matters.
Because the script runs atomically, the time read, the refill calculation, and the write all happen as one step. No other client can interleave between them.
A note on versions. Redis scripts that call TIME and then write were historically restricted because script replication sent the script itself to replicas and a non-deterministic call could produce different results. Modern Redis (5.0 and later by default, with effects replication) replicates the script's write commands instead, so this pattern works. If you run an old version or a managed service with restrictions, check its documentation.
Fix 2: tolerate skew by design
Sometimes you cannot use a central clock, for example when limiters run locally on each node for speed. Then you reduce your exposure to skew.
- Synchronize clocks. Run NTP or a similar service (chrony, or your cloud provider's time sync) on every node. Typical skew on a well-run fleet is a few milliseconds. Monitor the offset and alert when it grows.
- Use windows much longer than the expected skew. A 60-second window tolerates seconds of skew far better than a 1-second window.
- Clamp elapsed time. When computing a refill, treat negative elapsed time as zero and cap the refill at capacity. The Lua script does both with
math.max(0, ...)andmath.min(capacity, ...). - Prefer relative time to absolute time. Token bucket state stores a timestamp, but the decision only needs the difference. Algorithms that depend on absolute window boundaries are more sensitive to skew than those that depend on durations.
A clamped version of the refill step in Python:
def refill(tokens, capacity, rate, last_ts, now):
"""Return the new token count. Negative elapsed time (clock went backwards) adds nothing."""
elapsed = max(0.0, now - last_ts)
return min(capacity, tokens + elapsed * rate)
# Clock went backwards by 2 seconds: no tokens are added or removed.
print(refill(tokens=3.0, capacity=10, rate=1.0, last_ts=100.0, now=98.0)) # 3.0
# Normal case: 4 seconds pass at 1 token per second.
print(refill(tokens=3.0, capacity=10, rate=1.0, last_ts=100.0, now=104.0)) # 7.0
# Long gap: refill is capped at capacity.
print(refill(tokens=3.0, capacity=10, rate=1.0, last_ts=100.0, now=500.0)) # 10Clamping has a cost. If a fast clock writes a timestamp far in the future, later callers with correct clocks see negative elapsed time and get no refill until real time catches up. A one-time forward jump of 10 minutes in a node's clock can therefore freeze a bucket for 10 minutes. Using a single time source avoids this entirely.
Other time hazards
- Clock steps. NTP normally adjusts a clock gradually (slewing), but a large offset can cause an immediate step. A step backwards makes a wall clock repeat time. Use monotonic time for durations within a process.
- Virtual machine pauses and container migration. A paused VM resumes with a stale clock until it resynchronizes. Requests handled in that interval are timestamped incorrectly.
- Leap seconds. Some systems repeat or smear a second. A smear spreads the adjustment over hours, which makes each second slightly longer. Mixed fleets, where some nodes smear and some do not, can disagree by up to half a second.
- Key expiry. Redis
EXPIREuses the Redis server clock, so keys expire consistently with theTIMEcall. If you set expiry from a client-computed timestamp (EXPIREAT), skew shifts the expiry. Prefer relativeEXPIREorPEXPIRE. - Retry-After values. If you return an absolute timestamp to the client, skew between your servers makes it inconsistent. A relative number of seconds is safer, as discussed in the response semantics chapter.
Choosing an approach
| Situation | Recommended time source |
|---|---|
| Single-process limiter | `time.monotonic()` for token bucket, `time.time()` only for aligned windows |
| Shared Redis state, atomic script | Redis `TIME` inside the script |
| Shared Redis state, client-side logic | Synchronized NTP clocks, long windows, clamped elapsed time |
| Local per-node limiters with periodic sync | Monotonic clocks locally, accept approximate global behavior |
Testing time-dependent code
The earlier limiters accept a now argument for a reason: it lets you inject time. You can simulate skew directly.
class FixedWindowLimiter:
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.counters = {}
def allow(self, key, now):
index = int(now // self.window)
window_index, count = self.counters.get((key, index), (index, 0))
if count >= self.limit:
return False
self.counters[(key, index)] = (index, count + 1)
return True
shared = FixedWindowLimiter(limit=2, window=60)
# Real time is 59.0 on server A. Server B's clock is 3 seconds ahead, so it reads 62.0.
results = [
shared.allow("alice", now=59.0), # A, window 0
shared.allow("alice", now=59.1), # A, window 0
shared.allow("alice", now=59.2), # A, rejected
shared.allow("alice", now=59.2 + 3.0), # B, window 1: allowed despite the limit
]
print(results) # [True, True, False, True]The fourth call is allowed only because B's skewed clock put it in a different window. The test makes the failure visible and gives you a regression check for a fix.
Exercise
Server A and server B share a Redis fixed window counter whose key includes the window index. The window is 10 seconds and B's clock is 2 seconds ahead of A's. Describe the problem, and give two ways to fix it.
Show answer
Each server computes the window index from its own clock, so for the last 2 seconds of every window B writes to the next window's key while A still writes to the current one. A user sending requests through both servers can use up the limit in each key, getting up to double the allowed rate around the boundary. Fixes: compute the window index with Redis TIME inside a Lua script so all servers use one clock, or synchronize clocks with NTP and use a longer window so the skew is a small fraction of it.
Exercise
Why should an in-process token bucket use time.monotonic() rather than time.time()? Why can the same choice not work for a window index shared across servers?
Show answer
A wall clock can step backwards or forwards when it is corrected, which gives negative or inflated elapsed time and wrong refills. The monotonic clock never goes backwards, so differences are reliable within one process. A monotonic value has an arbitrary starting point that differs on each machine, so servers cannot agree on which window a moment belongs to. Shared window indexes need a wall clock or a central time source such as Redis TIME.