Skip to content

Monotonic clock vs wall clock: which clock to use for timeouts, durations and leases

Why Date.now() is the wrong clock for a timeout, the monotonic clocks in JavaScript, Go, Rust, Python and Swift, and when the wall clock is right.

· 8 min read

  • Debugging
  • Reliability
  • Time

A timeout that fires half a minute late. A request logged as taking minus 30 seconds. A lease that expires the moment it is granted. These bugs share a cause: the code measured a duration with a clock that tells the time, and the time changed while it was measuring.

Every mainstream platform gives you two clocks for two jobs. This article explains what each does, shows a timeout breaking under a clock step, and sets out which clock to use for what, in JavaScript, Go, Rust, Python and Swift. Everything in it was run on Linux 6.18, Node 22, Go 1.24, Rust 1.97 and Python 3.11, except the Swift examples, which were checked against Apple’s documentation.

Two clocks, two jobs

The wall clock says what time it is: seconds since 1970, mapped to dates. Linux calls it CLOCK_REALTIME. It can be set by an administrator, and a time daemon such as ntpd or chronyd keeps it in line with the rest of the world. Most of the time that correction is a slew: the clock runs a little fast or slow until the error is gone. The kernel limits slewing to 500 parts per million, about 1.8 seconds an hour. When the error is too large to slew, by default more than 128 ms for more than 300 seconds, ntpd steps the clock instead: it jumps, forwards or back. chronyd steps only when configured to, normally with makestep, and its documentation recommends limiting that to the first few updates after boot; its own example configurations set makestep 1.0 3.

A leap second also steps CLOCK_REALTIME back by a second unless the time source smears it. There has been none since the one at the end of 2016, but the code path is still there. That one caused a Cloudflare DNS outage: a Go service measured a negative elapsed time across it. The design document for Go’s monotonic time support cites that incident as its motivation.

The monotonic clock measures elapsed time from an arbitrary point, on Linux the moment the system booted. CLOCK_MONOTONIC cannot be set and never jumps. It is slewed by the same NTP rate adjustments as the wall clock, so it stays an accurate measure of seconds, but a step in the wall clock does not touch it. Its readings mean nothing outside the machine they came from, and nothing after a reboot.

Linux has two variants worth knowing. CLOCK_MONOTONIC_RAW is the hardware counter without the rate adjustments, so it drifts at whatever rate the hardware drifts. (On the virtual machine this was written in, with no time daemon running, the two differed by a constant 0.3 seconds: an offset from boot, not a correction.) CLOCK_BOOTTIME is CLOCK_MONOTONIC plus the time the system spent suspended. More on that below.

Watching a timeout break

Here is a timeout written both ways. It polls every 100 ms and gives up after half a second:

const limitMs = 500;
const wallStart = Date.now();
const monoStart = performance.now();

const timer = setInterval(() => {
  const wall = Date.now() - wallStart;
  const mono = performance.now() - monoStart;
  console.log(`wall ${wall} ms, monotonic ${mono.toFixed(0)} ms`);
  if (wall >= limitMs) console.log("wall clock: timed out");
  if (mono >= limitMs) { console.log("monotonic: timed out"); clearInterval(timer); }
}, 100);

We cannot set the system clock inside a container, and would not want to on a shared machine. Instead, a short LD_PRELOAD library intercepts the C library’s clock calls and, after a few reads, reports the wall clock 30 seconds in the past. It hooks both clock_gettime and gettimeofday because programs differ: Node’s Date.now() uses gettimeofday, while Python and Rust read CLOCK_REALTIME through clock_gettime. One counter covers both. The monotonic clock is untouched.

// stepback.c: gcc -shared -fPIC -O2 -o stepback.so stepback.c -ldl
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

static long calls, after = 20, step = 30;

static void init(void) {
  if (getenv("STEP_AFTER")) after = atol(getenv("STEP_AFTER"));
  if (getenv("STEP_SECONDS")) step = atol(getenv("STEP_SECONDS"));
}

