Network Latency, Timeouts, and Failure

Learn how latency, bandwidth, and jitter shape backend requests, then set useful timeouts, bounded retries, and failure handling without amplifying outages.

published: reading time: 12 min read author: Geek Workbench
Quick Summary

Network calls can outlast a caller or finish after a response is lost, so backend operations need deadlines and per-dependency budgets. This guide explains where bounded retries, jitter, idempotency keys, circuit breakers, and asynchronous queues help, while covering risks such as retry amplification and SSRF from caller-supplied URLs. Use the examples and observability checks to spot tail latency, contain excess load, and handle uncertain outcomes safely.

Network Latency, Timeouts, and Failure

Introduction

A request may cross several services before it returns. Any hop can slow down or disappear, even if the last thousand calls worked. Treat every network call as fallible.

An error alone does not make a retry safe. Check whether the operation can be repeated, then decide how much of the caller’s remaining time to spend on it.

The examples below use one request deadline, bounded retries, idempotency, and circuit breakers to contain failures without adding avoidable load.

What a timeout means

A timeout limits how long the caller waits; it does not prove the server stopped. The server may commit a write whose response was lost. Retrying a payment without an idempotency key can charge twice.

Set timeouts from the caller’s deadline. An API with 1.5 seconds to answer needs shorter downstream budgets, leaving time to validate and respond. Longer timeouts tie up sockets after the caller has left.

When to use retries, and when not to

Retry a transient failure only when repeating the operation is safe. A read is often safe, but check its application side effects rather than relying on the HTTP verb alone. For a write, retry only when the API guarantees deduplication for the same idempotency key and payload. Use exponential backoff and random jitter.

Do not retry validation or authentication errors, most 4xx responses, or writes whose outcome is unknown and cannot be deduplicated. Stop when the deadline cannot fit another attempt. A circuit breaker can stop calls during sustained failures.

Use a circuit breaker when repeated dependency failures waste caller time or add load. One slow response usually calls for enforcing the deadline; it does not tell you that the breaker should open. An asynchronous queue fits work that can finish after the caller receives an accepted or pending response, such as report generation or email delivery. Keep the queue bounded and make consumers safe to retry. A queue is a poor fit when the caller needs the result before it can continue.

Deadlines across nested calls

Give the whole request one deadline, then pass the remaining budget to each dependency. If three sequential calls each get a fresh 700 ms timeout, they can hold the caller for 2.1 seconds before local processing time. A shared deadline caps that wait. Parallel calls share the same deadline too, and work that is no longer needed should be cancelled.

The example uses performance.now() for a monotonic local clock. The x-timeout-ms header is application-specific; use the deadline metadata defined by your RPC protocol or service contract. The receiving service should cap its own work to the value it receives. Because time passes in transit, the caller must still enforce its local deadline.

async function fetchJsonWithBudget(
  url: string,
  budgetMs: number,
  parentSignal: AbortSignal,
): Promise<unknown> {
  if (parentSignal.aborted) {
    throw new DOMException("Caller cancelled", "AbortError");
  }

  const controller = new AbortController();
  let deadlineExceeded = false;
  const cancelFromParent = () => controller.abort(parentSignal.reason);
  parentSignal.addEventListener("abort", cancelFromParent, { once: true });
  const timer = setTimeout(() => {
    deadlineExceeded = true;
    controller.abort();
  }, budgetMs);

  try {
    const response = await fetch(url, {
      headers: { "x-timeout-ms": String(budgetMs) },
      signal: controller.signal,
    });
    if (!response.ok) throw new Error(`Downstream returned ${response.status}`);
    return await response.json();
  } catch (error) {
    if (parentSignal.aborted) {
      throw new DOMException("Caller cancelled", "AbortError");
    }
    if (deadlineExceeded) {
      throw new DOMException("Request deadline exceeded", "TimeoutError");
    }
    throw error;
  } finally {
    clearTimeout(timer);
    parentSignal.removeEventListener("abort", cancelFromParent);
  }
}

async function loadOrderData(parentSignal: AbortSignal) {
  const deadline = performance.now() + 1_500;
  const getWithinDeadline = (path: string) => {
    const remainingMs = Math.floor(deadline - performance.now());
    if (remainingMs <= 0) {
      throw new DOMException("Request deadline exceeded", "TimeoutError");
    }
    return fetchJsonWithBudget(path, remainingMs, parentSignal);
  };

  const user = await getWithinDeadline("/users/42");
  const orders = await getWithinDeadline("/users/42/orders");
  return { user, orders };
}

// The HTTP framework should abort this signal if the caller disconnects.
const caller = new AbortController();
const orderData = await loadOrderData(caller.signal);

