Share Python Timeout Budgets with time.monotonic_ns

A release tool has two sequential stages and a total budget of five seconds. Giving each stage a fresh five-second timeout permits roughly ten seconds of waiting. The intended rule is one deadline: time spent in the first stage reduces what the second stage may use.

These examples use Python 3.10 or later. They implement a small, cooperative budget for operations in one process. The helper reports remaining time; the operation receiving that value must enforce its own timeout.

Separate Wall Time from Elapsed Time

Calendar timestamps answer when an event happened. Timeout accounting asks how much time has passed. A system clock correction can change a wall-clock reading, so subtracting time.time() values is a poor basis for this budget.

The Python time reference documents a clock that cannot go backward and is unaffected by system clock updates. Its origin is unspecified; compare readings from the same clock rather than interpreting one as a calendar date.

time.monotonic_ns() supplies integer nanoseconds. Integer arithmetic keeps the deadline and its subtraction out of floating-point calculations. Nanosecond units do not imply nanosecond hardware resolution. Keep wall-clock timestamps for human-readable logs and monotonic differences for this deadline.

Create the Deadline Once

Save this module as budget.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import time


class Budget:
    def __init__(self, timeout_ms, *, clock=time.monotonic_ns):
        if type(timeout_ms) is not int:
            raise TypeError("timeout_ms must be an integer")
        if timeout_ms < 0:
            raise ValueError("timeout_ms must be nonnegative")
        self._clock = clock
        self._deadline_ns = clock() + timeout_ms * 1_000_000

    def remaining_ns(self):
        return max(0, self._deadline_ns - self._clock())

    def require_seconds(self):
        remaining = self.remaining_ns()
        if remaining == 0:
            raise TimeoutError("shared timeout budget exhausted")
        return remaining / 1_000_000_000

The public input is a nonnegative integer number of milliseconds. Booleans, fractional numbers, strings, and None are rejected. Zero creates an immediately exhausted budget. At the exact deadline, starting another stage is also rejected.

Each instance records its deadline only during construction. Calling require_seconds() samples the clock again without extending that deadline. Conversion to floating-point seconds occurs only at the consumer boundary; choose practical timeout values supported by that consumer’s API.

Pass the Remaining Budget to Each Stage

Add this function to budget.py:

1
2
3
4
5
def run_stages(first, second, timeout_ms, *, clock=time.monotonic_ns):
    budget = Budget(timeout_ms, clock=clock)
    first_result = first(timeout=budget.require_seconds())
    second_result = second(timeout=budget.require_seconds())
    return first_result, second_result

Both callbacks must accept timeout in seconds and apply it to their complete stage. The second callback receives the remaining allowance after the first callback returns. Constructing a new Budget before each callback would restart the allowance and defeat the shared limit.

Check the actual API being adapted. Some network APIs interpret a timeout as an inactivity limit or apply it separately to different phases. Passing a number to such an API does not automatically bound the entire stage. If the callback performs multiple waits, pass the same budget inward and recalculate before each wait.

An exception from either callback propagates. If the first stage consumes the budget, the next budget check raises before calling the second. Work already completed by the first stage remains completed; expiration supplies no rollback.

Test Boundaries with a Fake Clock

Save this as test_budget.py beside the module and run python test_budget.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from budget import Budget, run_stages


class FakeClock:
    def __init__(self):
        self.now_ns = 10_000_000_000

    def __call__(self):
        return self.now_ns

    def advance_ms(self, milliseconds):
        self.now_ns += milliseconds * 1_000_000


clock = FakeClock()
seen = []


def first(*, timeout):
    seen.append(timeout)
    clock.advance_ms(1200)
    return "downloaded"


def second(*, timeout):
    seen.append(timeout)
    clock.advance_ms(300)
    return "checked"


assert run_stages(first, second, 5000, clock=clock) == (
    "downloaded", "checked"
)
assert seen == [5.0, 3.8]

budget = Budget(1000, clock=clock)
clock.advance_ms(999)
assert budget.remaining_ns() == 1_000_000
clock.advance_ms(1)
assert budget.remaining_ns() == 0
try:
    budget.require_seconds()
except TimeoutError:
    pass
else:
    raise AssertionError("exact deadline must expire")

clock.advance_ms(500)
assert budget.remaining_ns() == 0
assert Budget(0, clock=clock).remaining_ns() == 0
print("Shared budget checks passed.")

The fake advances only when the test requests it. The assertions cover a reduced second-stage allowance, a positive value immediately before expiration, exact expiration, and clamping after expiration. No real sleep or scheduler timing makes the test flaky.

Treat Expiration as a Cooperative Boundary

This class cannot interrupt a callback that blocks forever or ignores its timeout. There is also time between checking the budget and beginning a wait. Completion may occur after the deadline because of scheduling, cleanup, or the consumer’s timeout behavior. A hard execution limit requires an execution model that can enforce it.

Retries and backoff should use the original budget too. Recheck after sleeping: the sleep documentation allows a suspension to exceed the requested duration. A requested delay is not proof of the exact elapsed interval.

Keep the deadline local to the running process. Do not save it as an expiry timestamp or send it to another machine. Suspension behavior depends on the underlying clock and platform, so define separate policy if the budget must include machine sleep. For ordinary sequential waits, one monotonic deadline makes the remaining allowance explicit at every stage.