A gateway gives a request two seconds. The downstream service gives its database two seconds, and its HTTP client another two seconds. When the gateway times out, those operations may still be running. During an incident, this invisible work competes with fresh requests, turning a slow dependency into a wider outage.
1. Give the request one budget
A timeout constrains one operation; a deadline constrains an entire request. Establish the deadline at a trusted ingress, cap it according to the endpoint's latency objective, and forward it only to trusted internal services. Each service derives its remaining budget and subtracts a small reserve for returning a response. Never let an incoming header extend the local maximum. Absolute timestamps require reasonably synchronized clocks; a clock skew allowance should be part of the policy.
const LOCAL_MAX_MS = 2000;
const RESPONSE_RESERVE_MS = 100;
function deadlineFromHeader(raw: string | undefined) {
const local = Date.now() + LOCAL_MAX_MS;
if (!raw || !/^\d{1,15}$/.test(raw)) return local;
const incoming = Number(raw);
return Number.isSafeInteger(incoming)
? Math.min(local, incoming)
: local;
}
Strip externally supplied deadline headers at the public boundary. For elapsed-time measurements inside a process, prefer a monotonic clock such as performance.now(). Do not assume the wall clock is monotonic.
2. Connect cancellation to actual I/O
Node.js exposes standard abort signals that can be composed and passed to fetch. Combine the caller's disconnect signal with a deadline signal. A controller alone does nothing unless the operation observes its signal.
async function loadProfile(
id: string,
deadline: number,
disconnected: AbortSignal
) {
const remaining = deadline - Date.now() - 100;
if (remaining <= 0) throw new Error('budget exhausted');
const signal = AbortSignal.any([
disconnected,
AbortSignal.timeout(remaining)
]);
const response = await fetch(
'https://profiles.internal/users/' +
encodeURIComponent(id),
{
signal,
headers: {
'x-request-deadline-ms': String(deadline)
}
}
);
if (!response.ok) {
await response.body?.cancel();
throw new Error('profile lookup failed');
}
return response.json();
}
For a Node HTTP server, a response closing before writableFinished can trigger the disconnect controller; remove listeners when the request completes. Keep the signal alive through response body consumption. Map deadline expiration, caller cancellation, and dependency failures separately at the API boundary. A timeout does not establish that a remote write was rolled back.
3. Bound database work independently
Budget pool acquisition and statement execution separately. PostgreSQL statement_timeout bounds individual statements, not the complete transaction. Set transaction-local limits with set_config inside a transaction when appropriate, and recompute the available budget before subsequent statements. Always roll back failed transactions and release clients. A driver that cannot cancel pool acquisition safely needs explicit bounded admission before the pool; racing a checkout promise can leak a client if it resolves later.
4. Spend retries like money
Retry only transient failures on operations that are safe to repeat. Before sleeping, check whether the backoff plus a realistic attempt duration fits the remaining deadline. Use bounded exponential backoff with jitter, and honor Retry-After when it fits. Avoid retries at every layer: three attempts at each of three layers can produce 27 leaf attempts for one incoming request.
For writes, use stable operation identities and durable idempotency. If the request times out after a database commit, the result is ambiguous to the caller, not necessarily a failure on the server. Background work needs its own durable job lifecycle and deadline rather than inheriting an already expired HTTP request budget.
5. Observe the budget, not only the error rate
- Record remaining budget at ingress and dependency dispatch using histograms.
- Separate deadline exhaustion before dispatch, local cancellation, remote timeout, and overload rejection.
- Track in-flight requests, queue wait, dependency latency, retry attempts and work continuing after disconnect.
- Use traces to locate the service that consumed the budget. Keep request IDs in traces or logs, not high-cardinality metric labels.
6. Test the failure path
Inject a slow downstream response and a slow response body separately. Disconnect the client mid-request. Saturate the database pool and verify that late acquisition cannot leak clients. Introduce clock skew in a disposable environment and confirm that no service extends the allowed deadline. Finally, load test with retryable failures and verify that completed throughput recovers after the dependency returns.