ResilienceC# · TypeScript

Timeout

Give every remote call a deadline so a slow dependency costs a bounded amount of time and resources instead of hanging the caller.

On this page
  1. Problem
  2. Context
  3. Solution
  4. Implementation
  5. Trade-offs
  6. Alternatives
  7. Anti-patterns
  8. Related lessons
  9. Interview questions

Problem

A dependency that fails fast is easy to handle. A dependency that becomes slow is far more dangerous: requests to it neither succeed nor fail, they just wait. Every waiting request holds a thread, a connection-pool slot, memory and often a database transaction. Once the pool is full, requests that have nothing to do with the slow dependency start waiting too.

Many client libraries default to very long or infinite timeouts. HttpClient in .NET defaults to 100 seconds; many database drivers wait indefinitely for a query. A user abandons the page after a few seconds, but the server keeps working on the request for minutes, and the retries the user triggers by refreshing pile on top.

Context

Use this pattern when:

  • The service calls anything over a network: HTTP APIs, databases, caches, queues, DNS.
  • Callers have a latency expectation, such as a user-facing SLO of 500 ms at P99.
  • Resources such as threads, connections and memory are finite and shared between requests.
  • Calls fan out through several services, so the time budget must be split along the chain.

Solution

Set an explicit timeout on every remote call, based on the dependency's measured latency rather than a guess: a value slightly above its P99 (or P99.9) catches genuine hangs without cutting off normal slow requests. Distinguish connection timeouts (short, typically a few hundred milliseconds) from request or read timeouts.

Treat the user request as having a deadline and propagate it. Each hop computes the time remaining and passes a shorter deadline downstream, so a backend never keeps working on a request whose caller has already given up. gRPC propagates deadlines natively; with HTTP, pass a header or a cancellation token through the call chain.

When a timeout fires, cancel the underlying work (abort the socket, cancel the query) instead of only abandoning the result, then fall back, fail fast or let a retry policy decide what happens next.

How it works, step by step

  1. 1Measure the dependency's latency distribution and choose a timeout above its normal tail.
  2. 2Start a timer (or create a cancellation token / abort signal) when the call begins.
  3. 3Pass the token to the client so it can cancel the socket or query, not just stop waiting.
  4. 4If the timer fires first, cancel the call and raise a timeout error the caller can classify.
  5. 5Downstream calls receive the remaining time budget, never a fresh full timeout.

Implementation

Both platforms have first-class cancellation: CancellationToken in .NET and AbortSignal in JavaScript. The examples show a per-call timeout combined with an overall request deadline.

C#Linked cancellation tokens for per-call and request deadlines
public sealed class PricingClient(HttpClient http)
{
    private static readonly TimeSpan CallTimeout = TimeSpan.FromMilliseconds(800);

    // requestAborted comes from the incoming request (HttpContext.RequestAborted),
    // so the call also stops when the user disconnects.
    public async Task<decimal?> GetPriceAsync(string sku, CancellationToken requestAborted)
    {
        using var cts = CancellationTokenSource.CreateLinkedTokenSource(requestAborted);
        cts.CancelAfter(CallTimeout);

        try
        {
            using var response = await http.GetAsync($"/prices/{sku}", cts.Token);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadFromJsonAsync<decimal>(cts.Token);
        }
        catch (OperationCanceledException) when (!requestAborted.IsCancellationRequested)
        {
            // Our own deadline fired: degrade instead of failing the whole page.
            return null;
        }
    }
}

// Registration: keep HttpClient.Timeout as a safety net above the per-call value.
builder.Services.AddHttpClient<PricingClient>(client =>
{
    client.BaseAddress = new Uri("https://pricing.internal");
    client.Timeout = TimeSpan.FromSeconds(5);
});

The when filter separates "our timeout fired" from "the client went away"; in the second case there is nobody left to answer, so the exception should propagate.

TypeScriptfetch with a per-call timeout and a propagated deadline
export class TimeoutError extends Error {}

/** Remaining time until an absolute deadline (epoch ms), never below zero. */
const remaining = (deadline: number) => Math.max(0, deadline - Date.now());