int clock_gettime(clockid_t id, struct timespec *ts) {
  static int (*real)(clockid_t, struct timespec *);
  if (!real) { real = dlsym(RTLD_NEXT, "clock_gettime"); init(); }
  int r = real(id, ts);
  if (id == CLOCK_REALTIME && ++calls > after) ts->tv_sec -= step;
  return r;
}

int gettimeofday(struct timeval *tv, void *tz) {
  static int (*real)(struct timeval *, void *);
  if (!real) { real = dlsym(RTLD_NEXT, "gettimeofday"); init(); }
  int r = real(tv, tz);
  if (++calls > after) tv->tv_sec -= step;
  return r;
}
$ STEP_AFTER=3 LD_PRELOAD=./stepback.so node timeout.js
wall 103 ms, monotonic 101 ms
wall -29798 ms, monotonic 200 ms
wall -29697 ms, monotonic 301 ms
wall -29596 ms, monotonic 402 ms
wall -29496 ms, monotonic 502 ms
monotonic: timed out

The wall-clock version would wait another 30 seconds before giving up. Step the clock forwards instead and it times out immediately. Either way the timeout is now a function of what NTP did at that moment. The monotonic version did not notice. The same shim gives the same result against Python’s time.time() and time.monotonic(), and against Rust’s SystemTime and Instant.

It is also a useful test. Run your service under it and watch for negative durations in logs, retries that fire at once, and rate limiters that open or close. One caveat: Go’s runtime reads the clock through the vDSO itself rather than through the C library, and a pure Go binary is not even dynamically linked, so the shim cannot intercept it.

What each language gives you

Language Wall clock Monotonic
JavaScript Date.now() performance.now(); in Node also process.hrtime.bigint()
Go time.Now() (wall reading) time.Now() (monotonic reading, used by Sub and Since)
Rust SystemTime::now() Instant::now()
Python time.time() time.monotonic(), time.perf_counter()
Swift Date() ContinuousClock, SuspendingClock

Some details matter.

JavaScript. performance.now() counts milliseconds from the time origin, which in Node is process start, and is not affected by clock adjustments. In browsers the specification requires it to be coarsened to at least 100 microseconds, or 5 in cross-origin isolated pages, and allows jitter on top, so do not expect nanoseconds. Never persist or send a performance.now() value: another process has a different origin.

Go hides the monotonic clock inside time.Time. time.Now() records both readings, and Sub, Since, Until, Before, After, Compare and Equal use the monotonic ones when both operands have them. Values from time.Unix, time.Date, time.Parse or decoding carry no monotonic reading, and Round, Truncate, In, UTC and Local remove it, so a comparison involving one of those silently falls back to the wall clock. The debug output shows which you have:

start := time.Now()
fmt.Println(start)          // 2026-11-16 09:00:32.078211719 +0000 UTC m=+0.000034453
fmt.Println(start.Round(0)) // 2026-11-16 09:00:32.078211719 +0000 UTC

time.Sleep(20 * time.Millisecond)
fmt.Println(time.Since(start))          // 20.394054ms, measured on the monotonic clock
fmt.Println(time.Since(start.Round(0))) // 20.423096ms, measured on the wall clock

fmt.Println(start == start.Round(0), start.Equal(start.Round(0))) // false true

The m= suffix is the monotonic reading. == compares it too, which is why two times for the same instant compare unequal above; use Equal. Go reads CLOCK_MONOTONIC on Linux, and a proposal to switch to CLOCK_BOOTTIME was withdrawn in 2019.

Rust keeps the clocks as separate types. SystemTime::duration_since returns a Result, because the earlier time may be later once the clock has moved. Instant::duration_since and elapsed saturate to zero if the platform’s monotonic clock misbehaves; earlier versions panicked. On Linux Instant reads CLOCK_MONOTONIC and SystemTime reads CLOCK_REALTIME, which we confirmed by logging the calls. On Darwin the standard library documentation says Instant uses CLOCK_UPTIME_RAW.

