How to Compose Timeout Budgets
Propagate one deadline from the entry point, derive per-call timeouts from the remainder, and keep retries inside the same budget.
On this page
Introduction
Timeouts are usually configured per layer by feel, a 5-second handler here, a 3-second database call there, a 10-second upstream client somewhere else, and the resulting composition misbehaves in two directions at once. Downstream work outlives upstream patience: the handler waits on a dependency that the gateway has already given up on, burning connections and CPU on results nobody will read. And upstream patience outlives useful work: the gateway holds the client for 10 seconds while the remaining chain needed 20, so the user sees a timeout where a fast, honest failure was possible. Both pathologies share one root cause: each layer picked a number for itself, and nobody owns the total. The fix is a budget, one deadline established at the entry point and propagated downward, from which every internal timeout is derived as remaining time minus still-owed work. This tutorial implements the pattern in Go, where context makes it native, and in TypeScript with AbortSignal, then handles the two interactions that make it subtle: retries competing for the same budget, and queues that hold work before it starts.
The arithmetic of composition
Walk a concrete request to see the composition problem. A gateway allows 10 seconds. The handler holds a 5-second timeout and calls two dependencies in sequence, each with a 3-second timeout, then serializes a large response that takes 1 second. The worst case is 3 plus 3 plus 1, 7 seconds, which fits, but only by luck, and the luck evaporates under retries: one retry on each dependency makes the worst case 13 seconds, exceeding the gateway’s patience while every individual number still looks sane. Reverse the misfit: shrink the handler to 2 seconds and the composition aborts its own useful work, killing calls that would have succeeded in the 10 seconds actually available. The static table cannot win in both directions because it does not know the remaining time at the moment each call starts. The budget model replaces luck with arithmetic: the deadline is fixed at entry, each call receives the remainder, and the composition’s worst case is bounded by construction rather than by review. The numbers stop being configuration folklore and become derivable at runtime.
Propagate a deadline in Go
Go’s context package is the canonical implementation: the deadline is an absolute time carried through the call graph, and every operation derives its timeout from the remaining time.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
price, err := h.pricing.Quote(ctx, h.remainFor(r, quoteOwedAfter))
if err != nil {
http.Error(w, "pricing unavailable", http.StatusServiceUnavailable)
return
}
json.NewEncoder(w).Encode(price)
}
func (d *Pricing) Quote(ctx context.Context, ...) (Quote, error) {
if deadline, ok := ctx.Deadline(); ok {
remaining := time.Until(deadline)
if remaining < minUseful {
return Quote{}, fmt.Errorf("budget exhausted before quote: %w", context.DeadlineExceeded)
}
}
// derive the inner timeout from the context, not from a constant
inner, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
return d.upstream.Quote(inner)
}
Two habits make this correct in practice. Check the remaining budget before starting expensive work: a call that cannot finish in the remaining time should fail fast with a budget-exhausted error rather than start and be cancelled at ninety percent. And always pass ctx as the first parameter, because the deadline travels with it, and a function that accepts a context but derives timeouts from constants has adopted the signature of budgeting without the semantics.
Compose signals in TypeScript
The browser and Node model cancellation through AbortSignal, and budget composition is signal combination. The entry point creates the total budget, each call derives a shorter one from the remainder, and AbortSignal.any composes them so either the outer budget or the inner timeout cancels the fetch.
export async function quoteWithBudget(
deps: Deps,
deadline: Deadline,
): Promise<Quote> {
const remaining = deadline.remainingMs();
const owedAfter = 150; // serialization + local work, measured
if (remaining <= owedAfter + MIN_USEFUL) {
throw new BudgetExhaustedError(remaining);
}
const perCall = remaining - owedAfter;
const res = await fetch(deps.pricingUrl, {
signal: AbortSignal.any([
deadline.signal,
AbortSignal.timeout(perCall),
]),
});
if (!res.ok) throw new HttpError(res.status);
return res.json() as Promise<Quote>;
}
export class Deadline {
private constructor(readonly signal: AbortSignal,
private readonly at: number) {}
static in(ms: number) {
return new Deadline(AbortSignal.timeout(ms), Date.now() + ms);
}
remainingMs() { return Math.max(0, this.at - Date.now()); }
}
The owed-after term is the part most implementations skip: the per-call timeout is not the remaining budget, it is the remaining budget minus everything that must still happen after the call returns, response serialization, subsequent calls, and a safety margin. Measure the owed work rather than guessing it, and revisit the measurement when payloads change, because a serialization step that grows from 50 to 500 milliseconds silently invalidates every derived timeout above it.
Retries inside the budget
Retries and budgets interact destructively when treated independently: a retry loop with its own attempt limit re-spends time the budget already spent, and the classic failure is a caller whose deadline expired two seconds ago faithfully executing attempt three of four. The rule is that retries draw from the same budget as everything else: before each attempt, compute the remaining time, and if it cannot cover the attempt plus the still-owed work, stop and surface the budget-exhausted error rather than the last attempt’s error. This changes the retry loop’s termination condition from attempts taken to time remaining, which is the caller-correct currency: three attempts at five seconds each exceeds most budgets, while the same three attempts at 700 milliseconds each fits comfortably. The jittered backoff delay also counts against the budget, which caps effective retry counts automatically under tight deadlines, fast-failing exactly when the system is too loaded for retries to help. A retry loop that ignores the deadline is a loop that optimizes for its own completion rather than the caller’s, and the difference shows up as p99 latency that no per-layer timeout table can explain.
Queues and the budget start time
A queued unit of work has a subtlety: the budget should start when the user’s request arrived, not when the worker picked it up, or a busy queue quietly resets every deadline and downstream calls receive a fresh budget for work that is already stale. Carry the arrival timestamp, or the absolute deadline itself, in the queued message, and have the worker reconstruct the deadline from it, failing fast on messages whose budgets expired in the queue. This is the difference between a queue as backpressure, where long queue waits translate into honest failures, and a queue as latency laundering, where waits disappear from every metric while users experience them anyway. The same principle applies to handoffs across process boundaries: an RPC deadline should propagate through to the callee, which gRPC does natively with its deadline header, so the callee’s internal calls derive from the same absolute clock rather than restarting their own. What must never happen is a middle tier that accepts a deadline, ignores it, and enforces its own, which severs the composition exactly where it matters most, the boundary between teams.
Test budget exhaustion
Budget logic fails silently, every layer still works, the composition just stops adding up, so tests must target the arithmetic directly. Composition test: with a 1-second total budget and a dependency that hangs, assert the entry point fails within 1 second plus a small margin, not within the sum of internal timeouts. Derivation test: with 800 milliseconds remaining and 200 milliseconds owed after a call, assert the call receives a 600-millisecond timeout, by observing when a hanging call is aborted. Retry containment: with a budget that fits one attempt, assert a failing dependency produces one attempt and a budget-exhausted error, not attempt two. Queue staleness: enqueue a message whose deadline expired, assert the worker fails it immediately without calling dependencies. Fail-fast: with less remaining time than the owed-after work, assert no network call is made at all. These are timing tests, so use fake clocks or generous margins, and run them on every change to the timeout derivation code, because that code is small, pure, and exactly where an innocent-looking refactor breaks the arithmetic the whole system depends on.
it('fails within the entry budget, not the sum', async () => {
const hanging = () => new Promise(() => {});
const start = Date.now();
await expect(
handle(hangingDeps, Deadline.in(1000)),
).rejects.toBeInstanceOf(BudgetExhaustedError);
expect(Date.now() - start).toBeLessThan(1300);
});
Common pitfalls
- Static per-layer tables. Each number looks sane in isolation; the composition overruns or aborts useful work, and nobody owns the total.
- Timeouts equal to the remaining budget. The call leaves nothing for serialization and later work; subtract what is still owed.
- Retries with their own currency. Attempt counts re-spend spent time; terminate on time remaining, not attempts taken.
- Queues that reset deadlines. A fresh budget per pickup launders queue latency out of every metric while users feel it fully.
- **Context accepted but ignored. ** A ctx parameter with constant timeouts has the signature of budgeting without the semantics.
- **No budget-exhausted distinction. ** A caller cannot distinguish hopeless from broken; surface budget errors as their own class so monitors see overload separately from faults.
Conclusion
Timeout composition is arithmetic that someone must own, and the budget model makes the ownership explicit: one deadline at the entry point, derived from the caller’s real patience, propagated through context or signals, from which every per-call timeout is computed as remaining time minus still-owed work. Fail fast when the remainder cannot cover the next call, count retries and their backoff delays against the same budget, and carry absolute deadlines through queues and RPC boundaries so staleness is honest rather than laundered. Distinguish budget exhaustion from ordinary failure in errors and metrics, because overload and faults deserve different responses. Then test the arithmetic directly, entry-budget containment, derivation values, retry termination, queue staleness, with fake clocks, since the code is small and pure and the property it protects, that the whole respects the patience of the part that started it, is invisible until it is gone.
Sources: gRPC: deadlines and cancellation, Go: context package, MDN: AbortSignal.timeout.
FAQ
- Why are per-layer static timeouts wrong?
- Layers add up: a 5-second handler calling three 3-second dependencies can hold a connection for 14 seconds while every individual timeout looks reasonable. Static numbers optimize each layer in isolation and the composition in no one’s favor.
- What is the difference between a timeout and a deadline?
- A timeout is a duration for one operation. A deadline is an absolute point in time for the whole unit of work. Timeouts should be derived from the remaining time to the deadline, which is why budgets compose and constant tables do not.
- What timeout should the innermost call get?
- The remaining budget minus the time still owed after the call: response serialization, remaining local work, and a safety margin. If that computes to zero or less, fail fast now instead of starting a call that cannot finish in time.
Report a problem with this articleOpens a pre-filled issue on GitHub.