How to Set Timeouts and Retries on fetch in Node.js
Add timeouts with AbortSignal.timeout, combine signals with AbortSignal.any, and write a retry helper with backoff, jitter and Retry-After that is safe for GET.

A request without a timeout is a request that can hang forever, and a request without a retry policy fails on the first hiccup of a network that was never promised to be reliable. The global fetch in Node.js has neither built in, but it gives you the part that matters: it accepts an AbortSignal, and the platform provides signals that fire after a delay. This post shows how to set a timeout with AbortSignal.timeout, how to combine it with a manual cancel using AbortSignal.any, how to tell a timeout from an abort, and how to write a retry helper with exponential backoff, jitter and Retry-After support that only retries what is safe to retry. The samples target Node.js 26 and rely on the AbortSignal documentation.
Why the default is a problem
A server that accepts the connection and never answers keeps your request pending. The Node.js HTTP client has internal limits for connecting and for headers, which are configurable on the undici dispatcher, but there is no overall deadline for a call on the plain fetch API. In a script that is an annoyance. In a server it is a leak: each hung request holds a socket, memory and often a user waiting. The fix is a deadline on every outbound call.
A timeout in one line
AbortSignal.timeout(ms) returns a signal that aborts after the delay. Pass it as the signal option.
try {
const res = await fetch("https://api.example.com/slow", {
signal: AbortSignal.timeout(2000),
});
console.log(res.status);
} catch (err) {
console.log(err.name);
console.log(err.message);
}If the server does not answer within two seconds, the output is:
TimeoutError
The operation was aborted due to timeoutThe error name is TimeoutError. That distinguishes it from AbortError, which is what you get when code calls abort() on a controller. The deadline covers the whole exchange up to the response headers, and, because the signal stays attached, also the reading of the body: if the body stalls after the headers arrive, res.json() rejects with the same error. That is usually what you want.
Cancelling by hand as well
Sometimes you also want to cancel for your own reasons, such as the user navigating away or a server shutting down. A manual AbortController gives you that, and AbortSignal.any combines it with the timeout so either one stops the request.
const controller = new AbortController();
setTimeout(() => controller.abort(), 500);
try {
await fetch("https://api.example.com/slow", {
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]),
});
} catch (err) {
console.log(err.name);
}The manual abort fires first, at half a second, so the output is:
AbortErrorCheck err.name to know which one happened, because the two need different handling: a timeout is a failure you may retry, and a manual abort is a decision you must respect.
A fetch wrapper with a default deadline
Rather than repeat the option, wrap fetch once. The wrapper also checks res.ok and turns every failure into an error that carries the status.
export class HttpError extends Error {
constructor(status, url) {
super(`HTTP ${status} for ${url}`);
this.status = status;
}
}
export async function request(url, { timeout = 5000, signal, ...options } = {}) {
const signals = [AbortSignal.timeout(timeout)];
if (signal) signals.push(signal);
const res = await fetch(url, { ...options, signal: AbortSignal.any(signals) });
if (!res.ok) throw new HttpError(res.status, String(url));
return res;
}import { request } from "./http.js";
const res = await request("https://api.example.com/users/1", { timeout: 3000 });
console.log(await res.json());{ id: 1, name: 'Ada' }What is safe to retry
Retrying is not free. Repeating a request that already changed something on the server can charge a card twice or create a duplicate row. The rule is about idempotency: an operation is idempotent if doing it twice has the same effect as doing it once.
| Method | Retry by default |
|---|---|
| GET, HEAD, OPTIONS | yes |
| PUT, DELETE | yes, they are defined as idempotent |
| POST, PATCH | no, unless the API supports an idempotency key |
And only some failures are worth retrying: network errors, timeouts, 429 Too Many Requests, and 502, 503 and 504. A 400, 401, 403 or 404 will fail the same way next time, so retrying wastes time and load.
const RETRY_STATUS = new Set([408, 429, 500, 502, 503, 504]);
export function isRetryable(err) {
if (err.name === "TimeoutError") return true;
if (err.name === "AbortError") return false;
if (typeof err.status === "number") return RETRY_STATUS.has(err.status);
return err instanceof TypeError;
}
console.log(isRetryable({ name: "Error", status: 503 }));
console.log(isRetryable({ name: "Error", status: 404 }));
console.log(isRetryable({ name: "AbortError" }));true
false
falseA network failure from fetch is a TypeError, which is why the last line of the function treats it as retryable. A 500 is included here, but think about whether your API signals permanent bugs that way before you keep it.
Backoff with jitter
Retrying immediately hits a struggling server again at the worst moment. Exponential backoff waits longer after each failure, and jitter randomises the wait so that a thousand clients that failed together do not retry together.
export function backoffDelay(attempt, base = 200, cap = 5000) {
const exp = Math.min(cap, base * 2 ** attempt);
return Math.random() * exp;
}
for (let attempt = 0; attempt < 4; attempt++) {
const max = Math.min(5000, 200 * 2 ** attempt);
console.log(`attempt ${attempt}: wait between 0 and ${max} ms`);
}attempt 0: wait between 0 and 200 ms
attempt 1: wait between 0 and 400 ms
attempt 2: wait between 0 and 800 ms
attempt 3: wait between 0 and 1600 msThis is the "full jitter" form: the wait is a random number between zero and the exponential ceiling. The cap stops the delay growing without limit. The actual waits are random, so the figures above show the range, not a measured value.
Respecting Retry-After
When a server answers 429 or 503, it may say how long to wait with Retry-After, either as seconds or as an HTTP date. A client that ignores it is a bad neighbour.
export function retryAfterMs(res) {
const value = res.headers.get("retry-after");
if (!value) return null;
const seconds = Number(value);
if (Number.isFinite(seconds)) return seconds * 1000;
const date = Date.parse(value);
return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
}
const res = new Response(null, { status: 429, headers: { "retry-after": "3" } });
console.log(retryAfterMs(res));3000The retry helper
Now combine the pieces. The helper takes a function that performs one attempt, so it can be reused for any call, and it honours an outer abort signal so cancelling stops the loop as well.
import { setTimeout as sleep } from "node:timers/promises";
import { backoffDelay } from "./backoff.js";
import { isRetryable } from "./retryable.js";
export async function withRetry(attempt, { retries = 3, signal } = {}) {
for (let n = 0; ; n++) {
try {
return await attempt(n);
} catch (err) {
if (n >= retries || !isRetryable(err)) throw err;
const wait = err.retryAfter ?? backoffDelay(n);
console.log(`attempt ${n + 1} failed (${err.status ?? err.name}), retrying`);
await sleep(wait, undefined, { signal });
}
}
}import { request } from "./http.js";
import { withRetry } from "./retry.js";
const res = await withRetry(() => request("https://api.example.com/flaky", { timeout: 2000 }));
console.log(res.status);If the first two calls return 503 and the third succeeds, the output is:
attempt 1 failed (503), retrying
attempt 2 failed (503), retrying
200sleep from node:timers/promises accepts a signal, so an abort during the wait rejects at once with AbortError, and isRetryable is not consulted again because the error leaves through the sleep line, not the catch. For POST, pass an Idempotency-Key header with a stable value across attempts if the API supports it, so the server can recognise the repeat.
Testing retries
Test the helper with a fake attempt function that fails a set number of times, with the delay shortened by passing a small cap, instead of calling a real server.
import { test } from "node:test";
import assert from "node:assert/strict";
import { withRetry } from "./retry.js";
test("retries until success", async () => {
let calls = 0;
const result = await withRetry(async () => {
calls += 1;
if (calls < 3) throw Object.assign(new Error("busy"), { status: 503, retryAfter: 1 });
return "ok";
});
assert.equal(result, "ok");
assert.equal(calls, 3);
});ā retries until successChoosing the numbers
There is no universal timeout. Choose it from what the call is for and what the caller can tolerate. A request made while a user waits should fail fast, within a few seconds, so the interface can show an error or fall back, while a background job that calls a slow reporting API can wait much longer. Start from the service's own behaviour: if its normal responses arrive well inside a second, a timeout of a few seconds leaves plenty of room and still catches a hang. Do not set the timeout to the highest value you can imagine, because the point of a deadline is to free resources.
Retry budgets deserve the same care. Each retry multiplies the load on a service that is already failing, so a system where every layer retries three times can turn one failure into dozens of requests. Keep retries at one layer where possible, cap the total time across all attempts with an outer signal, and stop retrying when the caller has given up. A circuit breaker, which stops calls for a short period after repeated failures, is the next step when a dependency is regularly unreliable.
Logging what happened
When a retry succeeds, the caller never sees a failure, so record it. A log line per retried attempt, with the URL host, the status or error name and the attempt number, shows how often a dependency misbehaves. Without those lines, a service can look healthy while quietly depending on retries to stay that way, and the first sign of trouble is the day the retries stop being enough.


