← Back to Node.js, page 8

nodejs-0150 · Hard senior

How do you propagate request cancellation and deadlines in a Node.js service so that work stops when the client leaves or time runs out?

Create an AbortController per request. Abort it when the client connection closes before the response finished, and combine it with AbortSignal.timeout(deadline) using AbortSignal.any. Pass the signal to fetch, database drivers that support it, timers and streams. Return 504 when the deadline passes, and pass the remaining time to downstream calls, so work that nobody waits for stops.

Full answer

The problem

  • A client closes the tab, a mobile network drops, or a gateway times out after 30 seconds. Without cancellation, the server keeps doing the work: database queries, calls to other services, expensive computation. Under load, this wasted work makes the overload worse.
  • Slow downstream calls without a timeout hold the request open and use sockets and memory.

The approach

  1. Create one AbortController per incoming request.
  2. Abort it when the response is closed before it finished: res.on('close', () => { if (!res.writableFinished) controller.abort() }). (The 'close' event of res fires on finish too, so check writableFinished.)
  3. Add a deadline: AbortSignal.timeout(ms). Combine with AbortSignal.any([closeSignal, timeoutSignal]) so either one cancels the work.
  4. Pass the signal to everything that can use it: fetch(url, { signal }), timers/promises (setTimeout with signal), streams and pipeline, fs.promises functions, and database drivers with cancellation support (pg does not cancel a running query through a signal, so use statement_timeout and query_timeout there).
  5. When the signal aborts, stop early and return quickly. Send 504 Gateway Timeout for a deadline, and do not try to write to a closed connection.
  6. Propagate the deadline: send the remaining time to downstream services in a header (for example X-Request-Timeout or gRPC deadlines), and subtract a margin. Each hop should wait less than its caller.

Design points

  • Choose timeouts per dependency, smaller than the user-facing timeout.
  • Retries must respect the overall deadline.
  • Cancellation is cooperative. Code that ignores the signal keeps running. CPU loops need to check signal.aborted.
  • Log cancelled requests at a low level, because client aborts are normal.
  • Combine with load shedding and circuit breakers for a service that degrades gracefully.
javascript
const http = require('node:http');
const express = require('express');
const { setTimeout: sleep } = require('node:timers/promises');

// A slow downstream service that notices when its caller goes away.
let downstreamAborted = 0;
const downstream = http.createServer((req, res) => {
  const timer = setTimeout(() => res.end('downstream result'), 500);
  res.on('close', () => { if (!res.writableFinished) { clearTimeout(timer); downstreamAborted++; } });
});

function deadline(ms) {
  return (req, res, next) => {
    const closed = new AbortController();
    res.on('close', () => { if (!res.writableFinished) closed.abort(new Error('client went away')); });
    const started = Date.now();
    res.locals.signal = AbortSignal.any([closed.signal, AbortSignal.timeout(ms)]);
    res.locals.remainingMs = () => Math.max(0, ms - (Date.now() - started));
    next();
  };
}

downstream.listen(0, '127.0.0.1', () => {
  const downstreamUrl = 'http://127.0.0.1:' + downstream.address().port;
  const app = express();
  app.get('/report', deadline(200), async (req, res) => {
    try {
      const response = await fetch(downstreamUrl + (req.query.fast ? '/fast' : ''), { signal: res.locals.signal });
      res.send(await response.text());
    } catch (err) {
      if (res.writableEnded || res.destroyed) return;                        // the client already left
      res.status(err.name === 'TimeoutError' ? 504 : 500).json({ error: err.name });
    }
  });
  app.get('/quick', deadline(200), async (req, res) => {
    await sleep(20, null, { signal: res.locals.signal });
    res.json({ ok: true, deadlineRemainingIsLessThan200: res.locals.remainingMs() < 200 });
  });

  const server = app.listen(0, '127.0.0.1', async () => {
    const base = 'http://127.0.0.1:' + server.address().port;

    // 1. The deadline (200 ms) passes before the downstream answers (500 ms).
    const slow = await fetch(base + '/report');
    console.log('1. deadline exceeded ->', slow.status, JSON.stringify(await slow.json()));
    await sleep(50);
    console.log('   downstream request was cancelled:', downstreamAborted === 1);

    // 2. The client gives up after 50 ms.
    downstreamAborted = 0;
    const clientAbort = new AbortController();
    setTimeout(() => clientAbort.abort(), 50);
    await fetch(base + '/report', { signal: clientAbort.signal }).catch((err) => console.log('2. client aborted ->', err.name));
    await sleep(100);
    console.log('   downstream request was cancelled:', downstreamAborted === 1);

    // 3. A quick request is unaffected.
    console.log('3. quick request ->', JSON.stringify(await (await fetch(base + '/quick')).json()));

    server.close(); downstream.close();
  });
});

A slow downstream service sees its request cancelled both when the deadline expires and when the client disconnects. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. deadline exceeded -> 504 {"error":"TimeoutError"} downstream request was cancelled: true 2. client aborted -> AbortError downstream request was cancelled: true 3. quick request -> {"ok":true,"deadlineRemainingIsLessThan200":true}

Key points

  • Abort work when the client leaves or the deadline passes.
  • Use AbortSignal.any to combine close and timeout signals.
  • Pass the signal to fetch, timers, streams and fs calls.
  • Cancellation is cooperative; CPU loops must check the signal.
  • Propagate the remaining time to downstream services.

Common mistakes

  • Letting work continue after the client has gone.
  • Calling downstream services with no timeout.
  • Checking the 'close' event of res without checking writableFinished.
  • Retrying until success and ignoring the overall deadline.
  • Assuming a signal stops CPU-bound code by itself.

Follow-ups

  • How does a circuit breaker work together with deadlines?
  • How do you pass the deadline to another service?
  • Why do pg queries need statement_timeout when an AbortSignal exists?

Tips

  • Describe the wasted-work problem first.
  • Name AbortSignal.any.
  • Say that cancellation is cooperative.