Trace which callback runs on the event loop, keep data flow bounded, and make cancellation and shutdown explicit. The examples focus on service behavior under slow dependencies and large inputs.
For: Node.js developers building backend services and data pipelines
Guide scope and versions
Uses built-in Node.js APIs available in current LTS releases. Stream and test-runner options vary across releases; confirm the supported runtime before adopting newer convenience methods.
Question 1 of 10
Why can one CPU-heavy callback slow every request?
JavaScript callbacks on an event loop run to completion. A long synchronous callback delays other queued callbacks on that loop, including unrelated socket and timer work, even if the server has many open connections.
A route parses a multi-megabyte JSON payload synchronously and then returns a response. While parsing runs, that event loop cannot process another callback. Async I/O allows the loop to do other work while waiting; it does not make arbitrary JavaScript CPU work parallel.
First measure event-loop delay and CPU profiles. Then reduce synchronous work, split bounded work across turns when semantics permit, or move CPU-heavy work to worker threads or another process. Splitting alone can still increase total work and complicate cancellation.
JavaScript · Worked example
import { performance } from 'node:perf_hooks';
const input = [1, 2, 3, 4];
function expensiveSynchronousTransform(values) { return values.reduce((sum, value) => sum + value * value, 0); }
const started = performance.now();
const result = expensiveSynchronousTransform(input);
const elapsed = performance.now() - started;
if (result !== 30 || !Number.isFinite(elapsed) || elapsed < 0) throw new Error(`unexpected transform result/timing: ${result}/${elapsed}`);
console.log({ result, elapsedIsNonnegative: elapsed >= 0 });
This measures one callback duration for illustration. Use event-loop delay/utilization and a CPU profile for a service-level diagnosis; this line is not an executed benchmark.
Executed with Node.js v24.14.0.
Follow-up: When would you move work to a worker thread?
When profiling shows CPU-bound JavaScript materially blocks the event loop and the task can be isolated with a manageable message/data-transfer cost. A worker pool needs bounded queueing and shutdown behavior too.
A rejected promise becomes a throw at the await expression, so a surrounding try/catch can handle it. Errors from callbacks that run later are not caught by a try block that already returned; use the callback API's error channel or bridge it to a promise.
A handler awaits a database lookup and then a remote call. Give each operation a meaningful error boundary and let failures reach the HTTP error middleware. Avoid an unhandled rejection that becomes detached from the request lifecycle.
Catching an error is not the same as recovering. If the handler cannot produce a valid response, rethrow or pass the error to the framework's established error path. Do not convert every failure to an empty success result.
The cause preserves the underlying error for diagnostics while adding operation context. Whether a framework serializes or logs cause is a separate boundary decision.
Executed with Node.js v24.14.0.
Follow-up: Should the route return the original database error?
Usually no. Map known domain outcomes to a public response and log internal causes with appropriate access controls. Avoid returning driver messages or SQL details to clients.
How do you export a large file without buffering it all?
Connect a readable source to a writable destination with pipeline, which handles backpressure and propagates stream errors. If writing manually, stop when write() returns false and wait for drain before producing more data.
A report generator writes rows to a slow client. Ignoring a false return from write() keeps accepting chunks into memory while the destination cannot keep up. highWaterMark is a threshold at which backpressure is applied, not a strict process memory limit.
Use stream/promises.pipeline when the pipeline should reject on failure. Decide what a partial output means: writing a file to a temporary path and renaming after success can give different semantics than streaming directly to an HTTP response.
JavaScript · Worked example
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
const sourceBytes = Buffer.from('id,value\n1,alpha\n2,beta\n');
await writeFile('large.csv', sourceBytes);
await pipeline(
createReadStream('large.csv'),
createWriteStream('copy.csv'),
);
const copiedBytes = await readFile('copy.csv');
if (!copiedBytes.equals(sourceBytes)) throw new Error('pipeline output differs from source');
console.log({ bytesCopied: copiedBytes.length, identical: true });
The pipeline connects source and destination while managing backpressure and errors. It is illustrative only; file names and failure cleanup need to match the application.
Executed with Node.js v24.14.0.
Follow-up: What happens if the destination fails halfway through?
The pipeline rejects and destroys participating streams. A file export should remove or mark the partial artifact; an HTTP response may already have sent headers or bytes, so it cannot always be replaced with a clean error response.
Create or receive an AbortSignal, pass it to APIs that support it, and clean up resources when it aborts. Cancellation is cooperative: it cannot undo a side effect already committed or stop an API that ignores the signal.
A client disconnects while a report pipeline is reading and compressing a file. Passing a signal to the pipeline destroys participating streams when aborted. Any database query or external call must separately support cancellation or be isolated behind a bounded operation.
Make cancellation idempotent and define what partial writes mean. Do not treat a timeout at the HTTP layer as proof that a downstream operation stopped; it may finish later and still consume resources or produce side effects.
JavaScript · Worked example
import { createServer } from 'node:http';
const server = createServer((_request, _response) => { received = true; });
let received = false;
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${server.address().port}/data`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5_000);
let cancelled = false;
try {
await fetch(url, { signal: controller.signal });
} catch (error) {
if (error.name !== 'AbortError') throw error;
cancelled = true;
} finally {
clearTimeout(timer);
server.closeAllConnections();
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
}
if (!received || !cancelled || !controller.signal.aborted) throw new Error('real request was not cancelled');
console.log({ received, aborted: controller.signal.aborted, cancelled });
A real Node fetch reaches this local HTTP server, which deliberately holds the response open. The deadline aborts that fetch, and cleanup clears the timer and closes server connections. A production server should also connect caller disconnection to an owned controller and decide how retries interact with cancellation.
Executed with Node.js v24.14.0.
Follow-up: What should a retry do if the caller has already canceled?
Stop scheduling retries and propagate the abort. If an operation may already have committed, use an idempotency key or query its outcome instead of assuming cancellation rolled it back.
Promise.all() observes the promises it receives; it does not schedule or limit the operations that created them. Mapping a large input with an async function can start every operation before Promise.all() waits for their results. Bound the producers when dependency capacity is limited.
A batch job needs to fetch 100,000 records from a rate-limited service. Starting all requests at once can exhaust sockets, memory, and the provider's quota. A fixed worker pool caps in-flight operations; a streaming input source is also needed if the input and results are too large to retain in memory.
The example stops assigning new items after the first observed failure, waits for already-started work to settle, then rejects with that error. It cannot cancel an in-flight work() call unless the function accepts and honors a cancellation signal. Preserving input order may retain later completed results behind a slow earlier task.
JavaScript · Worked example
import { test } from 'node:test';
import assert from 'node:assert/strict';
async function mapBounded(items, limit, work) {
if (!Number.isInteger(limit) || limit < 1) throw new RangeError('limit must be positive');
const results = new Array(items.length);
let next = 0;
let failed = false;
let failure;
async function worker() {
while (!failed) {
const index = next++;
if (index >= items.length) return;
try {
results[index] = await work(items[index]);
} catch (error) {
if (!failed) { failed = true; failure = error; }
}
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
if (failed) throw failure;
return results;
}
test('bounds work and preserves result order', async () => {
let active = 0;
let peak = 0;
const result = await mapBounded([1, 2, 3, 4], 2, async (item) => {
peak = Math.max(peak, ++active);
await Promise.resolve();
active--;
return item * 2;
});
assert.deepEqual(result, [2, 4, 6, 8]);
assert.equal(peak, 2);
});
test('stops assigning after failure and waits for in-flight work', async () => {
const started = [];
let release;
const gate = new Promise((resolve) => { release = resolve; });
const pending = mapBounded([0, 1, 2, 3], 2, async (item) => {
started.push(item);
if (item === 0) throw new Error('item 0 failed');
if (item === 1) await gate;
return item;
});
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(started, [0, 1]);
let settled = false;
pending.finally(() => { settled = true; }).catch(() => {});
await new Promise((resolve) => setImmediate(resolve));
assert.equal(settled, false);
release();
await assert.rejects(pending, /item 0 failed/);
assert.deepEqual(started, [0, 1]);
});
test('rejects an invalid worker bound', async () => {
await assert.rejects(mapBounded([1], 0, async (item) => item), RangeError);
});
Executed on Node.js 24.14.0 with node --test: three tests cover ordered success at a concurrency bound of two, stopping new assignments after an error while waiting for in-flight work, and rejecting an invalid limit. This materializes all input/results and cannot cancel a hung in-flight call.
Executed with Node.js v24.14.0.
Follow-up: How should one failed item affect the batch?
Choose explicitly between fail-fast, collecting per-item outcomes, or retrying selected transient failures. Stop assigning new work after cancellation or fail-fast error, and wait for in-flight work to settle or cancel it safely.
Use AsyncLocalStorage to carry context such as a trace identifier across asynchronous callbacks without threading it through every function. Keep business inputs explicit; ambient context can be harder to test and may be lost at custom callback boundaries.
A request middleware creates a correlation ID and downstream logs need to include it. Store the ID in a request-scoped async context, then read it in logging code. Do not use the store as a hidden dependency container for mutable business state.
Node documents AsyncLocalStorage as the preferred implementation of asynchronous context tracking. Custom thenables, native boundaries, or callback integrations may need care; verify propagation with an integration test using the actual library stack.
JavaScript · Worked example
import { AsyncLocalStorage } from 'node:async_hooks';
const requestContext = new AsyncLocalStorage();
function withRequest(id, handler) {
return requestContext.run({ id }, handler);
}
function currentRequestId() {
return requestContext.getStore()?.id;
}
const id = await withRequest('req-17', async () => {
await Promise.resolve();
return currentRequestId();
});
if (id !== 'req-17' || currentRequestId() !== undefined) throw new Error('async context escaped its request');
console.log({ inside: id, outside: currentRequestId() });
The store is scoped to the asynchronous work created within run. This illustrative wrapper does not prove context propagation through every custom callback API.
Executed with Node.js v24.14.0.
Follow-up: What belongs in the store?
Small request-scoped metadata such as a trace or correlation ID. Keep values immutable where practical and pass domain data explicitly through function parameters.
What should a Node service do after receiving SIGTERM?
Stop accepting new work, mark the instance unavailable, allow bounded in-flight work to finish, close owned resources, and exit before the supervisor's deadline. The exact ordering depends on the HTTP server and orchestrator lifecycle.
A rolling restart sends SIGTERM while requests are active. Close the listening server to stop new connections, apply a shutdown deadline, then close database pools and other clients after handlers settle. If the deadline expires, log what remains and allow the process manager's final termination policy to take effect.
Installing a signal listener changes default process behavior, so the handler must eventually complete shutdown or exit. Avoid an unbounded wait for a stuck dependency; cleanup itself needs a time budget.
JavaScript · Worked example
import { createServer } from 'node:http';
const shutdownOrder = [];
const server = createServer((_request, response) => response.end('ok'));
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
// A synthetic pool records the ordering boundary; no database is contacted.
const database = { async end() { shutdownOrder.push('database.end'); } };
async function shutdown() {
await new Promise((resolve, reject) => {
server.close(error => {
if (error) return reject(error);
shutdownOrder.push('server.close');
resolve();
});
});
await database.end();
}
const stopped = new Promise((resolve, reject) => {
process.once('SIGTERM', () => { void shutdown().then(resolve, reject); });
});
process.kill(process.pid, 'SIGTERM');
await stopped;
if (server.listening || shutdownOrder.join(',') !== 'server.close,database.end') {
throw new Error(`bad shutdown order: ${shutdownOrder}`);
}
console.log(shutdownOrder);
This starts a real local HTTP server and sends SIGTERM to its own Node process. The handler waits for server.close before ending a synthetic database pool. It checks the shutdown ordering, not database-driver behavior or drainage under load. Production code still needs an overall deadline, repeated-signal handling and a policy for upgraded or long-lived connections.
Executed with Node.js v24.14.0.
Follow-up: What if a handler cannot finish before the deadline?
Cancel cooperative work, stop retry loops, and record the unfinished operation. Side effects need idempotency or a durable queue so termination does not turn an uncertain outcome into a duplicate on restart.
How do you test a stream failure after partial output?
Use a deterministic source and destination, force the failure at a known point, and assert both rejection and cleanup behavior. Test the pipeline contract rather than only testing a transform's happy-path function.
A CSV exporter yields a few rows and then its source fails. The pipeline should reject and destroy participating streams. If output is a file, the application should remove or mark the partial artifact; if it is a response, the test should account for bytes already sent.
Keep the fixture in memory and avoid arbitrary sleeps. Add separate cases for an abort signal and a destination error if those paths have different cleanup policies. These tests verify the local contract but do not emulate every network socket behavior.
JavaScript · Worked example
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Readable, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
test('pipeline rejects a source error', async () => {
const source = Readable.from((async function* () {
yield 'partial';
throw new Error('source failed');
})());
const sink = new Writable({ write(_chunk, _encoding, done) { done(); } });
await assert.rejects(pipeline(source, sink), /source failed/);
});
This test was executed with Node.js 24.14.0 using node --test; it proves the in-memory source error rejects the pipeline, not cleanup of a real file or socket destination.
Executed with Node.js v24.14.0.
Follow-up: How would you test cancellation?
Pass an AbortController.signal, abort after the source has yielded a known chunk, then assert rejection and that the underlying resources were destroyed. Use a synchronization signal in the fixture rather than a timing sleep.
How do you distinguish a heap leak from event-loop delay?
Measure the symptom first. Heap snapshots and heap profiles help find retained JavaScript objects; CPU profiles and event-loop delay measurements help locate synchronous work. RSS also includes memory outside the JavaScript heap, such as buffers and native allocations.
A service has rising RSS and slow requests. Compare heap-used, external memory, event-loop delay, CPU, and request latency over the same workload. If heap stays flat while RSS rises, inspect buffers/native memory and dependencies rather than assuming a JavaScript object leak.
Capture profiles under a representative workload and account for diagnostic overhead. A snapshot may pause or consume memory, and a profile from a quiet local process may miss the production path.
JavaScript · Worked example
import { monitorEventLoopDelay } from 'node:perf_hooks';
const histogram = monitorEventLoopDelay({ resolution: 20 });
histogram.enable();
await new Promise((resolve) => setTimeout(resolve, 80));
histogram.disable();
if (!Number.isFinite(histogram.max) || histogram.max <= 0) throw new Error('monitor did not record an event-loop sample');
console.log({ sampleRecorded: true, maxDelayNanoseconds: histogram.max });
Shows the built-in monitor shape only. Production code must convert nanoseconds, reset or window samples, and expose the metric safely; no measurement was collected for this guide.
Executed with Node.js v24.14.0.
Follow-up: What evidence would support CPU-bound event-loop work?
High event-loop delay with a CPU profile showing long JavaScript stacks on the main thread is stronger evidence than high CPU alone. Then isolate the hot function and compare the effect of moving or reducing that work.
What determines whether a Node file is ESM or CommonJS?
Use an explicit module boundary. .mjs selects ECMAScript modules and .cjs selects CommonJS. For ordinary .js files, the nearest package configuration and supported Node release affect interpretation. Do not rely on source syntax alone to document the package contract.
A package with "type": "module" treats its ordinary JavaScript files as ESM; a .cjs file remains CommonJS inside that package. Be explicit so tests, scripts and consumers use the intended loader. Module resolution, package exports and file-extension rules are runtime contracts, not just a choice of spelling between import and require.
ESM and CommonJS interoperate, but not every export shape or initialization sequence is interchangeable. When importing a CommonJS module from ESM, a default import is the reliable representation of its module.exports value; inferred named exports have limits. Dynamic import is available from CommonJS and returns a promise. Support for require of ESM varies with runtime and the module graph, including top-level await. Test against the actual supported Node versions rather than promising universal compatibility.
For a published package, test the consumers you claim to support: a fresh ESM consumer, a CommonJS consumer if supported and an actual package installation using its exports map. A successful local source import does not prove that the packaged entry points or included files work.
The explicit extensions identify both loaders even inside an ESM package. The default import reads the CommonJS export object. The final function demonstrates the asynchronous boundary of dynamic import; it must be called and awaited by its consumer. These are separate files, not one executable concatenation.
Executed with Node.js v24.14.0.
Follow-up: Does switching TypeScript module output automatically fix the runtime boundary?
No. The emitted files, extensions, package type, exports map and supported Node loader must agree. Type checking cannot prove that the deployed package contains the declared runtime entry points.
These are Hacker News job posts that mention these technologies, not employee earnings or a measure of what a skill adds to pay. The amounts summarize annualized advertised minimums in approximate USD. Groups can overlap and differ in roles, locations and dates.
Approximate USD using ECB daily reference rates as of 2026-10-30. Original currencies and offer ranges remain on the source listings. These figures cover posts tagged Node.js, rather than every job in the broader technology family.