How to simulate slow API responses and test your timeouts

25 November 2026 · 7 min read

A dependency that's down is easy to live with. Requests fail in a few milliseconds, your error handling kicks in, and the user sees a message. A dependency that answers in 45 seconds is much worse. Every request that touches it holds a worker, a connection and a bit of memory while it waits, the queue behind it grows, and soon the parts of your app that never call that API are slow too.

The fix is a timeout on every outbound call, plus a way to prove it works. This guide covers both: what your HTTP client does by default (often nothing useful), how to set connect, read and total timeouts in Node, Python and Go, how timeouts and retries share one budget, and how to simulate a slow API response so you can test all of it.

Most HTTP clients wait far longer than you think

Here's what popular clients do when you don't set anything. We checked each one in its source.

Client Default timeout
Node.js fetch (undici) 10 s to connect, then 300 s for the response headers and 300 s between chunks of the body
axios timeout: 0, which means no timeout at all
Python requests None. The timeout argument defaults to None and requests waits forever
Go http.Client Timeout: 0 means no limit. The default transport only bounds dialing (30 s) and the TLS handshake (10 s)

So a Node service using plain fetch will wait up to five minutes for a stuck upstream to send headers, and a server that trickles out one byte every few seconds can keep it busy indefinitely. A Python worker using requests without a timeout can hang until the process is killed.

None of these defaults is a bug. A library can't know whether you're downloading a 2 GB file or calling a payments API with a 300 ms p99. That decision is yours, and most code never makes it.

Connect, read and total timeouts are different things

"Timeout" means at least three different limits, and clients disagree on which one their single timeout option controls.

  • Connect timeout: how long to wait for the TCP (and TLS) connection. Short is fine, since a healthy server accepts connections in milliseconds. A few seconds is plenty.
  • Read timeout: how long to wait between bytes. It resets every time data arrives.
  • Total timeout (deadline): the most the whole request may take, from the first byte sent to the last byte received.

The difference matters. We pointed Python requests with timeout=(3.05, 2) at a local server that sent one byte per second: the call took 8 seconds and succeeded, because no single gap reached 2 seconds. The same trickle against Go's http.Client{Timeout: 2 * time.Second} failed at exactly 2 seconds, because Go's Timeout covers the whole exchange, body included.

axios has its own twist. In Node, its timeout option is implemented with request.setTimeout, which is an inactivity timer on the socket. Against the same trickling server, an axios client with timeout: 2000 happily waited 5 seconds. (In the browser, axios uses XMLHttpRequest.timeout, which is a total limit.)

If a slow dependency should never cost you more than N seconds, you want a total deadline. A read timeout alone doesn't give you one.

Setting timeouts properly in Node, Python and Go

Node.js fetch: AbortSignal.timeout

const res = await fetch("https://api.example.com/orders/42", {
  signal: AbortSignal.timeout(3000), // total: covers headers and body
});
const order = await res.json();

AbortSignal.timeout(ms) gives you a real deadline. The same signal also aborts reading the body, so res.json() can't hang after the headers arrive. When it fires, the promise rejects with a DOMException named TimeoutError (a manual controller.abort() gives AbortError instead), which lets you tell the two apart:

try {
  await fetch(url, { signal: AbortSignal.timeout(3000) });
} catch (err) {
  if (err instanceof Error && err.name === "TimeoutError") {
    // the upstream was too slow: fall back, serve cached data, or fail fast
  }
  throw err;
}

axios: timeout plus a signal

import axios from "axios";

const api = axios.create({ baseURL: "https://api.example.com", timeout: 3000 });

// timeout: fails if the socket is idle for 3 s (ECONNABORTED)
// signal: a hard 5 s cap on the whole request (ERR_CANCELED)
const { data } = await api.get("/orders/42", { signal: AbortSignal.timeout(5000) });

Use both in Node. The timeout catches a server that goes silent; the signal catches one that keeps the connection alive with a slow trickle.

Python requests: always pass a tuple

import requests

try:
    r = requests.get("https://api.example.com/orders/42", timeout=(3.05, 5))
    r.raise_for_status()