The first call might use 500 ms and leave about 1 second for the second call and response handling. If the caller disconnects, aborting caller cancels the in-flight fetch and its response body. That stops this client from waiting; it does not prove the remote service stopped work it already started. Browser fetch exposes cancellation for the request, not separate controls for every network phase.

Timeout types

Client libraries use these names differently, so check what each setting actually bounds:

  • Connect timeout: time allowed to establish the transport connection. Some clients include DNS lookup in this limit; others expose DNS separately.
  • TLS handshake timeout: time allowed to negotiate TLS after the transport connection is established.
  • Response-header timeout: time from sending the request until response headers arrive. Some libraries use “response timeout” for a different interval, so verify the definition.
  • Idle or read timeout: the maximum gap between chunks while reading a response body. It can let a slowly streaming response run much longer than the same duration.

A request deadline caps the whole operation, including local work and every downstream call. Phase timeouts help diagnose or bound particular waits; they do not replace that overall deadline. The example uses one AbortSignal for the full fetch call. For separate connect, TLS, header, and idle limits, choose a client or transport that exposes those controls.

Request and dependency flow

sequenceDiagram
    participant Client
    participant API as Backend API
    participant Pay as Payment service
    Client->>API: Create order (deadline 1500 ms)
    API->>Pay: Charge (budget 700 ms)
    Pay-->>API: Timeout or response
    Note over API,Pay: Retry only if the outcome is safe to repeat
    API-->>Client: Result or bounded failure

A bounded request example

This example assumes the GET endpoint is a side-effect-free read. It gets at most three attempts and a two-second budget. The code retries selected status codes and likely network or timeout errors, not programming errors.

const sleep = (ms: number): Promise<void> =>
  new Promise((resolve) => setTimeout(resolve, ms));

async function getWithRetries(url: string): Promise<Response> {
  const parsed = new URL(url);
  if (!["http:", "https:"].includes(parsed.protocol)) {
    throw new Error("Unsupported URL protocol");
  }

  const deadline = performance.now() + 2_000;
  const maxAttempts = 3;

  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
    const remainingMs = deadline - performance.now();
    if (remainingMs <= 0) throw new Error("Request deadline exceeded");

    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), remainingMs);

    try {
      const response = await fetch(url, { signal: controller.signal });
      const retryable = [429, 502, 503, 504].includes(response.status);
      if (!retryable || attempt === maxAttempts) return response;
      await response.body?.cancel();
    } catch (error) {
      const transient =
        error instanceof TypeError ||
        (error instanceof DOMException && error.name === "AbortError");
      if (!transient || attempt === maxAttempts) throw error;
    } finally {
      clearTimeout(timer);
    }

    const backoffMs = 100 * 2 ** (attempt - 1) + Math.random() * 100;
    const pauseMs = Math.min(backoffMs, deadline - performance.now());
    if (pauseMs <= 0) throw new Error("Request deadline exceeded");
    await sleep(pauseMs);
  }

  throw new Error("Request attempts exhausted");
}

The scheme check does not prevent server-side request forgery (SSRF). If a caller can supply the URL, enforce an explicit destination allowlist as well. Aborting a fetch stops the client from waiting; the server may still finish. For writes, use an idempotency key and check the outcome before repeating work. Never put credentials or payloads in retry logs.

Failure modes and trade-offs

Choice Benefit Cost or risk
Short timeout Releases request resources quickly Can reject healthy but slow work
Longer timeout Allows slow dependencies to finish Holds sockets and workers, increasing queueing
Bounded retry with jitter Recovers from brief faults Adds latency and extra dependency load
No retry Keeps load predictable Exposes callers to transient faults
Circuit breaker Fails fast during sustained trouble Needs thresholds and a fallback policy

Failures often combine. Packet loss raises timeouts; immediate retries then add load to a service already falling behind. A dependency may accept a write but lose the response, leaving the caller unsure of the result. Use deadlines, small retry budgets, idempotency keys, and queue limits. Load balancing can route around an unhealthy instance, but cannot fix a dependency that is slow everywhere.

Production failure scenarios

Tail-latency overload

Failure: A dependency’s p99 latency rises while its median stays normal. Requests queue behind slow calls until worker pools and sockets fill, pushing more requests past their deadlines.

Detection: Track p95/p99 by dependency alongside in-flight requests, queue depth, and timeout rate. Compare client wait time with server completion time to find work that continues after callers give up.

Mitigation: Set per-hop deadlines, cap concurrent calls, and shed work when capacity is exhausted. Use a fallback only when it returns safe, useful data.

Retries amplify an outage

Failure: Clients retry timeouts and 503 responses immediately. The already saturated dependency receives more requests, slows further, and triggers retries from additional services.

