skip to content

A Node 24 service's calls to a slow payment API sometimes hang for minutes; what does each built-in client timeout bound, and how do you cap the whole call?

level: seniorimportance: must knowfreq 55%

answer

  1. idle timers versus a deadline
  2. an event that aborts nothing
  3. undici's five-minute defaults
  4. one signal for the whole call

basics

~20 s

Node's built-in client timeouts are idle timers: http.request's timeout only emits 'timeout', and fetch's undici defaults allow 300 seconds for headers and between body chunks. Cap the whole call with signal: AbortSignal.timeout(ms), which covers connect, headers and body.

solid answer

~40 s

For `http.request()`, the `timeout` option and `req.setTimeout()` set a socket **inactivity** timer; the docs are explicit that it does not abort the request or do anything besides emit `'timeout'`, so you must call `req.destroy()` yourself, and a server trickling bytes never trips it. For `fetch()`, undici's dispatcher applies a connect timeout of 10 seconds, `headersTimeout` of 300 seconds and `bodyTimeout` of 300 seconds measured between body chunks, surfacing as `TypeError: fetch failed` with a `cause` such as `UND_ERR_HEADERS_TIMEOUT`. None of these is a total deadline. Pass `signal: AbortSignal.timeout(2000)`: fetch rejects with a `DOMException` named `TimeoutError`, and a body still being read errors with the same reason. `http.request()` accepts the same `signal` and fails with code `ABORT_ERR`.

code

javascript · 16 lines
javascript
async function charge(payload) {
  const res = await fetch('http://localhost:4000/charge', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(payload),
    signal: AbortSignal.timeout(2000), // connect + headers + body
  });
  return res.json(); // still under the same 2-second deadline
}

try {
  console.log(await charge({ orderId: 'o-1', amount: 1999 }));
} catch (err) {
  if (err.name === 'TimeoutError') console.error('payment call exceeded 2 s');
  else throw err;
}

go deeper

for a junior

Recall that AbortSignal.timeout(ms) passed as signal is the usual way to bound a fetch() call in Node.

for a middle

Explain the difference between an idle timer and a deadline, and why http.request's timeout only emits an event.

for a senior

Diagnose a call that hangs past every configured timeout, name which timer each failure came from, and put the body read under the deadline.

for a principal

Decide which dispatcher-level backstops a team sets so a forgotten signal fails in seconds rather than minutes.