Python reports what each clock is built on:

>>> time.get_clock_info("time")
namespace(implementation='clock_gettime(CLOCK_REALTIME)', monotonic=False, adjustable=True, resolution=1e-09)
>>> time.get_clock_info("monotonic")
namespace(implementation='clock_gettime(CLOCK_MONOTONIC)', monotonic=True, adjustable=False, resolution=1e-09)

On this Linux build perf_counter is the same clock as monotonic. time.clock_gettime(time.CLOCK_BOOTTIME) is there if you need the suspend-aware one.

The third clock: what happens during sleep

Close a laptop or put a phone in a pocket and the system suspends. Does the monotonic clock keep counting? On Linux, CLOCK_MONOTONIC does not and CLOCK_BOOTTIME does. Go and Rust use CLOCK_MONOTONIC, so a Go time.Since or a Rust elapsed() that spans a two-hour suspend measures only the time the machine was awake. Apple’s mach_absolute_time stops too; mach_continuous_time does not, and Apple’s documentation names clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) as its equivalent, so on Darwin that clock includes sleep, the opposite of Linux. DispatchTime is built on mach_absolute_time: its uptimeNanoseconds is documented as excluding “any time the system spent asleep”.

Swift’s concurrency clocks make the choice explicit, which is the right design for a platform where devices sleep constantly:

let start = ContinuousClock.now          // keeps counting while the device sleeps
await upload()
let elapsed = ContinuousClock.now - start

let awake = SuspendingClock().measure {  // stops while the device sleeps
    renderThumbnails()
}

try await Task.sleep(for: .seconds(30)) // defaults to the continuous clock

Both clocks are available from iOS 16 and macOS 13. Which one you want depends on what the duration means. A request timeout should be continuous: if the phone slept for ten minutes, the server gave up long ago and the request should fail now rather than run for another thirty seconds. A benchmark or a “time spent in this screen” metric should be suspending. An animation should be suspending too, or it jumps to its end state on wake.

Which clock for what

The rule from Go’s design document is the right one: the wall clock is for telling time; the monotonic clock is for measuring it. In practice:

  • Durations, timeouts, retry backoff, rate limiters, cache TTLs held in memory: monotonic. Nothing here needs to know what time it is.
  • Timestamps on records, log lines, audit trails, anything a human or another machine reads: wall clock. A monotonic value is meaningless anywhere else.
  • Expiry that other systems must agree on, such as tokens and certificates: wall clock, with a tolerance for skew between machines. A few seconds is normal; validate accordingly.
  • Leases and locks shared across machines: wall clock, but let one clock be the authority. Our Postgres job queue sets and checks locked_until with the database’s now(), so worker clocks never enter into it. Remember that Postgres’s now() is frozen at the start of the transaction; clock_timestamp() is the current time, and inside one transaction we measured them 0.3 seconds apart after a pg_sleep(0.3).
  • Scheduling for a time of day: wall clock, and expect it to move. A scheduler that computes a monotonic delay to 03:00 and sleeps is wrong after the first NTP step; re-read the clock and recompute.

Two habits make the rest easy. Inject the clock into anything you want to test, as a now() function or an interface, so a test can advance it or step it back without a preload shim. And never store or transmit a monotonic reading: serialise wall-clock time, and derive durations from the monotonic clock in the process that measured them.

Timeouts, leases and retries are where the backends we build earn their reliability, and getting the clock right is part of that work: see our backend development service. Related reading: idempotent payment webhooks for what happens when a retry arrives twice, and reading a flame graph for measuring where the time went once you have measured it correctly.

Have something you'd like built?

Tell us what you're building. We'll reply within two working days with questions, an approach and next steps.

Start a project
Esc

↑ ↓ to move · Enter to open