← Building blocks

Do not trust the client clock

Consistency & coordinationsenior

Ordering, expiry and rate limits based on client timestamps are wrong when clocks drift.

Say it like this

Rate-limit windows and message order must not depend on client or even app-server clocks, so I take the timestamp from Redis TIME inside the script and use sequence numbers for ordering.

Basic solution

Use server time for anything that matters; use monotonic clocks for intervals; NTP all servers.

Redis TIMEhybrid logical clocksTrueTime (Spanner)

One clock for the decision

Gateways with skewed clocks send requests into the same limiter. The script reads TIME on the Redis node, so the window and the refill are computed on one clock regardless of which gateway forwarded the request.

How it works

  1. Every machine has its own clock. NTP (the protocol that synchronises clocks over the network) keeps servers within a few milliseconds of each other in a healthy data centre, but a bad sync, a VM pause or a leap second can push one off by seconds. Phones and laptops can be off by minutes.
  2. For anything that decides behaviour (expiry, windows, ordering, limits), take the time from one place: the store that enforces the rule reads its own clock inside the operation, or the single owner of a stream stamps each event. Then two requests that reach that place are compared on one clock.
  3. For measuring durations (timeouts, latency), use the monotonic clock, a counter that only moves forward and never jumps when NTP corrects the wall clock. Subtracting two monotonic readings gives a reliable elapsed time.
  4. For ordering events across nodes, use sequence numbers or logical clocks; wall-clock timestamps are for display and for coarse partitioning such as choosing which daily table a row belongs in.
  5. When wall-clock time must be compared across nodes, design for a skew budget: treat two events within a few hundred milliseconds of each other as concurrent rather than ordered, and make sure no decision flips because one clock is slightly ahead.
  6. For global ordering by time (Spanner), bounded-uncertainty clocks report an interval such as "now is between 10:00:00.003 and 10:00:00.007" and a transaction waits until the interval has passed before committing, so no later transaction can get an earlier timestamp. That only works with GPS and atomic clock hardware in every data centre.

What NTP gives you and what it does not

  • Typical skew in a well-run fleet: under 1 ms. During an incident: seconds. On client devices: unbounded.

Worked example

Rate limiter, sliding window with server clocks

  • Limit 100 requests per minute per key, enforced by 20 gateways against one Redis primary.
  • If each gateway uses its own clock and gateway 3 is 3 seconds fast, requests passing through it land in a window that the others consider future. Near the boundary a client gets up to 5 percent extra requests (3 of 60 seconds), and the Retry-After values the gateways compute disagree.
  • Fix: the Lua script calls TIME on the Redis node and uses that for both the window and the refill. Every gateway now sees the same clock. Cost: zero extra round trips because it happens inside the script.
  • Chat ordering: two servers 50 ms apart would reorder messages sent 20 ms apart. With a per-conversation sequence number the clock does not matter; the client timestamp is shown but never sorted on.
  • Token expiry: a JWT with exp set by an auth server whose clock is 2 minutes fast is accepted 2 minutes longer than intended. Allow a small leeway (30 seconds) and keep token lifetimes short so the error is bounded.

Variants and when each wins

Single source of time (the store's clock)

  • The decision reads the clock of the store that enforces it: Redis TIME inside the script, the database's now(), or the broker's append timestamp. It wins for limits and expiry because it removes skew between application nodes entirely, and it is the default.

Monotonic clocks for intervals

  • A clock that counts forward from boot and never jumps, read through clock_gettime(CLOCK_MONOTONIC) or System.nanoTime. It wins for timeouts and durations, and is meaningless across machines because each one starts from a different zero.

Logical clocks (Lamport, vector, hybrid logical clocks)

  • Counters that order events by cause and effect rather than by time; a hybrid logical clock combines wall time with a counter so timestamps stay close to real time but never go backwards. They win when events on different nodes must be ordered consistently, which is why CockroachDB uses them.

Bounded-uncertainty clocks (TrueTime)

  • GPS and atomic clocks give each node a time interval it is certainly within, and transactions wait out the interval before committing. It wins when you need linearizable global ordering across continents, and it requires dedicated hardware in every data centre.

Recommendation: store clock for decisions, monotonic for durations, sequence numbers for order, and treat wall clocks as approximate everywhere else.

Failure modes

Negative durations and instant timeouts

  • You notice a request timing out the instant it starts, or a latency metric showing a negative number. It happens because the code measured an interval with the wall clock, and NTP stepped the clock backwards between the two readings. Measure every duration with the monotonic clock.

Rate limit overshoot or starvation at the boundary

  • You notice some clients getting more than their limit while others are limited early. It happens because each gateway defines the window by its own clock, so a fast gateway counts a request in the next window while a slow one still counts it in the current one. Read the clock from the store inside the atomic script, so every gateway uses the same window.

Reordered messages

  • You notice a reply showing above the message it answers. It happens because the messages were sorted by timestamps taken on different servers or clients, and one clock was behind. Sort by a server-assigned sequence number per stream.

Expiry that is too early or too late

  • You notice sessions logged out early, or links still alive after their expiry. It happens because the expiry was set from one machine's clock and checked against a different machine's clock. Compute the expiry and check it on the same clock, and add a bounded leeway for the cases where that is impossible.

Last-writer-wins picks the wrong writer

  • You notice an older edit overwriting a newer one after an outage. It happens because the conflict was resolved by comparing timestamps from skewed nodes, and the node that wrote the older edit had the faster clock. Resolve conflicts with version numbers, vector clocks, or a hybrid logical clock that includes a logical counter.

Interviewer follow-ups

Answer out loud before you open each one.

Why is a monotonic clock safe for timeouts but useless for timestamps?

It counts time since an arbitrary point, usually boot, and is guaranteed never to go backwards, so differences between two readings are reliable. It has no relation to calendar time and differs on every machine, so it cannot be stored or compared across nodes.

How does a hybrid logical clock work?

Each node keeps the maximum wall time it has seen plus a counter. On a local event it uses its own clock if that is ahead, otherwise increments the counter. On receiving a message it adopts the larger timestamp. Timestamps stay close to real time while preserving causal order.

How would you handle a client whose clock is a year off?

Never trust it for decisions. The server stamps every event on receipt and stores both the server time and the client time; sorting and expiry use the server time and the client time is shown only to the user, with a sanity clamp if it is wildly off.

What is the skew budget in a design and where does it show up?

The maximum clock difference the design tolerates without a wrong decision, usually a few hundred milliseconds. It shows up as leeway on token expiry checks, as the window in which two writes are treated as concurrent, and as the reason windows and sequences are owned by one node.

Connections

Built on
Vector clock
Pairs with
Order events within a stream · Limit requests per client · Never wait forever · Expire data automatically
Pulls against
Accept a short delay for scale
Used in
Distributed Rate Limiter · Chat App (WhatsApp / Messenger)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon API GatewayGateway 3, Gateway 7, Gateway 12API Gateway, ApigeeAPI ManagementKong, Tyk
Amazon ElastiCacheRedis limiterMemorystoreAzure Managed RedisRedis, Valkey, Memcached