Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right
Half the CPU your API burns under load is spent on requests the client already gave up on. Here is the AbortController pattern that propagates a single cancellation signal through your entire Node.js stack — HTTP, database, fetch — with the 60 lines you actually have to write and the three traps that keep teams from getting the win.
Open a flame graph of any moderately busy Node.js API and you will find something embarrassing: a meaningful slice of the CPU is being spent on work for HTTP requests that the client closed three seconds ago. The browser navigated away. The mobile app retried. The load balancer hit its idle timeout. But your handler is still happily querying Postgres, calling a downstream service, parsing the JSON response, and writing a 200 OK to a socket nobody is listening on.
This is not a hypothetical. On a real production service I worked on, propagating cancellation end-to-end shaved 22% off median CPU during peak hours. Not because we wrote faster code. Because we stopped writing code at all for requests nobody wanted.
The fix is AbortController. It is in the Node.js standard library since 16, supported by fetch, supported by pg, supported by Express via req.signal, and almost nobody wires it through. Here is the pattern that does, the 60 lines that make it work, and the three traps that make teams give up halfway.
The shape of the problem
A normal Express handler that calls a database and a downstream API looks like this:
app.get('/api/orders/:id', async (req, res) => {
const order = await db.query('SELECT * FROM orders WHERE id = $1', [req.params.id]);
const shipping = await fetch(`https://shipping.internal/track/${order.tracking_id}`);
const data = await shipping.json();
res.json({ order, shipping: data });
});
Now imagine the client is on flaky 4G. They tap, wait two seconds, get bored, tap again. The first request is still mid-flight. Without cancellation:
- Postgres finishes the
SELECT(300ms). - The downstream
fetchruns to completion (1.2s). JSON.parseruns.res.jsonwrites to a closed socket and throws or silently swallows.- Repeat for the second tap, which the client also abandons.
You did the work three times. You paid for three database queries, three downstream calls, three JSON parses. The client got nothing. Multiply by every flaky connection on the internet.
The AbortController pattern says: every async operation in the request takes a signal, and when the request closes, the signal fires, and every operation aborts cooperatively. No CPU spent on dead work, no connections held open against your downstreams, no event-loop time on JSON for nobody.
The 60 lines
Three pieces. The middleware that produces a signal from each request. The handler convention that uses it. A small wrapper for the few async APIs that still don’t accept a signal natively.
// abort-middleware.ts
import type { Request, Response, NextFunction } from 'express';
declare module 'express-serve-static-core' {
interface Request {
signal: AbortSignal;
}
}
export function abortOnClientDisconnect(req: Request, res: Response, next: NextFunction) {
const controller = new AbortController();
// Express attaches the underlying socket; 'close' fires when the client
// disconnects before the response is fully sent. 'aborted' is the older
// event — keep both for compatibility with proxies that emit one or the other.
const onClose = () => controller.abort(new Error('client_disconnected'));
req.on('close', onClose);
req.on('aborted', onClose);
// Cleanup so we don't leak listeners on long-lived servers.
res.on('finish', () => {
req.off('close', onClose);
req.off('aborted', onClose);
});
req.signal = controller.signal;
next();
}
// db.ts — pass the signal through to the database client
import { Pool } from 'pg';
const pool = new Pool({ /* ...config... */ });
export async function query<T>(sql: string, params: unknown[], signal?: AbortSignal): Promise<T[]> {
const client = await pool.connect();
// Hook the abort to a server-side query cancel. This is the part most
// teams skip — and it is the part that actually frees the database.
const onAbort = () => {
// pg exposes a low-level cancel via the connection. It sends a
// CancelRequest to Postgres on a separate socket and the running query
// aborts with code 57014 (query_canceled). Without this, the JS Promise
// rejects but Postgres keeps churning.
(client as any).connection?.cancel?.();
};
signal?.addEventListener('abort', onAbort, { once: true });
try {
const res = await client.query(sql, params);
return res.rows as T[];
} finally {
signal?.removeEventListener('abort', onAbort);
client.release();
}
}
// handler.ts — the convention
import { query } from './db';
app.get('/api/orders/:id', async (req, res) => {
try {
const orders = await query<Order>(
'SELECT * FROM orders WHERE id = $1',
[req.params.id],
req.signal,
);
if (!orders[0]) return res.status(404).json({ error: 'not_found' });
// fetch supports AbortSignal natively — just pass it through.
const shipping = await fetch(
`https://shipping.internal/track/${orders[0].tracking_id}`,
{ signal: req.signal },
);
res.json({ order: orders[0], shipping: await shipping.json() });
} catch (err: any) {
if (err.name === 'AbortError' || err.code === '57014') {
// Client gave up. Don't bother responding — the socket is gone.
// Don't log this as an error, either; it isn't one.
return;
}
throw err;
}
});
That is the entire pattern. Wire abortOnClientDisconnect once at the top of your middleware chain, take a signal parameter in any function that does async I/O, pass it through to fetch, pg, redis, mongodb, and your own service-to-service calls. Done.
Why each piece is there
This pattern looks deceptively simple, and the small choices in it are the difference between cancellation that actually frees resources and cancellation that just makes the JavaScript Promise reject while the database keeps grinding.
req.signal, not a parameter on every handler. You could pass signal explicitly through every layer. In a real codebase, half the layers will forget. Putting signal on the request object turns it into an ambient property — every handler has it, every util that takes a req has it, and there is no way to “forget” without obviously dropping it. (For non-Express stacks, use AsyncLocalStorage the same way structured logging does. The principle is identical.)
Both 'close' and 'aborted' events. Different proxies, different Node versions, and different HTTP/2 vs HTTP/1.1 paths fire one or the other inconsistently. Listening for both costs nothing and avoids the bug where cancellation works in dev (HTTP/1.1) and silently fails behind your edge proxy (HTTP/2). When a client disconnects you want to know, not maybe-know.
Cleanup on 'finish'. Without req.off, every long-lived process accumulates listeners on every closed request. In a service handling 1000 req/s, that is 1000 leaked listeners per second. Node will warn at 11 listeners on the same emitter — but the bigger issue is that those listeners hold references to the closed-over controller, which holds references to whatever else closed over the request. Memory creeps. Cleanup is one line, and you only forget it once before you learn.
The actual database cancel. This is where most teams’ “cancellation” is a lie. The Postgres protocol supports CancelRequest: a separate connection that tells the server “abort the query running on connection X.” Without sending it, your await client.query() will reject immediately when the abort signal fires, but the server-side query keeps running until it completes, holding its row locks and connection. You freed the JavaScript stack frame and nothing else. The 4-line onAbort block above is the entire reason this pattern actually saves real CPU and database load. Confirm it works by killing a long-running query from a client and running SELECT pid, state, query FROM pg_stat_activity — the row should disappear within a second.
Returning early on AbortError. When the signal fires, every promise in the chain rejects. You catch it and… do nothing. Don’t write to res (the socket is closed; you’ll throw ERR_STREAM_WRITE_AFTER_END). Don’t log it as an error (it’s a normal lifecycle event, and your error budget will look terrible if every flaky connection counts as a 5xx). Just return.
err.code === '57014'. Postgres returns SQLSTATE 57014 for query_canceled. Catching it as a non-error is the difference between a clean dashboard and one that lights up red every time someone closes their laptop on the train.
The three traps that kill the pattern
Most teams who try this give up about a week in, because the pattern looks like it works in dev and silently doesn’t work in production. The three reasons it silently doesn’t work:
Trap 1: A library swallows the signal. You pass signal to your wrapper, your wrapper calls some ORM, the ORM calls pg, but the ORM’s API doesn’t have a place to put a signal — so it doesn’t propagate. The query runs to completion. From your side, everything looks correct: the Promise rejects, the metric counts as an abort. Under the hood, you bought nothing.
The fix is to audit at the boundary. Pick one of your real endpoints, add a deliberate 5-second sleep on the database side (pg_sleep(5)), trigger the request, and Ctrl-C it. Then immediately query pg_stat_activity. If the sleep is still running, the signal isn’t reaching Postgres. Either drop the ORM for that hot path, contribute a PR upstream, or use the lower-level pg directly with the cancel hook above.
Trap 2: The signal arrives but the handler isn’t listening between awaits. This one is subtle. JavaScript is single-threaded. While your handler is await-ing one slow operation, the abort fires — but if the next operation does not itself accept a signal, it runs to completion before the chain can react. A common offender is a synchronous CPU-bound loop, like a 200ms JSON parse or a regex over a large payload. Cancellation has no effect on synchronous code. If you have a hot path with a slow synchronous step, break it up with setImmediate or move it to a worker that itself accepts a signal.
Trap 3: The downstream service doesn’t cancel either. You pass signal to fetch, the abort fires, your fetch Promise rejects — and the downstream HTTP server keeps processing the request anyway. From your service’s perspective, you saved local CPU. From the system’s perspective, you saved nothing: the downstream still ran the query, called the next downstream, etc. Cancellation is a chain. It only works if every link honors it.
The fix here is policy, not code: every internal service in your fleet should set up abortOnClientDisconnect on day one, the way every service ships with structured logging on day one. Otherwise you’re paying for cancellation locally and not seeing the system-wide win.
What to actually measure
The pattern is not done when the code merges. It is done when the metrics show the win. Three numbers to watch:
http.client_disconnected_during_handler per minute. This is your aborted-request rate. If it is 0, you are probably not detecting disconnects (Trap 1, on your own service). If it is 5–15% of total requests, that is normal for a public API on consumer internet. If it spikes during an outage, that is a leading indicator: clients are giving up because something is slow.
Database query_canceled rate. Pull this from pg_stat_database (xact_commit vs cancellations) or from your APM. Before this pattern, this number is near zero. After, it should roughly match your client_disconnected rate. If it doesn’t, Trap 1 is in play — your cancels aren’t reaching the database.
Median and p99 CPU during peak. This is the number that justifies the work. After full propagation, both should drop. The median drops because you’re not running pointless work on the average request. The p99 drops because the abandoned requests of one slow user no longer block the event loop’s attention from another user’s healthy request. On the production service I mentioned at the top, p99 latency dropped 40% — not because anything got faster, but because the queue behind it got shorter.
Common mistakes once it’s wired
A few small things that don’t break the pattern but waste its benefits:
Calling controller.abort() with a string instead of an Error. Some downstream libraries inspect err.name === 'AbortError'. If you abort with a string, they get a string at the catch site and your err.name check silently fails. Always abort with an Error (or no argument, in which case Node creates an AbortError for you). Don’t get clever.
Adding signal to a function that has no I/O. A pure CPU function with no async cannot cooperate with a signal. Adding signal to its parameters is harmless but misleading; the next person to read the code will assume it cancels and it won’t. Reserve the convention for functions that actually await something.
Forgetting that setTimeout doesn’t cancel by default. setTimeout(fn, 1000) keeps the event loop alive and the handler pinned. If you must wait, use setTimeout(fn, 1000, { signal }) (Node 17+) or await new Promise((r, j) => { const t = setTimeout(r, 1000); signal.addEventListener('abort', () => { clearTimeout(t); j(signal.reason); }); }). Yes, ugly. Yes, mandatory if you don’t want sleepers to outlive their requests.
Treating cancellation as the same thing as a timeout. They are not. A timeout is your policy: “this operation has 5s and then I give up.” A cancellation is the client’s policy: “I no longer want this.” A well-built service has both. Use AbortSignal.timeout(5000) for the first and AbortSignal.any([req.signal, AbortSignal.timeout(5000)]) (Node 20+) when you want either condition to fire. The combinator is what gives you both timeouts and cancellation in a single signal that everything downstream already knows how to handle.
When not to bother
This pattern earns its keep on services with:
- High request volume (a few hundred req/s and up).
- Slow downstream calls (anything that talks to another HTTP service or a non-trivial query).
- Public-facing clients (browsers and mobile apps; internal callers usually retry deterministically).
If you run a small internal admin tool with three users a day, the wiring is overhead and the win is unmeasurable. If you run a public API hitting four-figure RPS with downstream calls in the half-second range, this is one of the highest-leverage refactors you can do. The 60 lines pay for themselves in the first peak hour.
The takeaway
Cancellation in Node.js is a complete, working, in-the-stdlib feature that almost nobody propagates end-to-end. The pattern is small: one middleware, one handler convention, one wrapper around any I/O library that doesn’t take a signal natively. The wins are real and measurable: less CPU, less database load, less downstream traffic, lower p99.
The reason teams skip it is that it works “well enough” without — the Promise rejects, the request looks done, the dashboards don’t scream. The hidden cost shows up as paying for compute that produces nothing. Once you flame-graph it once and see the wedge of dead work, you don’t go back.
Wire req.signal end-to-end. Verify the database actually cancels. Don’t log aborts as errors. The next time half your users are on a flaky train tunnel, your service will notice and stop working on requests they no longer want — which is the entire job.
A note from Yojji
The kind of work this post describes — propagating cancellation through an entire async stack, verifying the database actually frees its locks, reading a flame graph to find the wedge of dead CPU — is the difference between a service that survives a real production load and one that quietly burns money. It is also the kind of unglamorous backend craft Yojji has been shipping since 2016.
Yojji is an international custom software development company with offices in Europe, the US, and the UK. Their teams specialize in the JavaScript stack (React, Node.js, TypeScript), cloud platforms (AWS, Azure, Google Cloud), and microservices architectures, and they run dedicated senior outstaffed teams alongside full-cycle product engagements covering discovery, design, development, QA, and DevOps.
If you would rather hire the practice of building reliable, well-instrumented Node.js services than learn it the hard way after a peak-hour CPU alert, Yojji is worth a conversation.