Bound how long any request can consume resources. Every remote call gets a timeout derived from the time remaining in the original request, not a fixed number per hop. That remaining budget travels with the request, so every downstream service can stop early, skip doomed work and release what it holds.
A timeout is the most basic resilience control you have, and the one most often missing. Without it, a slow dependency does more than slow you down. It holds your sockets, threads and memory, then takes down services that were otherwise healthy. This guide follows one invented incident at a ticketing company. It covers two layers. The first is putting a deadline on every outbound call. The second is propagating a single request budget across services so each hop knows how much time is actually left. Interviewers probe the second layer. Saying "I'd add a timeout" is expected. Explaining why per-hop timeouts that add up to more than the caller's patience are still broken is what sets you apart.
The problem
A situation where the obvious design starts to hurt.
Encore Tickets sells concert tickets. Its checkout service, turnstile, runs on 24 pods and peaks around 1,800 checkout requests per second during a stadium on-sale. Each checkout calls four things in sequence. It calls seat-hold to reserve seats for 10 minutes and pricing to compute fees. It calls RiskLens, an external fraud-scoring vendor. Finally it calls the payments gateway.
During one on-sale, RiskLens p99 latency went from 180ms to between 20 and 30 seconds. Turnstile's HTTP client had been created with no timeout. Each pod had an outbound pool of 64 sockets, and those filled in under a second. New checkouts queued behind them, including ones that would never reach RiskLens because seat-hold calls waited for the same pool. The mobile app gave up after 8 seconds and retried twice, which tripled the incoming load. Seat-hold kept reserving seats for requests that no user would ever complete, so inventory looked sold out while real buyers saw errors. The on-sale was degraded for about 40 minutes.
The first fix was a 5-second timeout on every outbound call. It stopped the pool exhaustion but left a subtler bug. Four sequential calls at 5 seconds each can take 20 seconds, while the app abandons the request at 8. Turnstile still did up to 12 seconds of work nobody was waiting for. Seat-hold had its own 5-second database timeout, which also had nothing to do with how long the user would wait. Each service picked a reasonable number on its own, and together the numbers were wrong.
The solution
What the pattern proposes.
Treat time as a budget owned by the request, not a setting owned by each client library.
The edge gateway sets the budget once. The app waits 8 seconds, so the gateway allows 7,500ms and keeps 500ms for the network and rendering an error. It forwards the budget in a header, x-deadline-ms, as remaining milliseconds. Turnstile reads the header and converts it to a local deadline on a monotonic clock. Before each outbound call it computes timeout = min(per-call cap, remaining - reserve). The per-call cap reflects how slow that dependency can reasonably be. Seat-hold p99.9 is about 240ms, so its cap is 800ms. RiskLens gets 1,500ms and payments 3,000ms. If what remains is below a minimum useful amount, around 20ms, turnstile fails fast with a 504 instead of starting a call that cannot finish.
Every outbound request carries its own timeout in x-deadline-ms. Downstream services apply the same rule. Seat-hold checks the deadline before taking a hold and sets the Postgres statement_timeout for that transaction from the remaining budget. When the deadline fires, the caller cancels the in-flight request so the socket goes back to the pool. Holds created for abandoned requests are released by an expiry message instead of sitting for 10 minutes.
When RiskLens hangs now, the checkout fails or takes a fallback within 1.5 seconds. Turnstile's sockets are back in the pool within that window, and no service keeps working past the moment the app stops listening.
An everyday analogy
The same idea, outside software.
Picture a film crew with a hard stop at 6pm because the location permit expires. The producer does not tell each department to take as long as it needs, or even "two hours each". She tells them the shoot wraps at 6 and that lighting cannot take more than 90 minutes of it.
At 5:40, a lighting tech who needs 45 minutes does not start the setup. That is a fail-fast. When the permit runs out, everyone stops, including the people renting equipment by the hour. The fixed end time is the deadline. The 90-minute limit is the per-call cap. Packing up at 6 is cancellation.
Structure
The pieces and how they relate.
Participants
- Edge gateway
- Owns the root budget. It sets the deadline from the slowest client's patience minus a margin (8s minus 500ms). It also clamps any deadline header a client sends, so callers cannot ask for unlimited time.
- Deadline object
- In-process value holding an expiry instant on a monotonic clock. It answers two questions: how much time remains, and what timeout to give the next call, given a cap and a reserve.
- Outbound call wrapper
- The only path to the network. It computes the per-call timeout, writes it into x-deadline-ms, attaches a cancellation signal and maps a timeout to a typed DeadlineExceeded error.
- Per-call caps
- Configuration per dependency, based on its measured tail latency (for example 3x its p99.9). The cap stops one slow dependency from using the whole budget when the deadline is still far away.
- Downstream services
- Read the incoming header, rebuild a local deadline and enforce it in turn: on their own outbound calls, on database statement timeouts and with fail-fast checks before expensive steps.
- Compensation path
- Cleans up side effects of requests that timed out after doing partial work. Here, the hold-release queue frees seats held for a checkout that never completed.
Pseudocode
The solution to the scenario, language-neutral.
HEADER = "x-deadline-ms"
class Deadline:
expiresAt # monotonic clock instant
static fromHeader(raw, defaultMs, maxMs):
budget = parsePositiveNumber(raw)
if budget is missing: budget = defaultMs
return Deadline(now() + min(budget, maxMs))
remainingMs():
return max(0, expiresAt - now())
budgetFor(operation, capMs, reserveMs = 50, minUsefulMs = 20):
available = remainingMs() - reserveMs
if available < minUsefulMs:
raise DeadlineExceeded(operation) # fail fast, do not start doomed work
return floor(min(capMs, available))
callWithDeadline(deadline, operation, request, capMs):
timeoutMs = deadline.budgetFor(operation, capMs)
request.headers[HEADER] = timeoutMs # downstream sees what is left for it
try:
return send(request, totalTimeout = timeoutMs, cancelOnTimeout = true)
on timeout:
raise DeadlineExceeded(operation)
# turnstile checkout handler
handleCheckout(req):
deadline = Deadline.fromHeader(req.headers[HEADER], 7500, 7500)
try:
hold = callWithDeadline(deadline, "seat-hold", holdRequest, 800)
price = callWithDeadline(deadline, "pricing", priceRequest, 400)
risk = callWithDeadline(deadline, "risklens", riskRequest, 1500)
pay = callWithDeadline(deadline, "payments", payRequest, 3000)
return 200
on DeadlineExceeded:
enqueue(holdRelease(hold.id)) if hold exists
return 504
# seat-hold service
handleHold(req):
deadline = Deadline.fromHeader(req.headers[HEADER], 800, 800)
stmtMs = deadline.budgetFor("hold-tx", 600)
db.transaction:
exec("SET LOCAL statement_timeout = " + stmtMs)
insert hold ...The code
The same solution in TypeScript, Python and PHP.
// Node 18+: global fetch, AbortSignal.timeout and performance.now are built in.
const HEADER = "x-deadline-ms";
export class DeadlineExceeded extends Error {
constructor(public readonly operation: string) {
super(`deadline exceeded before or during ${operation}`);
this.name = "DeadlineExceeded";
}
}
export class Deadline {
private constructor(private readonly expiresAt: number) {}
static within(ms: number): Deadline {
return new Deadline(performance.now() + ms);
}
// Rebuild a local deadline from the incoming header, clamped to this service's maximum.
static fromHeader(raw: string | null, defaultMs: number, maxMs: number): Deadline {
const value = Number(raw);
const budget = Number.isFinite(value) && value > 0 ? Math.min(value, maxMs) : defaultMs;
return Deadline.within(budget);
}
remainingMs(): number {
return Math.max(0, this.expiresAt - performance.now());
}
// Timeout for one call: never above the cap, never past the deadline minus a reserve.
budgetFor(operation: string, capMs: number, reserveMs = 50, minUsefulMs = 20): number {
const available = this.remainingMs() - reserveMs;
if (available < minUsefulMs) throw new DeadlineExceeded(operation);
return Math.floor(Math.min(capMs, available));
}
}
export async function callWithDeadline(
deadline: Deadline,
operation: string,
url: string,
capMs: number,
init: RequestInit = {},
): Promise<Response> {
const timeoutMs = deadline.budgetFor(operation, capMs);
const headers = new Headers(init.headers);
headers.set(HEADER, String(timeoutMs));
try {
// The signal aborts the socket on expiry, so the connection returns to the pool.
return await fetch(url, { ...init, headers, signal: AbortSignal.timeout(timeoutMs) });
} catch (err) {
if (err instanceof Error && err.name === "TimeoutError") throw new DeadlineExceeded(operation);
throw err;
}
}
// Usage inside turnstile's checkout handler.
export async function holdSeats(incoming: Headers, body: string): Promise<Response> {
const deadline = Deadline.fromHeader(incoming.get(HEADER), 7_500, 7_500);
try {
return await callWithDeadline(deadline, "seat-hold", "http://seat-hold.internal/holds", 800, {
method: "POST",
body,
headers: { "content-type": "application/json" },
});
} catch (err) {
if (err instanceof DeadlineExceeded) return new Response(err.message, { status: 504 });
throw err;
}
}# Python 3.11+ (asyncio.timeout) with httpx.
import asyncio
import math
import time
from typing import Any
import httpx
HEADER = "x-deadline-ms"
class DeadlineExceeded(Exception):
def __init__(self, operation: str) -> None:
super().__init__(f"deadline exceeded before or during {operation}")
self.operation = operation
class Deadline:
def __init__(self, expires_at: float) -> None:
self._expires_at = expires_at # time.monotonic() seconds
@classmethod
def within(cls, ms: float) -> "Deadline":
return cls(time.monotonic() + ms / 1000)
@classmethod
def from_header(cls, raw: str | None, default_ms: float, max_ms: float) -> "Deadline":
try:
value = float(raw) if raw is not None else 0.0
except ValueError:
value = 0.0
budget = min(value, max_ms) if math.isfinite(value) and value > 0 else default_ms
return cls.within(budget)
def remaining_ms(self) -> float:
return max(0.0, (self._expires_at - time.monotonic()) * 1000)
def budget_for(self, operation: str, cap_ms: float,
reserve_ms: float = 50, min_useful_ms: float = 20) -> int:
available = self.remaining_ms() - reserve_ms
if available < min_useful_ms:
raise DeadlineExceeded(operation)
return int(min(cap_ms, available))
async def call_with_deadline(client: httpx.AsyncClient, deadline: Deadline, operation: str,
url: str, cap_ms: float, method: str = "GET",
**kwargs: Any) -> httpx.Response:
timeout_ms = deadline.budget_for(operation, cap_ms)
headers = {**kwargs.pop("headers", {}), HEADER: str(timeout_ms)}
try:
# Total timeout over connect, send and full body read; cancels the request on expiry.
async with asyncio.timeout(timeout_ms / 1000):
return await client.request(method, url, headers=headers, **kwargs)
except TimeoutError as exc:
raise DeadlineExceeded(operation) from exc
async def hold_seats(incoming_header: str | None, body: bytes) -> int:
deadline = Deadline.from_header(incoming_header, 7500, 7500)
# timeout=None: the deadline, not httpx's per-phase 5s default, governs.
async with httpx.AsyncClient(timeout=None) as client:
try:
resp = await call_with_deadline(
client, deadline, "seat-hold", "http://seat-hold.internal/holds", 800,
method="POST", content=body,
headers={"content-type": "application/json"},
)
return resp.status_code
except DeadlineExceeded:
return 504<?php
declare(strict_types=1);
// PHP 8.1+, Guzzle 7 (composer require guzzlehttp/guzzle).
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use Psr\Http\Message\ResponseInterface;
final class DeadlineExceeded extends RuntimeException
{
public function __construct(public readonly string $operation, ?Throwable $previous = null)
{
parent::__construct("deadline exceeded before or during {$operation}", 0, $previous);
}
}
final class Deadline
{
public const HEADER = 'x-deadline-ms';
private function __construct(private readonly int $expiresAtNs) {}
public static function within(int $ms): self
{
return new self(hrtime(true) + $ms * 1_000_000); // monotonic nanoseconds
}
public static function fromHeader(?string $raw, int $defaultMs, int $maxMs): self
{
$value = is_numeric($raw) ? (int) $raw : 0;
return self::within($value > 0 ? min($value, $maxMs) : $defaultMs);
}
public function remainingMs(): int
{
return max(0, intdiv($this->expiresAtNs - hrtime(true), 1_000_000));
}
public function budgetFor(string $operation, int $capMs, int $reserveMs = 50, int $minUsefulMs = 20): int
{
$available = $this->remainingMs() - $reserveMs;
if ($available < $minUsefulMs) {
throw new DeadlineExceeded($operation);
}
return min($capMs, $available);
}
}
function callWithDeadline(
Client $client,
Deadline $deadline,
string $operation,
string $uri,
int $capMs,
string $method = 'GET',
array $options = [],
): ResponseInterface {
$timeoutMs = $deadline->budgetFor($operation, $capMs);
$options['headers'][Deadline::HEADER] = (string) $timeoutMs;
$options['timeout'] = $timeoutMs / 1000; // total transfer time, enforced by cURL
try {
return $client->request($method, $uri, $options);
} catch (ConnectException $e) {
// cURL errno 28 is CURLE_OPERATION_TIMEDOUT.
if (($e->getHandlerContext()['errno'] ?? null) === 28) {
throw new DeadlineExceeded($operation, $e);
}
throw $e;
}
}
function holdSeats(?string $incomingHeader, string $body): int
{
$deadline = Deadline::fromHeader($incomingHeader, 7500, 7500);
$client = new Client(['http_errors' => false]);
try {
$response = callWithDeadline(
$client, $deadline, 'seat-hold', 'http://seat-hold.internal/holds', 800, 'POST',
['body' => $body, 'headers' => ['content-type' => 'application/json']],
);
return $response->getStatusCode();
} catch (DeadlineExceeded) {
return 504;
}
}When to use it
Situations where it pays off.
Any synchronous call to another process: HTTP, gRPC, database, cache or message-broker publish.
A call without a bound can hold a socket, a thread or a pool slot forever. A pool of 64 sockets drains in under a second at 1,800 rps once one dependency stops answering.
Request paths that fan out or chain through two or more services.
Independent per-hop timeouts add up. Only a shared, shrinking budget guarantees the whole chain finishes before the original caller gives up.
The caller has a hard patience limit you know: a mobile app timeout, a load balancer idle timeout, a user-facing SLA.
Work done after the caller has gone is pure waste. Deriving the budget from that limit turns it into fail-fast behaviour and frees capacity during incidents.
Requests create side effects, such as holds, locks or reservations, that are expensive to leave dangling.
Checking the deadline before taking the side effect avoids most orphans. Pairing that with a release path cleans up the few that slip through.
Calls to external vendors whose latency you do not control.
A per-call cap keeps a degraded vendor from consuming the whole budget, so your fallback has time to run and the rest of the request can still succeed.
How to implement it
Steps to introduce it in existing code.
Find the outermost patience limit, usually the client timeout or the load balancer timeout. Set the root budget a margin below it, for example 7,500ms for an 8s app timeout.
Create a Deadline at the edge on a monotonic clock. Accept an incoming deadline header only after clamping it to your own maximum.
Route every outbound call through one wrapper. It computes min(cap, remaining - reserve), sets the transport's total timeout to that value, writes it into the outgoing header and cancels on expiry.
Set per-dependency caps from measured tail latency, not guesses. Something like 2 to 4 times p99.9 is a sensible starting point. Review the caps whenever a dependency's SLO changes.
In each downstream service, rebuild the deadline from the header. Apply it to database statement timeouts, lock waits and its own outbound calls.
Add fail-fast checks before expensive or side-effecting steps. Return a distinct status (504 or DEADLINE_EXCEEDED) so callers and dashboards can tell budget exhaustion apart from errors.
Give partial side effects a cleanup path, such as an expiry or a release message, because a timeout does not tell the caller whether the callee committed.
Emit metrics: deadline-exceeded count per operation, remaining budget at each hop and calls skipped by fail-fast. Alert when one dependency regularly uses most of its cap.
Pros and cons
What you gain and what you pay.
Pros
- Bounds resource use per request, so a hung dependency costs at most its cap in socket and thread time instead of draining the pool.
- The whole chain finishes before the original caller gives up, so no service burns capacity on abandoned requests.
- Fail-fast at low remaining budget sheds load automatically during incidents. It is the cheapest form of load shedding you can add.
- A single header and wrapper make timeout behaviour visible and consistent instead of scattered across client library defaults.
Cons
- Every service in the path must honour the header. One service that ignores it breaks the guarantee for everything below it.
- Caps that are too tight turn normal tail latency into errors. Picking good values needs latency data you may not have yet.
- A timeout does not tell you whether the remote side completed the work, so you need idempotency or compensation for side-effecting calls.
- Relative budgets ignore network transit time and absolute ones depend on synchronised clocks, so either way you need a reserve margin.
Trade-offs
Decisions you'll have to make, each with its price.
Root budget of 7,500ms against an 8s app timeout instead of using the full 8s
You gainTurnstile returns a clean 504 with an error body the app can show, instead of the app timing out with no information.
You pay500ms less time for the happy path, and the margin must be revisited whenever the app's timeout changes.
Fail fast when less than 20ms remains
You gainNo socket, thread or downstream work is spent on calls that cannot finish, which sheds load automatically during slowdowns.
You payA small number of requests that might have just made it are rejected. Set the floor below the dependency's p50 latency, or you will reject healthy traffic.
RiskLens cap of 1,500ms with a fallback rule for orders under a set value
You gainA vendor outage degrades fraud checks instead of blocking sales, and leaves about 3 seconds for payments.
You payOrders accepted on the fallback carry more fraud risk and need a post-purchase review queue that someone has to staff.
Seat-hold sets Postgres statement_timeout per transaction from the remaining budget instead of a global 5s
You gainSlow queries are cancelled exactly when they become useless, which frees connections in the 20-connection pool sooner.
You payAn extra SET LOCAL round trip per transaction, and statement timeouts can now differ from request to request, which makes slow-query logs harder to read.
Propagating remaining budget instead of letting each team choose its own timeouts
You gainEnd-to-end latency is bounded by construction, whatever the depth of the call chain.
You payEvery service and client library must adopt the header and wrapper. Services that skip it become gaps the guarantee cannot cross.
How it fails
What goes wrong in production and how to prevent it.
Retries ignore the deadline: three attempts of 800ms each are scheduled with only 1,000ms left.
What to doAsk the deadline for budget before every attempt, including backoff sleeps. Stop retrying once budgetFor throws, and put a retry budget at the edge, for example retries capped at 10% of requests.
The caller times out but the callee keeps working, creating seat holds nobody will pay for.
What to doCancel the request on timeout so the callee sees the connection close. Check the deadline in the callee before side effects. Emit a release message with the hold's expiry so orphaned holds are freed within seconds, not 10 minutes.
A client sends x-deadline-ms: 600000 and ties up resources for 10 minutes.
What to doClamp incoming budgets to the service's own maximum (7,500ms at turnstile). At the public edge, ignore client-supplied deadlines entirely and set the root budget yourself.
Time spent waiting for a connection from the pool is not counted, so a call with a 400ms timeout takes 2s end to end.
What to doStart the timer before acquiring the connection, or set the pool's acquire timeout from the same budget. Track pool wait time as its own metric so saturation shows up before deadlines start failing.
A timeout on a payments call is treated as a failure, the user retries and gets charged twice.
What to doSend an idempotency key with every payment request. On timeout, mark the payment as unknown and resolve it with a status lookup using the same key, instead of reporting a failure.
Caps are set from averages, so normal tail latency trips them and the 504 rate jumps during busy periods.
What to doDerive caps from p99.9 under peak load, review them monthly and alert when a dependency's p99 exceeds half its cap. That gives you warning before timeouts start firing.
In a system design interview
When to bring it up and how to explain it.
Raise it whenever you draw a synchronous call between services, especially a chain of three or more, or a call to a third party. Bring it up again when the interviewer asks what happens when a dependency gets slow, or how you'd keep one bad service from taking down the rest.
What you could say
Every remote call in this design gets a timeout, but I don't pick a number per hop, because per-hop timeouts add up. If checkout calls four services sequentially with a 5-second timeout each, the chain can take 20 seconds while the app gives up at 8. So I set one budget at the edge, say 7.5 seconds, a little under the client's timeout, and propagate the remaining milliseconds in a header, the way gRPC does with grpc-timeout. Each service turns that into a local deadline on a monotonic clock. For each outbound call it uses the smaller of a per-dependency cap and the remaining time minus a small reserve. The cap comes from the dependency's p99.9, so a slow fraud vendor can't eat the whole budget. If there's almost no time left, I fail fast with a 504 instead of starting work nobody will wait for. Downstream services apply the same deadline to their database statement timeouts. On expiry I cancel the request so the socket goes back to the pool. And since a timeout doesn't tell me whether the other side committed, side-effecting calls carry idempotency keys or have a cleanup path.
Likely follow-ups
How do you choose the per-call caps?
From measured latency under peak load, not averages. I'd start around two to four times the dependency's p99.9 and check that the caps for the sequential calls fit inside the root budget with room to spare. Then I'd alert when p99 reaches half the cap, so I know about drift before users see errors.
How do retries interact with the deadline?
Retries share the same budget. Before each attempt, including the backoff sleep, I ask the deadline how much is left. If it's below the minimum useful time, I stop and return the last error. I'd also cap retries globally at the edge so a slowdown doesn't multiply traffic.
What if a downstream service is owned by another team and ignores the header?
My timeout still protects my own resources, because I enforce it on my side regardless. What I lose is the downstream's cleanup: it may keep working after I've gone. So I'd push the header and wrapper into the shared client library or service mesh, and make deadline handling part of the service-readiness checklist.
Why not just let the circuit breaker handle the slow vendor?
The breaker needs failures to count, and a hung call without a timeout never fails. Timeouts turn slowness into failures. The breaker then stops sending traffic once those failures pass a threshold. I'd use both.
Relations with other guides
Patterns it's often confused or combined with.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Retries must draw from the same deadline. A retry that starts with 30ms left only adds load, so the retry loop should ask the deadline for budget before each attempt and stop when budgetFor throws.
- Circuit breaker: fail fast when a dependency is down
Timeouts are the signal a circuit breaker counts. Without a timeout, a hung dependency never produces a failure, and the breaker never opens.
- Bulkhead: Isolate Resources So One Failure Stays Contained
A timeout bounds how long a slot is held. A bulkhead bounds how many slots one dependency can hold. Together they keep RiskLens from starving seat-hold of sockets.
- Idempotency Keys: Making Retried Writes Safe
A timed-out payment call may or may not have charged the card. An idempotency key lets you retry or reconcile safely.
- Backpressure: Let Slow Consumers Slow Down Fast Producers
Fail-fast on an exhausted deadline is a form of backpressure. It rejects work early instead of queueing it until it is useless.
- Decorator: Add Behaviour by Wrapping, the Way Middleware Does
The outbound call wrapper is naturally a decorator around the HTTP client, adding deadline headers, timeouts and error mapping without changing call sites.
Common questions
Short answers to the usual doubts.
Should the header carry a relative duration or an absolute timestamp?
Relative is safer across machines, and it is what gRPC does with grpc-timeout. The receiver adds it to its own monotonic clock, so clock skew between hosts does not matter. The cost is that network transit time is not counted, so the receiver thinks it has slightly more time than it does. The 50ms reserve covers that. Absolute timestamps are fine inside one host or with tightly synchronised clocks, but a 2-second skew silently gives or takes 2 seconds of budget.
Why keep per-call caps if the deadline already bounds everything?
Early in the request, the deadline is far away. Without a cap, a hung RiskLens call at the start of checkout could use 7 seconds and leave payments with nothing. The cap reflects what is normal for that dependency; the deadline reflects what the caller will tolerate. You need the smaller of the two.
Is the default timeout in my HTTP client good enough?
Often there is no default, or it is long, or it applies per phase. Python's urllib socket timeout restarts on every read, so a server trickling one byte every few seconds never trips it. Set a total timeout explicitly, and check that it covers reading the body, not just receiving headers.
What should the service do when the deadline expires mid-way through its own work?
Stop as soon as it can do so safely, roll back any open transaction and return DEADLINE_EXCEEDED. Do not commit a side effect after the deadline if you can avoid it, because the caller has already given up and will not act on the result. For side effects that did commit, rely on expiry or a release path.
How does this work across a message queue?
Put the absolute expiry time in the message metadata, because queue time counts against it. Consumers drop or dead-letter messages that are already past their deadline instead of processing them. For background jobs with no waiting user, use a separate, longer budget instead of inheriting the user's.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Resilience and high concurrencyTake the test
- A slow or failing external providerSolve the exercise