research/retrying-a-flaky-http-call-with-a-deadline

Retrying a Flaky HTTP Call With Backoff and a Deadline: What to Retry and When to Give Up

Engineering Note · November 23, 2026 · 10 minute read · Node.js · HTTP · Reliability · Testing

A flaky HTTP call should be retried only when the failure is likely to be temporary and the request is safe to repeat: network errors, timeouts, 408, 429 and the 500, 502, 503 and 504 errors. Everything else, including 400, 401, 403 and 404, should come back to the caller after one try. Each try needs its own timeout, and the whole call needs a deadline that includes the waits between tries, so a slow service cannot hold your page or job hostage. Between tries, wait a random time up to an exponentially growing limit, unless the server says how long to wait with a Retry-After header. We wrote a 50-line helper that does this and tested it against a local server built to fail in six different ways.

Everything below was run on Linux with Node.js 22.23.5, using its built-in fetch, AbortSignal.timeout and node:http. No packages were installed. The outputs are the real ones from these runs; the waits are random, so your numbers will differ.

What did the misbehaving server do?

A tiny node:http server on a random local port, with one route per kind of failure. It counts requests per URL so we can see how many tries reached it.

const hits = {};
const server = http.createServer((req, res) => {
  hits[req.url] = (hits[req.url] ?? 0) + 1;
  const n = hits[req.url];
  const path = req.url.split("?")[0];
  if (path === "/503-twice") {               // fails twice, then works
    if (n <= 2) { res.writeHead(503); return res.end("busy"); }
    res.writeHead(200); return res.end("ok");
  }
  if (path === "/429") {                     // asks us to wait 2 seconds once
    if (n === 1) { res.writeHead(429, { "Retry-After": "2" }); return res.end(); }
    res.writeHead(200); return res.end("ok");
  }
  if (path === "/reset-once") {              // drops the connection once
    if (n === 1) return req.socket.destroy();
    res.writeHead(200); return res.end("ok");
  }
  if (path === "/slow") {                    // never answers in time
    setTimeout(() => { res.writeHead(200); res.end("late"); }, 5000);
    return;
  }
  if (path === "/400") { res.writeHead(400); return res.end("bad input"); }
  if (path === "/always-500") { res.writeHead(500); return res.end("down"); }
  res.writeHead(404); res.end();
});

What does the retry helper look like?

Four decisions shape it:

  1. What to retry. A fixed set of status codes, plus anything fetch throws (a dropped connection or a timeout). Any other response, including every other 4xx, is returned to the caller after one try.
  2. How long one try may take. perTryMs, enforced with AbortSignal.timeout. The last try gets whatever is left of the deadline, if that is less.
  3. How long the whole call may take. deadlineMs, checked before each try and before each wait. A wait that would end past the deadline is not started.
  4. How long to wait. “Full jitter”: a random number of milliseconds between zero and baseMs × 2^(try − 1), capped at maxMs. If the server sent Retry-After, that wins.
const RETRY_STATUS = new Set([408, 429, 500, 502, 503, 504]);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function retryAfterMs(res) {
  const h = res.headers.get("retry-after");
  if (!h) return null;
  const secs = Number(h);
  if (Number.isFinite(secs)) return secs * 1000;
  const when = Date.parse(h);                 // HTTP-date form
  return Number.isNaN(when) ? null : Math.max(0, when - Date.now());
}

