Aborting a Fetch Is Client-Side Bookkeeping, Not Cancellation
A user clicks a row in a list, the detail panel opens, and 90 ms later they click a different row. The first request is still in flight. The canonical fix a fre...
A user clicks a row in a list, the detail panel opens, and 90 ms later they click a different row. The first request is still in flight. The canonical fix — a fresh AbortController per effect run, controller.abort() in the cleanup function — is correct, ships in every React tutorial published since 2021, and answers exactly one question: which response is allowed to call setState. It does not answer the question your p99 latency graph is asking, and it does not stop a single unit of work on the machine that matters.
What the Cleanup Actually Guarantees
Start with the strongest version of the pattern, because the weak versions fail for boring reasons and the strong version fails for interesting ones. The important detail is that the controller lives inside the effect body, so each run owns its own signal, and the cleanup aborts the run that created it.
function UserDetail({ userId }: { userId: string }) {
const [record, setRecord] = useState<{ key: string; user: User } | null>(null)
useEffect(() => {
const controller = new AbortController()
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json() as Promise<User>
})
.then((user) => {
if (controller.signal.aborted) return
// Store the key alongside the payload instead of a boolean flag.
setRecord({ key: userId, user })
})
.catch((err: unknown) => {
if (err instanceof DOMException && err.name === 'AbortError') return
if (err instanceof DOMException && err.name === 'TimeoutError') return
setRecord(null)
throw err
})
return () => controller.abort()
}, [userId])
// Structural check: data that does not belong to the current key never renders.
const ready = record !== null && record.key === userId
return ready ? <Profile user={record.user} /> : <Skeleton />
}
Two guarantees come out of this, both local to the tab: a late response cannot overwrite fresher state, and no state update lands on a tree that is already gone. The second one is widely misdescribed — React 18 removed the unmounted-update warning, and writing to state on a dead tree is a no-op, not a leak. The real cost in 2026 is a stale response rendering into a re-mounted tree with different keys.
Where the Abort Stops: A Measured Trace
The abort() call rejects the client promise in single-digit milliseconds and tears down the HTTP/1.1 connection. The server observes something. Your handler is an ordinary async function that nobody told to stop, so it keeps going until it returns.
A 2026 trace on Node 22 and 24, with a handler built from five 500 ms steps, makes the boundary unmissable — the client leaves at 1200 ms:
[ 540ms] server: step 1/5 done (socket.destroyed=false)
[1047ms] server: step 2/5 done (socket.destroyed=false)
[1216ms] client: abort()
[1223ms] client: caught AbortError / code=20
[1225ms] server: res 'close' (writableEnded=false, destroyed=true)
[1548ms] server: step 3/5 done (socket.destroyed=true)
[2562ms] server: step 5/5 done (socket.destroyed=true)
[2567ms] server: res.end() called, no throw
Note the last line. res.end() on a destroyed socket does not throw, so nothing in the naive handler ever learns that the client left. Three of five steps ran for a client that was gone 1.3 seconds earlier. The client promise, the body read, and the TCP connection stop for free; the handler, any downstream HTTP call, and the database query do not.
The Number That Should Change Your Architecture
Twenty clients, each abandoning after 100 ms, against a handler made of five 200 ms steps. The uncancelled server executed 100 of 100 possible steps. The handler wired to the response close event executed 0 of 100 and aborted 20 of 20 handlers.
Those are synthetic localhost numbers, so read them as a shape rather than a forecast. Every abandoned request costs full price: a held connection, a held pool slot, CPU another request wanted, sometimes a held row lock.
Search-as-you-type is the extreme case, because the abandon rate tracks typing speed rather than intent. A 300 ms debounce in front of the fetch cuts it by an order of magnitude and costs nothing at the backend — the request is never created. Debounce plus abort is the correct pair; abort alone is cleanup for requests you should not have started.
PostgreSQL Does Not Read Your Signal
This is the part that surprises people who have already wired the disconnect listener. node-postgres 8.23.1 accepts a { signal } option on query() and ignores it. A query aborted client-side after 300 ms ran to completion in roughly 2 seconds with no error raised. The option merges without complaint, which is worse than rejecting it.
A measured pg_sleep(3) with the client leaving at 500 ms, observed from a second connection:
[ 913ms] client: AbortError
[ 917ms] api: client left
[1227ms] DB: active pg_sleep queries 300ms after client left = 1
[3494ms] api: query finished normally
The database worked for 2.6 seconds on behalf of nobody. For a report query that means a held connection, wasted CPU, and possibly a held lock on a table other sessions want.
Cancellation has to be requested at the database, from a different connection, because the busy one is stuck inside the statement:
const signal = requestSignal(res, { timeoutMs: 5_000 })
const client = await pool.connect()
let listener: (() => void) | undefined
try {
const { rows } = await client.query<{ pid: number }>('select pg_backend_pid() as pid')
const pid = rows[0].pid
if (signal.aborted) {
res.status(504).json({ error: 'deadline exceeded' })
return
}
listener = () => {
// Cancel pool must be separate: a work pool of 2 deadlocks here.
cancelPool.query('select pg_cancel_backend($1)', [pid]).catch(() => {})
}
signal.addEventListener('abort', listener, { once: true })
const result = await client.query('select * from report_slow($1)', [accountId])
res.json(result.rows)
} catch (err) {
const code = (err as { code?: string }).code
if (code === '57014') {
// Cancelled: deadline, disconnect, statement_timeout, or a DBA. Only one is a 504.
if (signal.reason?.name === 'TimeoutError') {
if (!res.destroyed && !res.writableEnded) res.status(504).json({ error: 'timeout' })
return
}
return
}
throw err
} finally {
if (listener) signal.removeEventListener('abort', listener)
client.release()
}
Four details in that block cost real debugging time when they are missing. The cancel goes through a separate pool, because a work pool of two and two abandoned requests produced a hang: both connections held by handlers waiting on a cancel that needed a free connection. The signal.aborted check happens right after reading the pid, since a deadline that already fired never invokes the listener. The listener is removed and the release is deferred, so a connection cannot go back to the pool mid-cancel.
The inverse problem is the one most teams never fix: clients that never disconnect. statement_timeout set to 300 ms raised 57014 after 307 ms in the same test rig. A server-side deadline is the only cancellation that works when the client is a misbehaving script holding a connection open forever.
Aborted Does Not Mean Undone
The most expensive misconception in this whole area is that a client abort rolls back work. A transaction that inserted a row, spent one second on slow work, then committed — with the client leaving at 300 ms — committed through the naive handler. The order existed for a user who had left 700 ms earlier. The cancel-aware handler caught 57014 and rolled back, and the row never appeared.
The cancel interrupts the statement. The rollback is your code, in a catch, written on purpose.
The mirror image is on the client. If you abort a POST, you cannot know whether the server processed it — the request may have been fully written before your abort() landed. A blind retry on a timeout creates a duplicate order. The mitigation is not more cancellation:
// Idempotency key generated once per user intent, reused across retries.
const intentId = crypto.randomUUID()
async function submitOrder(payload: OrderInput, signal: AbortSignal) {
const res = await fetch('/api/orders', {
method: 'POST',
signal,
headers: {
'content-type': 'application/json',
'idempotency-key': intentId,
},
body: JSON.stringify(payload),
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return (await res.json()) as { orderId: string }
}
Server side, the key becomes a unique constraint and the retry returns the original response. That turns an ambiguous outcome into an idempotent one, which is the only thing that makes a retry safe when the first attempt’s fate is unknown. Any endpoint with side effects needs this the moment you add AbortSignal, because you have just made “did it happen?” a question the client cannot answer.
One Signal, Passed Downward
Cancellation does not cross process boundaries on its own. What you want is a single AbortSignal per inbound request that merges “the client left” with “we have waited too long,” then travels through every function that can be stopped.
export function requestSignal(
res: ServerResponse,
{ timeoutMs }: { timeoutMs?: number } = {},
): AbortSignal {
const gone = new AbortController()
res.once('close', () => {
if (!res.writableFinished) gone.abort(new Error('client closed request'))
})
const signals: AbortSignal[] = [gone.signal]
// Must be created per request: a module-level timeout expires once and then
// fails every subsequent request.
if (timeoutMs) signals.push(AbortSignal.timeout(timeoutMs))
return AbortSignal.any(signals)
}
signal.reason tells you which case you are in: a TimeoutError for the deadline, your own error for a disconnect. That distinction needs to reach your logging, because “client went away” and “our query is too slow” are different incidents with different owners.
The version floors matter. AbortSignal.timeout landed in Node 17.3, AbortSignal.any in 20.3 and 18.17. req.signal arrived in Node 24.16 — code that reads it works on 24 and silently does nothing on 22. In the same rig, a hand-wired controller carried cancellation from the browser through the API to a downstream service in about 25 ms, all of it explicit plumbing.
Which produces the design constraint: every function that touches the network takes a signal?: AbortSignal and passes it on. Cancellation is cooperative, so an un-propelled signal is decoration. The type signature is where you enforce that — a fetch wrapper that does not accept a signal should fail code review, not production.
On the client, TanStack Query does this properly and most teams leave it on the table. The queryFn receives a QueryFunctionContext with a signal that the library aborts on key change and unmount. Forwarding it inside your API client is a two-line change that makes every query in the app cancellable.
Cooperative Cancellation Has a Hard Floor
JavaScript cannot interrupt code that is already running. A 1000 ms synchronous loop inside a handler, with the client aborting at 200 ms, produced this: the loop finished at 1061 ms, the disconnect was delivered at 1065 ms, and res.writableFinished came back true.
Read that value again. Node had written the response into a socket whose closure it had not yet noticed, so the check that guards every cancellation helper — if (!res.writableFinished) — reported the client as present when it was 800 ms gone. A blocked event loop does not just delay cancellation; it corrupts the signal you use to detect that cancellation was needed.
The fixes are mechanical and neither is cancellation. Move the work to a worker thread, which can be terminated, or split it into chunks with await between them so the loop can observe the socket. An upload hits the same wall from the other side: aborting mid-transfer truncates the body rather than negotiating it, so a consumer that treats a partial body as complete has a data-integrity bug the abort path cannot fix.
What to Instrument Before You Ship It
Most teams add AbortController, feel finished, and never learn whether backend load changed. Three counters make the question answerable, and all three are cheap.
- Disconnect rate per route — the fraction of inbound requests where the response closed before
writableFinished. That is the population cancellation can save. - Steps executed after disconnect — a counter at each unit of work, compared against the number of aborted handlers. The 100-of-100 versus 0-of-100 result is this metric, and it is the only one that proves the wiring works.
- Ambiguous-write retries — retried POSTs that lacked an idempotency key. This number should be zero, not merely low.
The trade-offs are real. Propagating a signal adds a parameter to every function on the path, and each layer that forgets it breaks the chain silently. Cancellation makes write outcomes ambiguous, forcing idempotency work you may not have budgeted. And a cancelled request a cache or retry policy was counting on simply vanishes, which is how you get a UI that re-fetches forever on a flaky connection.
Against that, the tutorial version of the pattern is fifteen lines and prevents the one bug users actually report — a detail panel showing the wrong record. It is worth every line. It is also the part of the chain where the request has already left your building.
The gap between “the browser stopped listening” and “the system stopped working” is a series of decisions no library makes for you: a close listener, a signal threaded through three services, a cancel issued from a second connection, a rollback written by hand, an idempotency key on the write path. Measure the disconnect rate first. Under a percent, the fifteen lines are enough and the rest is ceremony. In double digits on your busiest route, the fifteen lines are the least interesting code in the request.