The Node.js test doesn't ask for API trivia. It puts you in front of production situations and checks whether you reason from how the runtime works: one thread running your JavaScript, an event loop that must never be blocked, a process that dies on errors nobody handled, memory that only shrinks when nothing points to it. Master these nine ideas and most answers follow on their own.
Study order
If time is short, go in this order.
- The event loop and CPU-bound work
Everything else builds on it: if you understand what blocks the thread, half the situational questions answer themselves.
- Errors, rejections and crashing on purpose
Crashes from unhandled rejections are the most common production surprise in Node, and interviewers love to probe them.
- Memory: heap, leaks and container limits
Requires knowing heap vs RSS and how to investigate, not just «there's a leak».
- Concurrency limits
Ties the event loop to the services you call: how much to send at once, and why.
- Streams and backpressure
The key to handling large payloads without running out of memory.
- Timeouts for slow dependencies
Short to learn and decisive in practice: most cascading failures start with a call that had no deadline.
- Graceful shutdown
Very visible: it separates people who have run services from people who have only written them.
- Dependencies and supply-chain security
Comes up as soon as the conversation turns to security or releases; triage matters more than tools.
- Configuration and secrets
Quick to cover and easy to get wrong: validation at start-up and keeping secrets out of images and logs.
The event loop and CPU-bound work
Your JavaScript runs on one thread. While a callback runs, nothing else does: no other request is parsed, no timer fires, no response is written. Node is fast with I/O because waiting for the network or the disk happens outside that thread; the loop only comes back to run a short callback when the result is ready.
CPU-bound work breaks that deal. Resizing an image, hashing a password synchronously, parsing a 50 MB JSON body or a regular expression that backtracks badly keep the thread busy, and every other request waits behind it. Making the function async changes nothing: async is about waiting, not about running elsewhere.
The remedies, from cheapest to biggest: use the asynchronous version when one exists (crypto.scrypt instead of scryptSync), split the work into chunks that yield with setImmediate, move it to a pool of worker threads, or move it to a separate job or service. And measure: event-loop delay is the metric that tells you the thread is starved.
TypeScript
import { monitorEventLoopDelay } from "node:perf_hooks";
import { Worker } from "node:worker_threads";
// 1. Measure: a p99 delay of tens of milliseconds means something is hogging the thread.
const delay = monitorEventLoopDelay({ resolution: 20 });
delay.enable();
setInterval(() => {
metrics.gauge("event_loop_delay_p99_ms", delay.percentile(99) / 1e6);
delay.reset();
}, 10_000).unref();
// 2. Move CPU work off the main thread: here, making thumbnails of uploaded photos.
function thumbnailInWorker(photo: Buffer, width: number): Promise<Buffer> {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL("./thumbnail-worker.js", import.meta.url), {
workerData: { photo, width },
});
worker.once("message", resolve);
worker.once("error", reject);
});
}In production, reuse a pool of workers (for example with piscina) instead of creating one per task.
Traps
- Believing
async/awaitmoves work to another thread. It doesn't; only I/O happens off the main thread. - Looking only at average latency: a blocked loop shows up in p99 and in event-loop delay first.
- Creating a new worker per request: start-up costs tens of milliseconds and memory. Use a fixed-size pool.
- Raising the libuv thread pool (
UV_THREADPOOL_SIZE) to fix CPU work in your own JavaScript: that pool runs some native I/O and crypto, not your code.
Errors, rejections and crashing on purpose
Since Node 15, a rejected promise that nobody handles terminates the process by default. That's a feature: a process that hit an error nobody planned for may be in a broken state, and carrying on can corrupt data or hang requests forever.
Separate two kinds of errors. Operational errors are expected —a timeout, a 404 from another service, invalid input— and belong to normal code paths: catch them close to where they happen and turn them into a response, a retry or a log line. Programmer errors —reading a property of undefined, a promise nobody awaits— mean the code is wrong; the honest reaction is to log with context, stop accepting work and restart cleanly.
Most unhandled rejections come from promises nobody awaits: fire-and-forget calls, a forEach with an async callback, an EventEmitter with no error listener. Global handlers are the safety net to log and exit, not a place to swallow errors and keep going.
TypeScript
// A promise you don't await still needs its catch, right where you drop it.
void auditLog.write(event).catch((err) => logger.warn({ err }, "audit write failed"));
// An EventEmitter with no 'error' listener throws, and the throw takes the process down.
socket.on("error", (err) => logger.warn({ err }, "client socket error"));
// Last line of defence: log with context, then exit and let the supervisor start a clean process.
process.on("unhandledRejection", (reason) => {
logger.fatal({ reason }, "unhandled rejection");
shutdown(1);
});
process.on("uncaughtException", (err) => {
logger.fatal({ err }, "uncaught exception");
shutdown(1);
});The global handlers log and shut down; they never pretend nothing happened.
Traps
- Using
process.on('unhandledRejection')to ignore errors and keep serving: you hide bugs and leave the process in an unknown state. array.forEach(async ...): forEach doesn't wait and doesn't propagate rejections. Usefor...ofwithawait, orPromise.all.- Throwing strings or plain objects: you lose the stack trace. Always throw
Errorinstances, with acausewhen wrapping. - Running without a supervisor (Kubernetes, systemd, a process manager): crashing on purpose only works if something starts you again.
Memory: heap, leaks and container limits
V8 frees an object only when nothing reachable points to it. A leak in Node is almost never «memory the runtime forgot»: it's a reference you keep without meaning to. The usual suspects are module-level maps and arrays used as caches with no limit, event listeners added on every request and never removed, timers that capture big objects in their closures, and buffers kept around «for later».
Two numbers matter. The heap is where your JavaScript objects live and has a limit (--max-old-space-size); RSS is everything the process uses, buffers and native memory included. In a container, the orchestrator kills the process when RSS crosses the container limit, often before V8 has realised it should try harder to collect garbage. Set the heap limit comfortably below the container's memory.
To find a leak: watch heap usage after garbage collection over hours (a sawtooth that keeps rising is the signature), take two heap snapshots some time apart and compare which object types grew, then follow the retainers back to the code that holds them.
TypeScript
// The leak: a module-level cache keyed by something unbounded (every search term ever typed).
const suggestions = new Map<string, string[]>();
// The fix: bound it. A Map keeps insertion order, so the first key is the oldest.
const MAX_ENTRIES = 5_000;
function remember(term: string, result: string[]) {
suggestions.delete(term); // re-inserting moves it to the end
suggestions.set(term, result);
if (suggestions.size > MAX_ENTRIES) suggestions.delete(suggestions.keys().next().value!);
}
// Start with a heap limit below the container's memory, and a snapshot before it dies:
// node --max-old-space-size=1536 --heapsnapshot-near-heap-limit=2 dist/server.jsBounded caches (with a size limit or a TTL) are the first fix to look for.
Traps
- Raising the memory limit as the fix: a leak just takes longer to kill you.
- Comparing RSS before and after one request: the garbage collector runs when it wants. Look at trends after GC, over time.
- Caching per user or per term with no bound: the number of keys grows with your traffic, forever.
- Taking a heap snapshot on a production instance under load: it pauses the process and can double its memory. Take it out of rotation first.
Concurrency limits
Node makes it very easy to start a thousand operations at once: Promise.all(items.map(callApi)). That's often the problem. The other service gets a burst it may rate-limit or fall over from, your process opens a thousand sockets, and memory holds a thousand responses at the same time.
Doing them one by one, with await inside a for loop, is the opposite mistake: correct and gentle, but the total time is the sum of every latency. The answer in between is bounded concurrency: keep at most N operations in flight, and start the next one when one finishes. N comes from the limits of whatever is on the other side —its rate limit, your connection pool size— not from guesswork.
Think about failures as part of the design. Promise.all rejects on the first error but doesn't cancel the others, which keep running. Promise.allSettled gives you every result so you can report or retry the failures. For long batches, add a timeout per operation and a way to resume.
TypeScript
import pLimit from "p-limit";
// 5,000 welcome emails: not 5,000 connections at once, and not one after another.
const limit = pLimit(10);
const results = await Promise.allSettled(
newUsers.map((user) => limit(() => mailer.sendWelcome(user.email))),
);
const failed = results.filter((r) => r.status === "rejected");
logger.info({ sent: results.length - failed.length, failed: failed.length }, "welcome batch done");A small library such as p-limit keeps at most 10 sends in flight; the rest wait their turn.
Traps
- Sizing concurrency above the connection pool: the extra operations just queue inside the pool, with less visibility.
- Assuming
Promise.allcancels the rest when one fails: they keep running and their results are thrown away. - Retrying failures immediately and all at once: add backoff with jitter, or you recreate the burst.
- Forgetting other instances: 10 per process times 20 pods is 200 concurrent calls to the same API.
Streams and backpressure
A stream moves data in chunks instead of all at once. Reading a big file, an export or an upload as a stream keeps memory flat no matter the size: only a few chunks are in memory at any time.
That only holds if the fast side waits for the slow side. That's backpressure: when a writable's internal buffer passes its highWaterMark, write() returns false, and the producer should stop until the drain event. If you ignore it —for example, writing in a loop without checking— chunks pile up in memory and you've rebuilt the «load it all» problem, just slower.
You rarely have to handle this by hand. pipeline() from node:stream/promises connects the stages, propagates backpressure from the slowest consumer back to the source and, crucially, destroys every stage when one fails, so a client that disconnects doesn't leave a database cursor or a file handle open. Async iteration (for await (const chunk of readable)) also respects backpressure.
TypeScript
import { Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
app.get("/exports/orders.csv", async (_req, res) => {
res.setHeader("content-type", "text/csv; charset=utf-8");
const rows = db.queryStream("SELECT id, total, created_at FROM orders ORDER BY id"); // one row at a time
const toCsv = new Transform({
objectMode: true,
transform(row, _encoding, done) {
done(null, `${row.id},${row.total},${row.created_at.toISOString()}\n`);
},
});
// pipeline pauses the query while the client reads slowly, and destroys every stage on error.
await pipeline(rows, toCsv, res);
});Memory stays flat whether the export has a thousand rows or ten million.
Traps
readable.pipe(writable)without error handling: if one side fails, the other stays open. Preferpipeline().- Calling
write()in a loop and ignoring its return value: that's exactly how backpressure is lost. - Collecting the stream into a buffer «to process it» and then sending it: you're back to loading everything in memory.
- Forgetting that the client can disconnect halfway: with
pipeline()the source is cleaned up; with hand-written code, check forcloseon the response.
Timeouts for slow dependencies
A dependency that is down fails fast: the connection is refused and you move on. A dependency that is slow is far more dangerous, because every request waiting for it keeps its memory, a socket and a slot in some pool for as long as the wait lasts. With enough traffic, a slow neighbour turns into your own outage.
Don't trust the defaults. A plain http.request has no timeout at all, and the defaults behind fetch are measured in minutes, not milliseconds. Give every outgoing call a deadline derived from your own budget: if your endpoint promises an answer in 3 seconds, a call it makes can't be allowed 30. AbortSignal.timeout() sets one in a line, and AbortSignal.any() combines it with a signal that fires when the client disconnects.
A timeout should cancel the work, not just stop waiting for it: Promise.race against a timer returns early but leaves the request running in the background. And decide up front what you answer when the deadline passes —a 504, a cached value, a partial response— because that's part of the design, not an afterthought.
TypeScript
// This endpoint has a 3 s budget; the pricing service gets at most 800 ms of it.
async function quote(productId: string, signal: AbortSignal) {
const res = await fetch(`${PRICING_URL}/quotes/${productId}`, {
signal: AbortSignal.any([signal, AbortSignal.timeout(800)]),
});
if (!res.ok) throw new Error(`pricing answered ${res.status}`);
return res.json();
}
app.get("/products/:id", async (req, res) => {
const cancel = new AbortController();
// The client went away before we answered: stop working for nobody.
res.on("close", () => {
if (!res.writableEnded) cancel.abort();
});
try {
res.json(await quote(req.params.id, cancel.signal));
} catch (err) {
if ((err as Error).name === "TimeoutError") return res.status(504).json({ error: "pricing_timeout" });
throw err;
}
});The deadline cancels the outgoing request, and so does a client that disconnects.
Traps
- Assuming
fetchor your HTTP client gives up after a sensible time: check, and set your own deadline. - Using
Promise.racewith a timer: you stop waiting, but the request keeps its socket and memory until it finishes. - Retrying a timed-out call with the same long deadline: under load that multiplies the traffic towards a dependency that is already struggling.
- Giving each of three sequential calls a 2-second deadline in an endpoint with a 3-second budget.
Graceful shutdown
Processes are stopped all the time: deploys, autoscaling, node rotation. The platform sends SIGTERM, waits a grace period and then sends SIGKILL. What your service does in between decides whether users notice.
The order matters. First stop receiving new work: fail the readiness check so the load balancer takes you out, then stop accepting connections with server.close(). Then let the work in flight finish: requests being served, the message being processed. Only after that, close what those requests needed —database pools, queue connections— and exit. All of it under a deadline shorter than the grace period, so you exit on your own terms instead of being killed mid-response.
Two details trip people up. The load balancer takes a few seconds to notice you're not ready, so new requests can still arrive just after SIGTERM. And HTTP keep-alive connections stay open after server.close(), so idle ones have to be closed explicitly.
TypeScript
let stopping = false;
app.get("/ready", (_req, res) => res.status(stopping ? 503 : 200).end());
process.once("SIGTERM", async () => {
stopping = true; // readiness fails: the platform stops routing new requests here
const deadline = setTimeout(() => process.exit(1), 25_000); // below the platform's grace period
deadline.unref();
server.close(); // stop accepting; requests in flight carry on
server.closeIdleConnections(); // keep-alive sockets with nothing in flight
await consumer.stop(); // finish the message being processed, take no more
await db.end(); // only now close the pool the requests were using
clearTimeout(deadline);
process.exit(0);
});Close in the reverse order you opened: entry points first, dependencies last.
Traps
- Calling
process.exit()straight away on SIGTERM: every request in flight is cut off mid-response. - Starting Node through
npm startor a shell script that doesn't forward signals: your handler never runs. Runnodedirectly or use an init process that forwards them. - Closing the database pool first: requests still in flight fail on their last query.
- Having no deadline: one stuck request keeps the process alive until SIGKILL anyway.
Dependencies and supply-chain security
A typical Node service ships hundreds of packages it never chose directly. Reproducibility comes first: commit the lockfile and install in CI and in images with npm ci, which installs exactly what the lockfile says and fails if it doesn't match package.json. Version ranges in package.json describe what you accept; the lockfile is what you actually run.
When an audit reports a vulnerability several levels down the tree, triage before you panic. Is the package used at runtime or only to build and test? Is the vulnerable function reachable from your code, with input an attacker controls? If it is, the quickest safe fix is often an overrides entry that forces the patched version of that transitive package, tested like any other change and removed once the direct dependency ships its own fix.
Prevention beats firefighting: automated update pull requests in small batches, so a single upgrade is easy to review and revert; few dependencies for small jobs; install scripts disabled where you can; and an eye on packages that suddenly change maintainer or gain a post-install step.
JSON
{
"dependencies": {
"invoice-pdf": "^4.2.0"
},
"overrides": {
"invoice-pdf": {
"xml-lite-parser": "2.3.1"
}
}
}An override pins the patched version of a transitive package until the direct dependency releases its fix. Remove it then.
Traps
- Running
npm installin CI or in the Docker build: it may resolve different versions from the ones you tested. Usenpm ci. - Running
npm audit fix --forcebefore a release: it can jump major versions and break things the audit never mentioned. - Treating every advisory the same: a regular-expression DoS in a build tool and a remote code execution in your HTTP parser are not equally urgent.
- Leaving overrides in place forever: they hide the moment the real fix arrives and drift from what the direct dependency expects.
Configuration and secrets
The same build should run in every environment; only configuration changes. Read it from the environment (variables or mounted files), in one place, once, at start-up, and validate it there: a typo in a variable name should stop the deploy, not surface as undefined in a code path that runs once a week. The rest of the code imports a typed config object and never touches process.env directly.
Secrets are configuration with stricter rules. They never live in the repository, in the Docker image or in a .env file outside your laptop. A secret manager stores them, the platform injects them at runtime, and access is limited to the service that needs them. Plan for rotation from day one: a key you can't change without a deploy and an outage will not get rotated.
Finally, keep secrets out of what you emit. Logging the whole config, the full error of a failed HTTP call with its headers or the environment on start-up are the usual ways a key ends up in a log index that half the company can read.
TypeScript
import { z } from "zod";
// Read and validate once, at start-up: a missing variable stops the deploy,
// not the request at 3 a.m. that happens to need it.
const Config = z.object({
NODE_ENV: z.enum(["development", "test", "production"]),
PORT: z.coerce.number().int().default(3000),
DATABASE_URL: z.string().url(),
PAYMENTS_API_KEY: z.string().min(20), // injected by the platform from the secret manager
PRICING_TIMEOUT_MS: z.coerce.number().int().positive().default(800),
});
export const config = Config.parse(process.env);
// Never log `config` whole: it carries secrets.One validated, typed config object; the rest of the code imports it instead of reading process.env.
Traps
- Branching on the environment name (
if (env === 'production')) instead of on a setting: behaviour then differs in ways no test environment reproduces. - Baking secrets into the image with
ENVorCOPY .env: anyone who can pull the image can read them, layer history included. - Logging error objects from HTTP clients wholesale: many include request headers, and with them the
Authorizationtoken. - Reading
process.env.SOMETHINGdeep in the code: misspell it and you getundefinedsilently, months later.
Common questions
Short answers to the usual doubts.
Do I need to memorise the phases of the event loop?
No. Knowing that timers, I/O callbacks and setImmediate run in different phases helps with an edge case or two, but the test cares about consequences: what blocks the thread, what runs elsewhere, how you'd notice in production.
Worker threads, child processes or a separate service?
Worker threads for CPU work that shares data with the request and finishes in seconds. A child process to run another program. A separate job or service when the work is long, needs its own scaling or must survive a restart of the API.
How do I prepare if I've only used Node with a framework?
Write a tiny service without one: an HTTP server, a SIGTERM handler, a streamed endpoint, a batch job with a concurrency limit. Then break it on purpose —block the loop, leak a map, kill it mid-request— and watch what happens.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Node.js in productionTake the test
- Promises with a concurrency limitSolve the exercise
- Serverless API handlerSolve the exercise