skip to content

A C++ gateway's rate limiter built on system_clock::now() stopped admitting requests for an hour after an NTP clock step; what went wrong, and how do you fix it?

level: seniorimportance: should knowfreq 45%

answer

  1. the window start was wall time
  2. negative elapsed time
  3. intervals on the stopwatch clock
  4. convert deadlines once, at the edge
  5. inject the clock to test it

basics

~20 s

The limiter stored its window start as a system_clock time; when the wall clock stepped back an hour, now minus start stayed negative, so the window never reset. Measure every in-process interval with steady_clock and keep system_clock for timestamps.

solid answer

~50 s

A fixed-window limiter resets its counter when `now - windowStart >= window`. With `system_clock`, a one-hour backward step makes `now - windowStart` about minus one hour, so the reset condition stays false and every request is refused until wall time passes the old start; a forward step does the opposite and resets early, admitting a burst. The fix is to compute windows, timeouts, retry delays and deadlines with `std::chrono::steady_clock`, whose time points never decrease. Keep `system_clock` for log timestamps and values exchanged with other hosts. When a deadline arrives as wall time, convert it once: `remaining = deadline - system_clock::now()`, then `localDeadline = steady_clock::now() + remaining`. There is no conversion between the two clocks, since `steady_clock` has an unspecified epoch. Making the limiter a template on `Clock` lets a test inject a fake clock that steps.

code

cpp · 44 lines
cpp
#include <chrono>
#include <iostream>

// A fake wall clock the test can step, like an NTP correction would.
struct FakeWallClock {
    using duration = std::chrono::milliseconds;
    using rep = duration::rep;
    using period = duration::period;
    using time_point = std::chrono::time_point<FakeWallClock>;
    static constexpr bool is_steady = false;
    static inline time_point current{};
    static time_point now() { return current; }
};

template <class Clock>
class FixedWindowLimiter {                      // at most `limit` requests per window
public:
    FixedWindowLimiter(int limit, typename Clock::duration window)
        : limit_(limit), window_(window), start_(Clock::now()) {}
    bool admit() {
        const auto now = Clock::now();
        if (now - start_ >= window_) { start_ = now; used_ = 0; }  // negative after a backward step
        return used_ < limit_ ? (++used_, true) : false;
    }
private:
    int limit_, used_ = 0;
    typename Clock::duration window_;
    typename Clock::time_point start_;
};

int main() {
    using namespace std::chrono_literals;
    FakeWallClock::current = FakeWallClock::time_point{10h};
    FixedWindowLimiter<FakeWallClock> limiter(2, 1s);
    std::cout << limiter.admit() << limiter.admit() << limiter.admit() << '\n';  // 110
    FakeWallClock::current -= 1h;                                // NTP steps the clock back
    FakeWallClock::current += 5s;                                // five real seconds pass
    std::cout << limiter.admit() << '\n';                        // 0: window never resets
    FakeWallClock::current += 1h;                                // an hour of real time later
    std::cout << limiter.admit() << '\n';                        // 1

    FixedWindowLimiter<std::chrono::steady_clock> production(100, 1s);  // the fix
    std::cout << production.admit() << '\n';                     // 1
}

go deeper

for a junior

Recall that steady_clock is for measuring intervals and system_clock for wall-clock timestamps.

for a middle

Explain how a backward step makes now minus start negative and why a fixed-window reset condition then never fires.

for a senior

Show the diagnosis, the boundary conversion from a wall-clock deadline to a steady deadline, and a test that injects a stepping fake clock.

for a principal

Turn the incident into a convention: which clock each kind of value uses, a static_assert in timing utilities, and an audit of existing call sites.