export async function fetchWithRetry(url, opts = {}) {
  const {
    attempts = 4,          // total tries, including the first
    perTryMs = 1000,       // timeout for one try
    deadlineMs = 4000,     // budget for the whole call, waits included
    baseMs = 200,          // first backoff ceiling
    maxMs = 2000,          // largest single wait
    idempotent = true,     // only retry what is safe to repeat
    log = () => {},
    ...init
  } = opts;
  const deadline = Date.now() + deadlineMs;
  let lastErr;
  for (let i = 1; i <= attempts; i++) {
    const left = deadline - Date.now();
    if (left <= 0) break;
    const signal = AbortSignal.timeout(Math.min(perTryMs, left));
    let res, wait = null;
    try {
      res = await fetch(url, { ...init, signal });
      if (res.ok || !RETRY_STATUS.has(res.status)) return res; // success, or a 4xx we must not repeat
      wait = retryAfterMs(res);
      lastErr = new Error(`HTTP ${res.status}`);
      await res.body?.cancel();
    } catch (err) {
      lastErr = err;
      // network error or timeout: fall through and retry
    }
    if (!idempotent) { log(`try ${i}: ${lastErr.message}; not idempotent, giving up`); break; }
    if (i === attempts) { log(`try ${i}: ${lastErr.message}; out of attempts`); break; }
    // full jitter: a random wait between 0 and the exponential ceiling
    const ceiling = Math.min(maxMs, baseMs * 2 ** (i - 1));
    const delay = wait ?? Math.round(Math.random() * ceiling);
    if (Date.now() + delay >= deadline) { log(`try ${i}: ${lastErr.message}; waiting ${delay} ms would pass the deadline, giving up`); break; }
    log(`try ${i}: ${lastErr.message}; waiting ${delay} ms`);
    await sleep(delay);
  }
  throw lastErr ?? new Error("deadline passed before the first try");
}

Two small details matter. await res.body?.cancel() throws away the body of a failed response, so the connection is not left holding unread data while we wait. And the helper returns a non-retryable response instead of throwing, so the caller still sees the 400 and its message.

What happened against each failure?

Each case ran with the defaults above (four tries, 1-second tries, 4-second deadline) unless the label says otherwise. The line in parentheses is how many requests the server counted, and how long the whole call took.

503 twice, then OK  (server saw 3 request(s), 434 ms)
  try 1: HTTP 503; waiting 167 ms
  try 2: HTTP 503; waiting 245 ms
  => HTTP 200 "ok"

429 with Retry-After: 2  (server saw 2 request(s), 2007 ms)
  try 1: HTTP 429; waiting 2000 ms
  => HTTP 200 "ok"

connection reset once  (server saw 2 request(s), 52 ms)
  try 1: fetch failed; waiting 45 ms
  => HTTP 200 "ok"

400 bad input  (server saw 1 request(s), 2 ms)
  => HTTP 400 "bad input"

always 500  (server saw 4 request(s), 406 ms)
  try 1: HTTP 500; waiting 171 ms
  try 2: HTTP 500; waiting 104 ms
  try 3: HTTP 500; waiting 122 ms
  try 4: HTTP 500; out of attempts
  => threw: Error: HTTP 500

slow server, 1 s per try, 4 s deadline  (server saw 4 request(s), 4001 ms)
  try 1: The operation was aborted due to timeout; waiting 186 ms
  try 2: The operation was aborted due to timeout; waiting 77 ms
  try 3: The operation was aborted due to timeout; waiting 213 ms
  try 4: The operation was aborted due to timeout; out of attempts
  => threw: TimeoutError: The operation was aborted due to timeout

always 500, POST without idempotency  (server saw 1 request(s), 5 ms)
  try 1: HTTP 500; not idempotent, giving up
  => threw: Error: HTTP 500

429 with Retry-After: 2, but a 1.5 s deadline  (server saw 1 request(s), 1 ms)
  try 1: HTTP 429; waiting 2000 ms would pass the deadline, giving up
  => threw: Error: HTTP 429

What we read from it:

  • Temporary failures recovered. Two 503s, a 429 and a dropped connection all ended in a 200. The dropped connection shows up as a plain fetch failed error, with no status code, which is why the helper treats anything fetch throws as retryable.
  • The 400 came back after one request. Retrying a request the server called invalid would only send the same invalid request again.
  • The deadline held. Against the server that never answered, the call ended at 4,001 ms. Three full 1-second tries plus three short waits left about 0.5 seconds, so the fourth try was cut to fit. Without the deadline the same settings would have run past 4.5 seconds, and with a common 10-second per-try timeout they would have run past 40.
  • The slow server still did four requests’ worth of work. Aborting a fetch stops the client waiting; it does not tell the server to stop. Every timed-out retry against a struggling service adds to its load, which is one more reason to keep the number of tries small.
  • A deadline that cannot fit Retry-After gives up at once. Retrying before the server’s requested wait would most likely get another 429, so the helper returns the failure immediately, after one request and 1 ms.