## Why the call hangs A payment API that accepts the connection and then stalls, or sends headers and dribbles the body, defeats most timeouts because they measure **inactivity**, not **elapsed time**. Node's two clients each ship idle timers with generous or absent defaults, and only an abort signal gives a hard ceiling. ## node:http: timeout is a notification For `http.request()` and `http.get()`: - The **`timeout`** option, and `request.setTimeout(ms)`, call `socket.setTimeout()` once the socket connects. If the socket sees no traffic for that long, the request emits **`'timeout'`**. - The documentation is direct: setting the option "will not abort the request or do anything besides add a 'timeout' event". If you listen for it, you must call `req.destroy()` yourself. - An agent's own `timeout` option, including the 5-second one on `http.globalAgent`, sets the same kind of socket timer; it is an idle timer, not a cap on the whole exchange. - A server that sends one byte every few seconds resets the timer each time, so the call can run indefinitely while never being "idle". ## fetch(): undici's dispatcher timers `fetch()` gets its timers from undici's dispatcher options: | Timer | Default | What it measures | Failure | |---|---|---|---| | connect timeout | 10 s | TCP (and TLS) connection setup | `UND_ERR_CONNECT_TIMEOUT` | | `headersTimeout` | 300 s | wait for complete response headers | `UND_ERR_HEADERS_TIMEOUT` | | `bodyTimeout` | 300 s | gap between body chunks | `UND_ERR_BODY_TIMEOUT` | A dispatcher timeout makes the `fetch()` promise reject with `TypeError: fetch failed`, carrying undici's error in `cause`. Five minutes for headers is far longer than most service-to-service calls can tolerate, and `bodyTimeout` resets with every chunk, so neither bounds total duration. You can lower them on a custom dispatcher passed in the `dispatcher` option, but they remain per-phase idle limits. ## AbortSignal.timeout(): the total deadline `AbortSignal.timeout(ms)` returns a signal that aborts after `ms` milliseconds with a `DOMException` named **`TimeoutError`**. Node unrefs its internal timer, so a pending timeout signal does not keep the process alive. - **With `fetch()`**: pass it as `signal`. If it fires before headers, the promise rejects with that `TimeoutError`. If it fires while you are reading the body with `res.json()` or `res.text()`, the body stream errors with the same reason, so **one signal bounds connect, headers and body together**. - **With `http.request()`**: the `signal` option has been accepted since v15.3.0. Aborting behaves like `req.destroy()`: the request emits `'error'` with the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`, and the abort reason as `cause` when one was provided. - Create the signal **per call**. A signal is aborted once and stays aborted; one created at module load and shared would fail every later call. How to combine a per-call deadline with a caller's cancellation signal, and the general AbortSignal contract, are covered in the JavaScript lessons on cancellation. ## What an abort costs An abort is not free, and at high volume with tight deadlines the cost shows: - In `fetch()`, aborting a request that is still in flight tears down **that connection**; undici destroys the socket rather than returning it to the pool. The next call to the same origin pays for a new TCP and TLS handshake. - In `http.request()`, an abort behaves like `req.destroy()`, which also destroys the socket. - A deadline that fires often is therefore also a connection-churn signal: the deadline may be too tight for the dependency's normal latency, or the dependency is degrading. ## Putting it together 1. Give every outbound call an `AbortSignal.timeout()` sized for that dependency. 2. Read the body under the same signal, so a stalled body cannot outlive the deadline. 3. Treat `err.name === 'TimeoutError'` as "we gave up", distinct from `TypeError: fetch failed`, which means the network or a dispatcher timer failed first. 4. Optionally lower undici's `headersTimeout` and `bodyTimeout` on the dispatcher as a backstop for code paths that forget the signal. 5. Remember that giving up locally does not stop the payment API's work; idempotency and retry rules belong to the resilience material, not to these APIs. ## Common errors - Relying on `timeout` in `http.request()` options and never listening for `'timeout'`, so nothing is ever aborted. - Assuming fetch has "no timeout" when it has five-minute ones, or assuming those five minutes are a total cap. - Racing `fetch()` against a timer promise: the caller moves on, but the request and its socket keep running.

  • Your code sets { timeout: 3000 } on http.request() and the call still hangs. What is missing?
    A `'timeout'` listener that destroys the request. The option only emits `'timeout'` after 3 seconds of socket inactivity; Node does not abort anything. Add `req.on('timeout', () => req.destroy(new Error('idle timeout')))`, and add a `signal` from `AbortSignal.timeout()` if you need a total deadline rather than an idle one.
  • How do you tell a deadline abort from a network failure when fetch() rejects?
    With `AbortSignal.timeout()`, the rejection is the signal's reason: a `DOMException` whose `name` is `'TimeoutError'`. A network failure or a dispatcher timer rejects with `TypeError: fetch failed`, and its `cause` holds undici's error, for example code `UND_ERR_CONNECT_TIMEOUT` or `UND_ERR_HEADERS_TIMEOUT`.

  • The timeout option on http.request aborts the request when it fires.
  • fetch in Node has no timeout at all unless you add one.
  • undici's bodyTimeout caps how long the whole download may take.
  • One shared AbortSignal.timeout created at startup works for every call.
  • The timeout signal only covers the wait for headers, not the body read.

Assumes Node 24 with its bundled undici 7.x: a 10-second connect timeout, 300-second headersTimeout and bodyTimeout, and a 4-second keepAliveTimeout; http.request() has accepted signal since v15.3.0.