# How to inject a fake clock into an SDK to test timeouts

> Pass a clock to the SDK's constructor so a test of a 30-second deadline runs on virtual time and still raises the timeout error, in TypeScript, Go, and Python.

Source: https://voxgig.com/howto/inject-a-fake-clock-to-test-timeouts

- Audience: library-maintainer
- Level: intermediate
- Languages: typescript, go, python
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Give the SDK a clock with now() and sleep() in its constructor, and route every deadline, attempt limit, and backoff through it. In tests, pass a manual clock that jumps to the next pending sleep and a fake transport with no socket. A 30-second deadline then raises its error on virtual time. Go's testing/synctest reaches the same result without the parameter, inside a bubble of fake time, and Python's freezegun by patching the time module.

---
## You will need

An SDK with a timeout or deadline, and the runtimes for the languages you test. The TypeScript files
run with Node's type stripping, which needs Node 22.18 or later. The Go tests run on Go 1.24 or
later, and the `synctest` test needs 1.25. The Python samples ran on 3.12. The transport is
already a function the client calls, as in [wrapping an SDK transport with middleware](/howto/wrap-an-sdk-transport-with-middleware), so a
test can hand it a fake.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [@sinonjs/fake-timers](https://github.com/sinonjs/fake-timers#var-clock--faketimersinstallconfig) or [Jest fake timers](https://jestjs.io/docs/jest-object#jestusefaketimersfaketimersconfig) | You cannot change the SDK, and it reads `setTimeout` and `performance.now` | Patches the whole process; the default install hung a real `node:http` request here | The test also talks to a real socket, or you own the SDK |
| [constructor-injected clock interface](https://go.dev/blog/testing-time) | You own the SDK and test it in several runtimes or frameworks | One more constructor option, and every wait in the SDK must use it, transports included | The SDK is someone else's, or Go's bubble already covers it |
| [Go testing/synctest](https://pkg.go.dev/testing/synctest#Test) or [jonboulle/clockwork](https://pkg.go.dev/github.com/jonboulle/clockwork@v0.5.0) | Go 1.25 for `synctest` with no SDK change; clockwork for an injected clock, which also runs on Go 1.24 | `synctest` needs every goroutine inside the bubble; clockwork needs a loop that advances the clock | The code waits on real network I/O, which no bubble controls |
| [Python freezegun](https://github.com/spulec/freezegun#readme) or [time-machine](https://time-machine.readthedocs.io/en/latest/usage.html) | A Python SDK you cannot change, which reads the time module | Neither replaces `time.sleep`, and time-machine left `time.monotonic` unmoved with `tick` on or off | The SDK computes deadlines on `time.monotonic` and you picked time-machine |

An injected clock costs a constructor option and the discipline to send every wait through it, and
in exchange it works in any runtime and any test framework. Global fake timers need no change to
the SDK, but they patch everything underneath it too. Go's `synctest` is the exception, because its
fake clock applies only inside its bubble.

## Put the clock in the constructor

The interface is two methods: a monotonic reading in milliseconds, and a sleep that a signal can
cancel.

```ts title="sdk.ts"
export interface Clock {
  /** Milliseconds on a monotonic scale. Only differences mean anything. */
  now(): number
  /** Resolves after ms; rejects with signal.reason if the signal aborts first. */
  sleep(ms: number, signal?: AbortSignal): Promise<void>
}
```

Each attempt races the transport against a sleep on that clock, and cancels whichever side lost.

```ts title="sdk.ts"
  async function attemptOnce(path: string, budgetMs: number): Promise<string> {
    const request = new AbortController()
    const timer = new AbortController()
    try {
      return await Promise.race([
        transport(path, request.signal),
        clock.sleep(budgetMs, timer.signal).then(() => {
          throw new AttemptTimeout()
        }),
      ])
    } finally {
      // Whichever side lost is cancelled: the request on a timeout, the timer on an answer.
      request.abort(new AttemptTimeout())
      timer.abort(new Error('attempt settled'))
    }
  }
```

The production default is `systemClock`, built on `setTimeout` and `performance.now`, so callers who
never pass a clock see no change.

## Drive a manual clock in the test

The test clock never advances on its own. `run()` lets pending callbacks finish, then jumps to the
earliest sleep, and repeats until the work settles.

```ts title="manual-clock.ts"
  async run<T>(work: Promise<T>, maxJumps = 1_000): Promise<T> {
    let settled = false
    work.then(
      () => (settled = true),
      () => (settled = true),
    )
    for (let jump = 0; jump <= maxJumps; jump++) {
      // Let every pending callback run before deciding the work is waiting on the clock.
      await new Promise((resolve) => setImmediate(resolve))
      if (settled) return work
      this.#sleepers.sort((a, b) => a.at - b.at || a.seq - b.seq)
      const next = this.#sleepers.shift()
      if (!next) throw new Error('the work is waiting on something other than this clock')
      this.#now = next.at
      next.resolve()
    }
    throw new Error(`still running after ${maxJumps} jumps`)
  }
```

Run the client against a fake transport that never answers:

```bash
node demo.ts
```

```text output
attempt 1   5000 ms  attempt timed out
attempt 2  11000 ms  attempt timed out
attempt 3  18000 ms  attempt timed out
attempt 4  27000 ms  attempt timed out
DeadlineExceededError: deadline exceeded after 4 attempts and 30000 ms
virtual time 30000 ms; real time under 5 s: true
```

Each attempt gets five seconds, and the backoffs between them are one, two, and four seconds. The
fourth backoff, eight seconds, is cut to the three seconds left, so the deadline lands at exactly
30000 virtual milliseconds.

## Check it worked

The first test asserts the error, four attempts, 30000 ms on the clock, a cancellation of every attempt,
and less than five seconds of real time. The bound is deliberately loose, because the claim is that
30 seconds did not pass, not that this machine is fast.

```bash
node --test clock.test.ts
```

```text output
1..6
# tests 6
# suites 0
# pass 6
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 276.903589
```

Swap `clock.sleep` for `systemClock.sleep` in `attemptOnce` and the first test fails.

## Patch time globally instead

With no clock passed, the client falls back to `setTimeout` and `performance.now`, and
@sinonjs/fake-timers can replace both. The second half of the script sends a plain `node:http`
request to a local server under three installs.

```bash
node sinon.ts
```

```text output
toFake setTimeout, clearTimeout, performance
  deadline exceeded after 4 attempts and 30000 ms; real time under 5 s: true
default install (fakes every method)
  node:http GET to 127.0.0.1: no answer within 5 s of real time
toFake ['nextTick']
  node:http GET to 127.0.0.1: no answer within 5 s of real time
toFake ['setTimeout', 'clearTimeout', 'performance']
  node:http GET to 127.0.0.1: answered
```

The README says an install with no `toFake` list fakes every method it supports, and faking
`nextTick` alone was enough to stall the request. Jest's
[`doNotFake`](https://jestjs.io/docs/jest-object#jestusefaketimersfaketimersconfig) option makes
the same choice from the other side, and its documentation says its default fakes every API.

In Go, one test injects a clockwork `FakeClock` and advances it whenever the client waits on it.
The other passes no clock at all and runs inside `synctest.Test`.

```bash
node go-tests.mjs
```

```text output
PASS  TestDeadlineInjectedClockwork
      sdk_test.go:51: deadline exceeded after 4 attempts and 30s; clock elapsed 30s
PASS  TestPermanentErrorIsNotRetried
PASS  TestDeadlineSynctest
      synctest_test.go:19: deadline exceeded after 4 attempts and 30s; clock elapsed 30s
```

[`synctest.Test`](https://go.dev/doc/go1.25#new-testingsynctest-package) arrived in Go 1.25, so its
test sits in a file marked `//go:build go1.25`. Go 1.24 leaves that file out and runs the two
clockwork tests, which is the route for a toolchain without `synctest`.

In Python, the same client runs under an injected `ManualClock`, under freezegun with `time.sleep`
patched to `tick`, and under time-machine with `time.sleep` patched to `shift`:

```bash
python3 -I python/compare.py
```

```text output
injected ManualClock               DeadlineExceeded: deadline exceeded after 4 attempts and 30 s; real time under 5 s: True
freezegun 1.5.5, sleep -> tick     DeadlineExceeded: deadline exceeded after 4 attempts and 30 s; real time under 5 s: True
time-machine 3.6.0, SystemClock    RuntimeError: stopped by the guard after 100 attempts; real time under 5 s: True
time-machine 3.6.0, WallClock      DeadlineExceeded: deadline exceeded after 4 attempts and 30 s; real time under 5 s: True
```

Time-machine moved `time.time` and left `time.monotonic` where it was, so a deadline measured on the
monotonic clock never arrived until the guard stopped it. Its
[usage page](https://time-machine.readthedocs.io/en/latest/usage.html) lists the functions it mocks,
and `time.monotonic` is not among them; `time.clock_gettime` is mocked for `CLOCK_REALTIME` only. A wall-clock reading works under it, at the price of a
deadline that jumps whenever the system clock is set.

The Python tests pin each of those findings, with `tick` on and off, and also that neither library
replaces `time.sleep` under any option the test tries:

```bash
python3 -I python/test_sdk.py
```

```text output
ok   test_a_transient_failure_is_retried_after_the_backoff
ok   test_bad_limits_are_refused
ok   test_freezegun_moves_monotonic_and_rewrites_module_attributes
ok   test_injected_clock_reaches_the_deadline_without_real_waiting
ok   test_neither_library_replaces_sleep
ok   test_time_machine_leaves_monotonic_alone
```

## When it goes wrong

The test with a fake clock still takes the real time. The timeout lives on the socket, where no
fake clock reaches, so pair the fake clock with a fake transport. The same 1500 ms timeout, once on
a socket and once on the manual clock:

```bash
node pitfall.ts
```

```text output
socket timeout 1500 ms  clock moved to 60000 ms; call settled: false
                        TransientError: socket idle for 1500 ms; waited at least 1.4 s of real time: true
clock timeout 1500 ms   clock moved to 1500 ms
                        TransientError: no answer within 1500 ms on the clock; waited at least 1.4 s of real time: false
```

Sixty virtual seconds passed while the socket call stayed pending.

`run()` throws `the work is waiting on something other than this clock`. Some wait in the SDK skipped
the injected clock, or the transport is real; the last test in `clock.test.ts` shows the message.
Send that wait through `clock.sleep`.

A timing measured inside a freezegun block reads the frozen time. freezegun replaces
`time.perf_counter` as well as `time.monotonic`, and it rewrites module attributes that hold the
real functions.[^1] The Python test asserts both, and `compare.py` keeps its real timer inside a
dict for that reason.

## When not to do this

Do not add a clock parameter to an SDK whose only timeout is the socket's own. A clock cannot
shorten a timer it does not own, and the test still needs a fake transport. Test the socket timeout
once, with a short limit, against a server that never answers.

Keep global fake timers out of integration tests. The default install stalled a plain
HTTP request here, and the same patch reaches every library in the process.

Do not use time-machine for a Python SDK that measures deadlines on `time.monotonic`. Inject a clock,
or use freezegun, which moved the monotonic clock in the same run.[^2]

## Related how-tos

- [Enforce one total deadline across all retry attempts](/howto/enforce-a-total-deadline-across-retry-attempts)

- [Inject latency and failures into SDK tests](/howto/inject-latency-and-failures-into-sdk-tests)

- [Audit SDK retry and timeout defaults before adoption](/howto/audit-sdk-retry-and-timeout-defaults)

- [Inject a deterministic idempotency key generator for tests](/howto/inject-a-key-generator-into-sdk-idempotency)

## Last verified

Verified 2026-11-30 against Node 22.23.5, Go 1.25.14, Python 3.12.3, @sinonjs/fake-timers 15.5.0,
clockwork v0.5.0, freezegun 1.5.5, time-machine 3.6.0, and python-dateutil 4.0.0. The clockwork
tests also ran on Go 1.24.7. Every output block is what the command preceding it printed. Jest was not run; its default and `doNotFake` are read
from its documentation.

[^1]: The rewrite is in freezegun's
[`api.py`](https://github.com/spulec/freezegun/blob/1.5.5/freezegun/api.py): on entry it walks
`sys.modules` and, for each module attribute outside its ignore list that holds a real time
function, sets the fake in its place. That is how a module that ran `from time import monotonic` sees frozen time. It also means a
helper that saved the real function at import time to measure the test is holding the fake.

[^2]: freezegun's README offers a `real_asyncio` parameter, which lets asyncio event loops see real
monotonic time while `time.monotonic()` itself stays frozen. The
[README](https://github.com/spulec/freezegun#readme) gives the reason: without it, `asyncio.sleep()`
and the other asyncio functions that rely on monotonic time break.