## What happened A gateway admits at most `N` requests per second per client. The simplest implementation is a **fixed window**: remember when the current window started, count requests, and reset when a full window has passed. ```cpp const auto now = std::chrono::system_clock::now(); if (now - windowStart >= 1s) { windowStart = now; used = 0; } ``` At 10:00 the host's clock was an hour fast; a time-synchronization daemon corrected it by **stepping** it back to 09:00. The next `system_clock::now()` returned roughly 09:00, so `now - windowStart` was about **minus one hour**. A negative duration is never `>= 1s`, the counter never reset, and every client at its limit was refused until the wall clock passed 10:00 again. Nothing crashed and nothing was logged as an error, which is why such incidents are slow to diagnose. ## Why system_clock behaves this way The standard describes `system_clock` as **wall clock time from the system-wide realtime clock**. Its `is_steady` is unspecified and is `false` on mainstream platforms, because the operating system lets that clock be set: - a time-synchronization daemon may step it when the offset is large, or slew it gradually; - an administrator or orchestration tool can set it; - a virtual machine resumed from a snapshot can return with a stale clock that is then corrected. `steady_clock`, by contrast, is specified so that its time points **never decrease** and **advance at a steady rate relative to real time**: the clock may not be adjusted. | Symptom | Backward step | Forward step | |---|---|---| | Fixed-window limiter | window never resets: requests refused | window resets early: burst admitted | | Timeout `start + 5s` checked against `now()` | fires late | fires immediately | | Request latency `end - start` | negative or too small | too large | ## The fix 1. **Use `steady_clock` for every in-process interval**: rate-limit windows, token-bucket refills, timeouts, retry backoff, request latency and cache ages. 2. **Keep `system_clock` for civil time**: log timestamps, `Date` and expiry headers, values persisted to a database or sent to another host. Those must survive a restart and be understood elsewhere, which a `steady_clock` value cannot, because its epoch is unspecified. 3. **Convert at the boundary, once.** A client sends an absolute deadline in wall time. Compute the remaining budget against `system_clock` immediately, then add it to `steady_clock::now()`. From then on the deadline is immune to steps. There is no `clock_cast` between the two clocks: the standard defines no conversion for `steady_clock`, because there is no fixed relationship to define. 4. **Treat a negative remaining budget as expired**, since the wall-clock deadline may already have passed. ## Make the clock a parameter Clock-dependent bugs are hard to reproduce because they need the clock to move. Making the component a template on the clock type, as `FixedWindowLimiter<Clock>` does in the example, lets production use `steady_clock` and a unit test use a hand-written clock that satisfies the clock requirements: `rep`, `period`, `duration`, `time_point`, `is_steady` and a static `now()`. The test can then step the fake clock back an hour and assert the limiter's behaviour. To keep `system_clock` from creeping back, give production code one alias, `using GatewayLimiter = FixedWindowLimiter<std::chrono::steady_clock>;`, and use only that. The fake clock in the example declares `is_steady = false` because it imitates the adjustable wall clock that caused the incident. ## What to say in the post-mortem - The defect is **choosing the wrong clock**, not the time daemon: stepping the wall clock is normal operation. - Audit for `system_clock::now()` used in subtraction or comparison with an earlier reading; each one is a candidate. - Waiting on a condition variable or a lock with a timeout raises the same clock question; that belongs to the material on concurrency, but the rule is the same: express relative waits as durations, and prefer `steady_clock` deadlines. ## Other limiter designs, same clock rule A **token bucket** keeps a token count and the time of the last refill; on each request it adds `elapsed * rate` tokens, capped at the bucket size. A **sliding-window log** keeps the time points of recent requests and drops those older than the window. Both compute `now - earlier` on every request, so both fail exactly like the fixed window if `now` comes from `system_clock`: a backward step yields negative refills or a window that never empties. The clock choice, not the algorithm, decides whether a step can hurt.

  • Why not convert a steady_clock time point to system_clock with clock_cast for logging?
    The standard's `clock_cast` works through `clock_time_conversion` specializations that go via `system_clock` or `utc_clock`, and a source clock needs `to_sys` or `to_utc` for that. `steady_clock` has neither, because its epoch is unspecified and has no fixed relation to civil time. Log a separate `system_clock::now()` reading, or log a `steady_clock` duration as elapsed time.
  • Does switching to steady_clock fully protect a token bucket from clock problems?
    It removes steps, the main hazard, because steady_clock never decreases. What remains is scope: a `steady_clock` value only means something inside one program run, so a limiter whose state is shared between instances, or persisted across restarts, cannot store `steady_clock` time points. Such a limiter needs a shared store with its own notion of time, or wall-clock values guarded so that a negative elapsed time is treated as a reset.

  • system_clock is monotonic on Linux servers, so steps cannot happen
  • a backward clock step only delays one request
  • clock_cast converts a steady_clock time point to system_clock
  • steady_clock values can be stored in a database for later comparison
  • using high_resolution_clock fixes the problem on every platform