except requests.exceptions.ConnectTimeout:
    ...  # couldn't connect within 3.05 s
except requests.exceptions.ReadTimeout:
    ...  # connected, but the server went quiet for 5 s

The tuple is (connect, read), as the requests docs on timeouts describe. Both exceptions inherit from requests.exceptions.Timeout, so you can catch that if you treat them the same. Remember the read value is per gap, not per request. If you need a hard total, enforce it around the call (a worker-level deadline, or a client such as httpx that supports one).

Go: Client.Timeout or a context

client := &http.Client{Timeout: 3 * time.Second} // connect, headers and body

// or per request, when the caller already has a deadline:
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.example.com/orders/42", nil)
resp, err := client.Do(req)

Avoid http.DefaultClient (and http.Get, which uses it) for calls to other services: it has no overall timeout.

Timeouts and retries share one budget

Retries make timeouts trickier. Three attempts with a 10-second timeout each can keep a request alive for 30 seconds plus backoff, long after the user (or the load balancer in front of you) gave up.

Give each call two limits: a per-attempt timeout and an overall deadline that no attempt or backoff wait may cross. In Node, AbortSignal.any combines them:

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

/** GET with a per-attempt timeout, retries, and one overall deadline. */
export async function getWithDeadline(url: string, { attemptMs = 2000, totalMs = 5000, retries = 2 } = {}) {
  const deadline = AbortSignal.timeout(totalMs);
  for (let attempt = 0; ; attempt++) {
    try {
      const res = await fetch(url, { signal: AbortSignal.any([deadline, AbortSignal.timeout(attemptMs)]) });
      if (res.status >= 500 && attempt < retries) throw new Error(`HTTP ${res.status}`);
      return res;
    } catch (err) {
      if (deadline.aborted || attempt >= retries) throw err;
      await sleep(Math.min(250 * 2 ** attempt, 2000) * (0.5 + Math.random() / 2)); // backoff with jitter
    }
  }
}

Against a local server that took 3 seconds to answer, getWithDeadline(url, { attemptMs: 1000, totalMs: 2500, retries: 5 }) rejected with TimeoutError at 2.5 seconds, not after six slow attempts. To size the numbers:

  1. Set the per-attempt timeout a little above the dependency's normal p99 latency, so healthy-but-slow requests still succeed.
  2. Set the total deadline below whatever is waiting on you: your own endpoint's timeout, the load balancer's idle timeout, or the user's patience.
  3. Only retry what's safe to repeat. A timed-out POST may have gone through; send an Idempotency-Key so the server can deduplicate it.
  4. Treat a timeout as a signal. Lots of them in a row usually mean you should stop calling for a while (a circuit breaker), not retry harder.

How to simulate a slow API response

You can't test any of this against a fast, healthy API. You need one that's slow on demand.

The local options all work, and each has a cost:

  • A stub server that sleeps (a few lines of Express or http.server). Easy, but you maintain it, and it rarely matches the real API's responses.
  • Toxiproxy sits between your app and the dependency and can add latency or stall connections. Powerful, but it's another service to run in every environment, and you configure it per test.
  • tc netem adds delay at the network level. Realistic, but Linux-only, needs root, and slows everything on that interface.

Jitterbox takes a different route: it's a hosted fake of the API you call, at a real URL (https://<projectKey>.jitterbox.dev), and a failure scenario decides how it misbehaves. Two kinds of fault matter here:

  • Latency adds a delay before the response. Give it a fixed value or a range (a range picks a random delay per request) and choose how often it fires.
  • Timeout makes the request hang, then answers 504 Gateway Timeout. It's the "upstream never answered" case.

Both are capped at 30 seconds. You can set them up in the dashboard, or as code in jitterbox.yaml:

scenarios:
  - name: Slow gateway
    endpoints: ["GET /orders/{id}"]
    enabled: false
    faults:
      - latency: 500-3000ms   # a random delay in this range
        rate: 30%             # on about 3 in 10 requests
      - timeout: 10s          # hang for 10 s, then 504
        rate: 1 in 10

