Give a Node.js catalogue request one time budget with AbortSignal.any
Use one budget for headers and the JSON body while keeping caller cancellation separate from timeout. Test five outcomes with a local server.
In this article
Carry the reason back to the workflow
A warehouse page requests a catalogue as JSON. When the user changes warehouses, the previous request can be abandoned. A request for the current warehouse can also run past its time budget. Both cases end the wait, with different outcomes for the page. A request from the previous selection can disappear quietly, while a timeout for the current selection can show a retry button. Separate controllers let the interface own its cancellation decision and the request function own its own budget. The example combines their signals and keeps the same result contract until the JSON body has arrived. An HTTP error and a parsing failure remain visible as distinct outcomes. Keeping the cancellation reason makes it possible to measure timeout frequency without counting ordinary navigation as poor service performance.
Budget for headers and the response body
Fetch can return a Response as soon as the headers arrive. The service may still be writing the JSON body when the first await completes. The example keeps fetch and response.json in the same try block so that one time budget covers both phases. It starts that budget when the function is called. The example does not restart it when the first bytes arrive. You can test a slow body separately from a service that delays headers, and can inspect both phases when an operation is slow. For an unsuccessful HTTP status, the helper cancels the body and returns the status. A caller that needs structured diagnostics from that body can define a bounded read for the expected response format.
export async function loadCatalogue(url, ownerSignal, budgetMs = 1500) {
const deadline = AbortSignal.timeout(budgetMs);
const signal = AbortSignal.any([ownerSignal, deadline]);
try {
const response = await fetch(url, { signal });
if (!response.ok) {
await response.body?.cancel();
return { kind: 'http-error', status: response.status };
}
return { kind: 'ok', catalogue: await response.json() };
} catch (error) {
if (!signal.aborted || (error !== signal.reason && error.name !== 'AbortError')) {
throw error;
}
return {
kind: signal.reason === deadline.reason ? 'timeout' : 'cancelled',
reason: signal.reason
};
}
}
Keep the first cancellation reason
Each operation creates a timeout signal. The interface owns the other controller and can pass its signal to any outstanding reads it needs to stop together. AbortSignal.any composes the input signals and retains the reason of the first to abort. If several inputs have already aborted, the order of the inputs determines the selected reason. The example checks the resulting reason against the reason of the timeout signal itself. That preserves the caller’s cancellation even if the caller supplies an error whose name happens to be TimeoutError. A failure from an unresponsive network or invalid JSON continues to throw when the composed signal is still active. Testing the exact reason object makes the result independent of localized exception messages.
Exercise the behavior with a loopback server
The test server listens on a free loopback port. A successful route immediately sends a small JSON document. A second route flushes the headers and starts sending the body, then waits before finishing the JSON. The read is expected to return timeout while that response is still incomplete. Another assertion passes an already cancelled user signal and checks that the helper returns its original reason. The last route sends incomplete JSON and must yield a SyntaxError. The server clears its timer if the test request closes and shuts down at the end of the suite. These cases exercise real Node fetch behavior locally without an external dependency. Generous time margins keep the check focused on the ordering of events across machines.
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { loadCatalogue } from './catalogue.mjs';
const server = createServer((request, response) => {
if (request.url === '/missing') {
response.writeHead(404).end('not found');
return;
}
response.writeHead(200, { 'content-type': 'application/json' });
if (request.url === '/slow-body') {
response.write('{"stock":');
const timer = setTimeout(() => response.end('7}'), 3500);
response.on('close', () => clearTimeout(timer));
return;
}
response.end(request.url === '/invalid' ? '{"stock":' : '{"stock":7}');
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const origin = 'http://127.0.0.1:' + server.address().port;
try {
const user = new AbortController();
assert.deepEqual(await loadCatalogue(origin, user.signal), {
kind: 'ok', catalogue: { stock: 7 }
});
assert.deepEqual(await loadCatalogue(origin + '/missing', user.signal), {
kind: 'http-error', status: 404
});
const timedOut = await loadCatalogue(origin + '/slow-body', user.signal, 900);
assert.equal(timedOut.kind, 'timeout');
assert.equal(timedOut.reason.name, 'TimeoutError');
await assert.rejects(loadCatalogue(origin + '/invalid', user.signal), SyntaxError);
const reason = new DOMException('Warehouse selected', 'TimeoutError');
user.abort(reason);
assert.deepEqual(await loadCatalogue(origin, user.signal), { kind: 'cancelled', reason });
console.log('Success, HTTP error, body timeout, invalid JSON, caller cancellation: passed');
} finally {
server.closeAllConnections();
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
}
Apply only the response for the active selection
Picture a request for warehouse A which completes at the moment the user chooses warehouse B. Aborting A may arrive after its result is already available. Give each selection an incrementing identifier and verify it before using the response to update the page. This is especially important when one handler renders success and another renders errors. Both handlers should update only the current selection. A retry for the active selection should create a fresh timeout signal and use the same captured warehouse ID. The outer workflow can use another signal if it needs a budget across several individual operations. Each operation has its own timeout and an already aborted controller cannot be reset for the next selection.
Tie metrics and retries to the operation
A catalogue read can use a bounded retry policy for temporary errors. A write has a different outcome to consider. The server may finish a payment or an order while the client waits for a body, and a client timeout cannot tell whether it committed. A retry decision for that operation depends on an idempotency key or a status endpoint the service actually supports. Client telemetry can record the request type, HTTP status, time through the body and retry count without retaining the response or arbitrary user-supplied reason text. Keep the user-cancelled, timed-out, HTTP-error, parse-error and successful outcomes distinguishable. Measure time through headers and time through the body before enlarging the budget. Each phase gives you a different place to investigate.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment