Video in progress
What errors does clock skew between services cause, and how do you make a design tolerant of it?
The clocks of different servers differ by milliseconds to seconds. Ordering events by timestamp, "last write wins", JWT exp/nbf checks and lock expiry all go wrong because of it. For ordering, use versions; for expiry, use a single source clock and a small tolerance.
📖 Answer
Even with NTP, clocks are not identical: usually milliseconds, seconds after a VM migration or when NTP breaks, sometimes minutes.
Where it shows up:
- Ordering.
order-servicewroteCancelledat 10:00:00.120, andpayment-service, whose clock is 50 ms behind, wrotePaidat 10:00:00.090, though it actually happened later. The consumer sorts by timestamp and leaves the order "canceled". A timestamp is not an ordering across different sources. - Last-write-wins. Two regions or two services update the same record and "the newest timestamp wins": the server whose clock is ahead always wins, and the real last write is lost.
- JWT. The auth server's clock is 2 minutes ahead: the token's
nbfis a time that hasn't arrived yet for the resource server, beyond Spring's default 60-second tolerance, so the token is rejected. - Locks and TTLs. A lock is written as "until 10:05", and another node's clock is ahead, so it considers the lock expired before its time.
- Monitoring: in a trace, a child span looks like it started before its parent.
A tolerant design:
- For ordering, use versions, not the clock: the aggregate version, the partition offset, a DB sequence. These are reliable within a single source.
- Let one source compute expiry times. The lock expiry is computed by the system that grants the lock (the DB's
now(), a Redis TTL), not the client's clock. The saga deadline is stored in the orchestrator's DB. - Tolerance in JWT. Spring Security's
JwtTimestampValidatorallows 60 seconds of skew by default, so don't set it to zero. - A monotonic clock for durations. Measure timeouts and latency with
System.nanoTime(), notcurrentTimeMillis(), so that when NTP moves the clock back you don't get a negative duration. - Infrastructure: monitoring of chrony/NTP and an alert on clock offset (
node_timex_offset_secondsfrom node_exporter).
A good point to make in an interview: in a distributed system there is no reliable answer to "when?", but you can answer "after what?" with versions.
Sign up to mark studied questions and save your progress.