Why does the POST case stop after one try?

Because a failed POST may not have failed. If the server created the booking and then timed out sending the answer, a retry creates a second booking. The helper only retries when the caller says the request is safe to repeat (idempotent: true, the default here because most calls we retry are GETs).

The idempotent flag is a promise the caller makes. For a GET that reads data, it is true. For a POST that creates something, it is only true when the server can recognize a repeat, usually through an idempotency key: a unique ID the client sends with the request, which the server stores with its first answer. Today’s companion note, Idempotency Keys for a Booking Form, tests exactly that: the same retry loop without a key created four bookings, and with a key created one.

Does jitter make a difference?

Jitter matters when many clients fail at once, for example when a service restarts and every open request gets a 503 at the same moment. With fixed waits, they all come back at the same moment too. We simulated ten clients, each making three retries with the same 200, 400 and 800 ms ceilings, added up each client’s waits to get the moment of each retry, and counted the retries in the busiest 50 ms window (the code is in the same script as the helper):

ten clients, three retries each: most retries landing in one 50 ms window
  fixed exponential (200, 400, 800 ms): 10
  full jitter:                          6

Fixed waits put all ten clients in the same window, three times over. Full jitter is random, so we ran it six times in all: the busiest window held 7, 5, 5, 8, 5 and 6. With only ten clients and a 200 ms first ceiling, the first round of retries has just four 50 ms windows to spread into, so the gain is real but modest. It grows with the number of clients and the size of the ceiling.

A checklist for any retry loop

  • Retry network errors, timeouts, 408, 429, 500, 502, 503 and 504. Return everything else.
  • Give each try a timeout, and the whole call a deadline that includes the waits.
  • Wait a random time up to a capped exponential limit, and honor Retry-After when it fits the deadline.
  • Retry a POST only with an idempotency key the server understands.
  • Log each try and its wait, so a slow day shows up as retries rather than mystery delays.
  • Pick the deadline from how long the person or job on the other end can wait, and check whether the service you call documents its own retry advice.

Limitations

  • The server was local. Real networks add DNS failures, TLS errors and proxies, which fetch reports as other thrown errors; we did not test those separately.
  • The status codes we retry are our choice, based on what they usually mean. We could not open the HTTP specification (RFC 9110) from this environment, so we have not quoted it on which methods are idempotent or on the exact forms Retry-After may take. Our helper accepts a number of seconds or a date.
  • The jitter comparison is a simulation of arrival times, not a load test against a real service.
  • Only Node.js 22.23.5’s built-in fetch was tested. Other HTTP clients report timeouts and dropped connections with different error types.

Frequently asked questions

Which HTTP errors should I retry?

Retry network failures, timeouts, 408, 429, 500, 502, 503 and 504, which usually mean the service was busy or briefly unreachable. Do not retry other 4xx responses such as 400, 401, 403 or 404: the same request will fail the same way. That is the set our helper uses, and the 400 in our test returned after one request.

What is the difference between a timeout and a deadline?

A timeout limits one try. A deadline limits the whole call, including every retry and every wait between them. Without a deadline, four tries with a 10-second timeout plus backoff can keep a visitor waiting close to a minute. In our test a server that never answered was abandoned at 4.0 seconds, as the deadline said.

Why add jitter to retry backoff?

When many clients fail at the same moment, fixed waits make them all retry at the same moment too, which can knock a recovering service over again. Jitter picks a random wait up to the backoff limit, which spreads them out. In our simulation of ten clients, the busiest 50 ms window held all 10 retries with fixed waits and between 5 and 8 with full jitter.

Should I honor the Retry-After header?

Yes, when the wait it asks for fits inside your deadline. Our helper waits exactly what the server asks, and gives up straight away when that wait would pass the deadline, rather than retrying early and being refused again. In our test a Retry-After of 2 seconds with a 1.5-second deadline ended the call after one request.

Is it safe to retry a POST request?

Only if the server can recognize a repeat. A POST that timed out may have succeeded, so retrying it can create a second order or booking. Retry it only when the server supports an idempotency key, a unique ID sent with the request so repeats are answered from the first result. Otherwise fail once and let a person decide.

More from Research

← All research