export async function getJson<T>(url: string, options: { timeoutMs: number; deadline?: number; signal?: AbortSignal }): Promise<T> {
  const budget = options.deadline === undefined ? options.timeoutMs : Math.min(options.timeoutMs, remaining(options.deadline));
  if (budget === 0) throw new TimeoutError('deadline already passed');

  const signals = [AbortSignal.timeout(budget)];
  if (options.signal) signals.push(options.signal);

  try {
    const response = await fetch(url, {
      signal: AbortSignal.any(signals),
      // Tell the next hop how long it has (it subtracts its own overhead).
      headers: { 'x-request-deadline': String(Date.now() + budget) },
    });
    if (!response.ok) throw new Error('HTTP ' + response.status);
    return (await response.json()) as T;
  } catch (error) {
    if (error instanceof DOMException && error.name === 'TimeoutError') {
      throw new TimeoutError(url + ' timed out after ' + budget + ' ms');
    }
    throw error;
  }
}

// In a request handler: one deadline for the whole request, shared by every call.
export async function handleProductPage(id: string) {
  const deadline = Date.now() + 1_500;
  const [product, reviews] = await Promise.all([
    getJson<{ name: string }>('https://catalog.internal/products/' + id, { timeoutMs: 800, deadline }),
    getJson<unknown[]>('https://reviews.internal/products/' + id, { timeoutMs: 500, deadline }).catch(() => []),
  ]);
  return { product, reviews };
}

AbortSignal.timeout and AbortSignal.any are available in Node 20+ and modern browsers. Aborting the signal closes the underlying connection, so the server stops waiting on it.

In production

  • Derive timeouts from measured percentiles and revisit them when the dependency's latency profile changes.
  • Set connection, request and overall timeouts separately; a connect timeout of a few seconds is almost always a sign of trouble.
  • Database queries need their own limit (statement_timeout in PostgreSQL, CommandTimeout in ADO.NET), because a cancelled HTTP request does not stop a running query by itself.
  • With retries, the per-attempt timeout times the attempt count must fit inside the overall deadline.
  • Record timeouts as a distinct metric; a rise in timeouts is an early signal of saturation that error rates alone miss.

Trade-offs

Benefits

  • Bounds the time and resources any single call can consume.
  • Prevents a slow dependency from exhausting thread and connection pools shared by healthy code paths.
  • Turns hangs into explicit errors that retries, breakers and fallbacks can act on.
  • Deadline propagation stops wasted work on requests nobody is waiting for.

Costs

  • A timeout that is too short fails requests that would have succeeded, especially during GC pauses or cold starts.
  • A timed-out write has an unknown outcome: it may still complete on the server, so it needs idempotency to be retried safely.
  • Choosing values requires latency data per dependency and periodic review.

Alternatives

Asynchronous processing
Accept the request, return 202 Accepted and do the slow work in the background, so the caller never waits on the dependency at all.
Bulkhead
Limit how many concurrent calls can wait on one dependency; complements timeouts by capping the blast radius when many calls are slow at once.
Hedged requests
Instead of waiting for a slow replica, send a second request elsewhere after a short delay; useful for idempotent reads with long tails.

Anti-patterns

Relying on library defaults
Defaults such as 100 seconds or infinite waits are far longer than any user will wait and let pools drain silently.
Fresh full timeouts at every hop
If every service in a five-hop chain waits up to 2 seconds, the caller can wait 10 seconds; downstream hops should get the remaining budget.
Abandoning without cancelling
Returning an error while the underlying query or socket keeps running still consumes the resources the timeout was meant to protect.
Retrying timed-out non-idempotent writes
The first attempt may have succeeded; retrying without an idempotency key can duplicate orders or payments.

Interview questions

How do you choose a timeout value for a dependency?

Start from its measured latency distribution and set the timeout a little above the tail you consider normal, often around P99 or P99.9, then check it fits the caller's own latency budget. If the dependency's normal tail does not fit the budget, the problem is the dependency or the design, not the timeout.

What is deadline propagation and why does it matter?

Each hop passes the absolute deadline (or remaining budget) of the original request downstream, so deeper services know how much time is left. Without it, a backend keeps working on a request the user abandoned long ago, wasting capacity during exactly the overloads where capacity matters most.

A request to create an order timed out. What do you know about whether the order exists?

Nothing: the server may have rejected it, still be processing it, or have committed it after the client gave up. The safe approach is to retry with the same idempotency key or query the order status before deciding.

Why can a slow dependency be worse than a dead one?

A dead dependency fails immediately, so callers spend almost nothing on it. A slow one holds threads and connections for the full timeout on every call, which can exhaust shared pools and take down unrelated features of the calling service.