Detection: Watch attempts per original request, retry volume, dependency latency, and circuit-breaker state. If attempts per request rise, retries are adding load to the outage.

Mitigation: Retry at one layer, cap attempts and total retry time, and apply exponential backoff with jitter. Use a retry budget and circuit breaker; protect writes with idempotency keys.

Partial network failure leaves an unknown result

Failure: A backend commits a write, but a connection reset or lost response prevents the caller from seeing success. Other services remain reachable, so the failure may look like an isolated client timeout.

Detection: Compare client timeout/reset traces with server-side completion records and operation status. Alert on a rise in completed operations whose responses did not reach callers.

Mitigation: Give the operation an idempotency key and let callers check its status before retrying. Never repeat an unsafe write just because the response was lost.

Observability checklist

  • Record dependency, operation, attempt, and outcome without secrets or payloads.
  • Measure tail latency, timeout and retry rates, and error class by dependency.
  • Propagate traces; alert when slow spans or retry volume consume request budgets.
  • Compare client timeouts with server completion and cancellation metrics.

Security and compliance notes

Use TLS and validate certificates. Limit connections and response sizes, especially for user-controlled URLs, to reduce resource exhaustion and server-side request forgery risk. Keep authorization headers and sensitive data out of logs.

For regulated workloads, check the applicable requirements for encryption in transit, log access, audit records, and retention. TLS protects a connection but does not by itself make the service compliant.

Common pitfalls and anti-patterns

Avoid retrying every exception, giving every hop the same timeout, or watching only averages. A client abort also does not cancel server work automatically. Treat retries as an explicit load policy with clear safety rules.

Quick recap checklist

  • Distinguish latency, bandwidth, and jitter; inspect tail latency.
  • Give each operation a deadline and each dependency a smaller budget.
  • Retry only transient failures, within a small attempt and time limit.
  • Use idempotency for writes and jitter to spread retries.
  • Observe timeout and retry rates alongside successful latency.

Interview questions

1. How do latency, bandwidth, and jitter differ?
Latency is exchange delay, bandwidth is transfer capacity, and jitter is variation in delay. A small call can be latency-bound on a high-bandwidth link.
2. Why can a timeout leave a write in an unknown state?
The server may commit after the client stops waiting, or the response may be lost. A timeout does not prove rollback. Use an idempotency key or check operation status before retrying.
3. How can retries make an outage worse?
Clients add traffic to an overloaded dependency. Cap attempts, stay within the caller deadline, and add backoff with jitter.
4. How should downstream timeouts fit within a caller's deadline?

Expected answer points:

  • Propagate the caller's deadline or remaining budget to each dependency instead of giving every hop the full original timeout.
  • Reserve time for application work, response validation, and sending the result back to the caller.
  • For sequential calls, ensure their budgets and processing time fit within the total deadline; parallel calls still need limits and cancellation behavior.
5. Does a client timeout cancel work already running on the server?

Expected answer points:

  • No. The client can stop waiting while the server continues processing.
  • Cancellation must be propagated through the application and dependencies, and each component must honor it.
  • For a write with an unknown outcome, check its status or use an idempotency key before retrying.
6. When is an asynchronous queue a better fit than a longer request timeout?

Expected answer points:

  • Use a queue when the caller can receive an accepted or pending result and the work can finish later.
  • Keep the queue bounded and make consumers safe to retry so a dependency outage does not create unbounded backlog or duplicate effects.
  • It is a poor fit when the caller needs the completed result before it can continue.
7. Why add random jitter to exponential retry backoff?

Expected answer points:

  • Without jitter, many clients that fail together may retry at the same intervals.
  • Random delay spreads attempts over time and reduces synchronized load spikes at the recovering dependency.
  • Backoff still needs an attempt limit and the caller's overall deadline.

Further reading

Conclusion

The difficult case is a write that may have succeeded after its caller stopped waiting. Carry one deadline through the request, cancel work the caller no longer needs, and check an uncertain write’s status before trying it again.

Category

Related Posts

Network Observability: Signals for Reliable Services

Track network health across hosts, DNS, paths, proxies, and requests. Learn which signals help diagnose failures without confusing telemetry with service SLOs.

#networking #observability #monitoring

Background Jobs, Scheduling, and Worker Pools

Design background jobs and worker pools with bounded concurrency, safe retries, scheduling, and production checks that keep slow work out of request paths.

#backend #background-jobs #worker-pools

Debugging Backend Applications

Use a repeatable backend debugging workflow to reproduce failures, inspect evidence, test one hypothesis at a time, and verify fixes safely in production.

#debugging #backend #observability