For a single test you don't even need a scenario. Send the X-Jitterbox-Fault header and that one request gets the fault, whatever scenario is on:

# this request waits 4 seconds, then answers normally
curl -H "X-Jitterbox-Fault: latency=4000" https://<projectKey>.jitterbox.dev/orders/42

# this one hangs for 10 seconds, then answers 504
curl -H "X-Jitterbox-Fault: timeout=10000" https://<projectKey>.jitterbox.dev/orders/42

That makes a focused test straightforward:

import { test } from "node:test";
import assert from "node:assert/strict";

const BASE = process.env.JITTERBOX_BASE_URL; // your project's mock base URL

test("gives up on a hung upstream within its deadline", async () => {
  const started = Date.now();
  await assert.rejects(
    fetch(`${BASE}/orders/42`, {
      headers: { "X-Jitterbox-Fault": "timeout=10000" },
      signal: AbortSignal.timeout(3000),
    }),
    { name: "TimeoutError" },
  );
  assert.ok(Date.now() - started < 3500);
});

Every request lands in the live request log with the faults that were applied and why, so when a test fails you can see what the client was sent.

Check that your client gives up, not just that the test passes

A test proves one code path. The resilience report looks at everything your app sent while a scenario was on. One of its checks is Times out instead of hanging: whenever a request hit a timeout fault of 5 seconds or more, it passes if the client disconnected or retried before Jitterbox answered, and fails if the client sat there for the whole hang. It sits alongside checks for retries, backoff, Retry-After and idempotency keys, so you also catch a client that times out correctly and then retries instantly.

To keep it from regressing, run your suite against the scenario in CI and require that check to pass:

npx jitterbox run --scenario "Slow gateway" --require times-out -- npm test

jitterbox run switches the scenario on, runs your tests with JITTERBOX_BASE_URL set, switches it off again and fails the build if the check fails. Jitterbox in CI has the GitHub Action version.

Where to start

Search your codebase for outbound calls with no timeout: bare fetch( with no signal, axios.create( with no timeout, requests.get( with no timeout=, http.Get( in Go. Each one is a place where a slow dependency can stall your service. Add a total deadline to the most important one, point its tests at a slow fake, and watch it give up on time. The getting started guide gets you a mock URL in a couple of minutes.

Questions people ask

Does Node.js fetch have a default timeout?

Not a useful one. Node's fetch is built on undici, which waits up to 10 seconds to connect, 300 seconds for the response headers and 300 seconds between chunks of the body. A slow upstream can hold a request for five minutes, and one that trickles data can hold it longer. Pass signal: AbortSignal.timeout(ms) to set a real total deadline.

What is the difference between a connect timeout and a read timeout?

A connect timeout limits how long the client waits to open the connection. A read timeout limits the gap between bytes once connected, and resets whenever data arrives. Neither caps the whole request: a server sending one byte a second never trips a 2 second read timeout. For a hard cap, use a total deadline such as AbortSignal.timeout in Node or http.Client.Timeout in Go.

Does Python requests have a default timeout?

No. The timeout argument defaults to None, so requests waits indefinitely for a server that never answers. Always pass one, ideally as a (connect, read) tuple such as timeout=(3.05, 5). Catch requests.exceptions.ConnectTimeout and ReadTimeout separately, or their parent requests.exceptions.Timeout, to handle them.

How do I simulate a slow API response in tests?

Point your client at a fake API that delays on purpose. A local stub that sleeps, Toxiproxy or tc netem all work. Jitterbox gives you a hosted fake at a real URL with latency faults (a fixed delay or a random range, on a share of requests) and timeout faults that hang, then answer 504. The X-Jitterbox-Fault header applies one to a single request.

How should timeouts and retries work together?

Give each call a per-attempt timeout slightly above the dependency's normal p99 latency, and one overall deadline that no attempt or backoff wait may cross. Without the overall deadline, three attempts with a 10 second timeout can keep a request alive for 30 seconds or more, long after the caller has given up.

Try it on your own code

Jitterbox gives you a fake version of the APIs you call, at a real URL, and makes them fail on purpose. Free during the beta.