On this page

Node.js Interview Questions

Node.js interviews go beyond JavaScript. They test whether you understand how the runtime works — the event loop, the thread pool, memory management, and the streaming model that makes Node capable of handling thousands of concurrent connections on a single thread. This page covers the questions that matter.

How to use this page

Questions are grouped by level — Junior (runtime model, modules, errors, buffers, tooling), Senior (ordering puzzles, libuv, streams, concurrency, memory, interop, testing, security, shutdown) and Staff (permission model, profiling, scaling, observability, incident design) — then by topic. Each has an answer, a runnable example, the common wrong answer or trap, and the interviewer's usual follow-up. Every ordering puzzle was run on Node 22 and shows the real output; where the order is non-deterministic, the page says so.

Versions as of November 2026

Node.js 26 (Lithium), 24 (Krypton) and 22 (Jod) are the supported LTS lines; Node 20 reached end-of-life in spring 2026, and v27 is in alpha. Starting with Node.js 27 the project moves to one major release per year, and every major becomes LTS — the old "even = LTS, odd = short-lived" rule ends with 26 (nodejs.org release schedule). In an interview, "we run the Active LTS line and upgrade once a year" is the expected production answer.


Junior

Runtime Basics

Q: What is Node.js, and how does a single thread handle thousands of connections?

Node.js is a JavaScript runtime built from three pieces: V8 (Google's JavaScript engine, which compiles and runs your code), libuv (a C library that provides the event loop, async I/O and a thread pool) and Node's own C++ bindings and JavaScript standard library (fs, http, stream, crypto…).

Your JavaScript runs on one main thread. That thread never waits for I/O. When you call socket.write() or fs.readFile(), Node hands the operation to the operating system (sockets, via epoll/kqueue/IOCP) or to libuv's thread pool (files, DNS, some crypto), registers a callback, and returns immediately. When the operation completes, the callback is queued, and the event loop runs it when the main thread is free.

That is why Node is excellent for I/O-bound workloads — an API server spends most of its time waiting on databases and networks, and 10,000 idle sockets cost only memory, not threads. It is also why Node is bad at CPU-bound work on the main thread: while your code is computing, nothing else runs.

// Run: node server.js, then: curl localhost:3000/fast and curl localhost:3000/slow
const http = require('node:http');

http.createServer((req, res) => {
  if (req.url === '/slow') {
    const end = Date.now() + 3000;
    while (Date.now() < end) {} // CPU-bound: blocks EVERY other request for 3 s
    return res.end('slow done\n');
  }
  // I/O-bound: the thread is free while the timer is pending
  setTimeout(() => res.end('fast done\n'), 100);
}).listen(3000);

Hit /slow and then /fast in another terminal: /fast waits until /slow finishes. That one experiment explains the whole runtime model.

Common wrong answer / trap: "Node is single-threaded." Only your JavaScript is (per isolate). A Node process has several threads: the main thread, four libuv pool threads by default, V8's GC and compiler helper threads, and any worker_threads you start. The accurate phrasing is "Node runs JavaScript on a single thread per event loop."

Follow-up: "So how do you use all CPU cores?" — Run several processes (cluster, a process manager, or more container replicas) for throughput, and worker_threads for CPU-heavy tasks inside one process. Both are covered in the Senior section.

Q: Explain the Node.js event loop phases in detail.

The event loop is a semi-infinite loop that processes callbacks in a specific order. Each iteration is called a "tick." There are six phases, and each phase has a FIFO queue of callbacks to execute.

graph TD
    START["Event Loop Tick Starts"] --> T["1. Timers<br/>setTimeout, setInterval"]
    T --> PC["2. Pending Callbacks<br/>Deferred I/O callbacks"]
    PC --> IP["3. Idle / Prepare<br/>Internal use only"]
    IP --> POLL["4. Poll<br/>Retrieve new I/O events<br/>Execute I/O callbacks"]
    POLL --> CHECK["5. Check<br/>setImmediate callbacks"]
    CHECK --> CLOSE["6. Close Callbacks<br/>socket.on('close')"]
    CLOSE --> START
    MQ["Drain Microtask Queue<br/>(process.nextTick, then Promises)<br/>after EVERY callback in every phase"]
    T -.-> MQ
    POLL -.-> MQ
    CHECK -.-> MQ
    CLOSE -.-> MQ

    style POLL fill:#059669,color:#fff
    style MQ fill:#7c3aed,color:#fff
PhaseCallbacks ProcessedKey Detail
TimerssetTimeout, setIntervalExecutes callbacks whose timer has elapsed. Not guaranteed to fire at exact time — just "no sooner than."
Pending CallbacksDeferred I/O callbacksSystem-level callbacks (e.g., TCP errors like ECONNREFUSED).
Idle / PrepareInternal onlyUsed by Node internals. Not accessible to user code.
PollI/O callbacksThe phase where Node spends most time. Retrieves new I/O events from the kernel and runs their callbacks. If no timers are scheduled, it will block here waiting for I/O.
ChecksetImmediateRuns immediately after the poll phase completes.
CloseClose handlerssocket.on('close', ...) when a handle is closed abruptly (e.g. socket.destroy()).

Between every phase, Node drains the microtask queue:

  1. process.nextTick callbacks (highest priority)
  2. Promise .then/.catch/.finally callbacks

Correction (2026-11-09): Since Node 11, the microtask queues are drained after each individual callback, not only once between phases (the earlier diagram showed a single drain after the close phase). Two setTimeout(…, 0) callbacks that each schedule a promise will run timer → its promise → timer → its promise — see the puzzle in the Senior section. The close phase also does not run process.on('exit'); 'exit' is a process event emitted synchronously when the process is about to exit, after the loop has stopped. And a gracefully closed socket emits 'close' via process.nextTick; only abrupt closes go through the close phase (Node.js event loop guide).

Correction (2026-11-09): Starting with libuv 1.45.0 (Node.js 20), timers run after the poll phase in each iteration instead of before it. For backwards compatibility libuv still runs timers once before entering the loop. The six-phase table above is still the right mental model; just know that on modern Node the "timers" step sits at the end of the cycle (after poll/check/close) rather than the start, which can change how setImmediate and timers interleave in edge cases.

// Run: node phases.js — prints one line per phase, in phase order
const fs = require('node:fs');
const net = require('node:net');

fs.readFile(__filename, () => {                       // poll phase
  console.log('poll: readFile callback');
  setImmediate(() => console.log('check: setImmediate'));
  setTimeout(() => console.log('timers: setTimeout 0'), 0);
  const sock = net.connect(1); // nothing listens on port 1
  sock.on('error', () => {});
  sock.on('close', () => console.log('close: socket close'));
  sock.destroy();
});
// Typical output:
// poll: readFile callback
// check: setImmediate
// close: socket close
// timers: setTimeout 0

Common wrong answer / trap: Listing "microtask queue" as a seventh phase, or saying promises "run in the timers phase." Microtasks are not a phase; they run in between callbacks whenever the JavaScript stack empties. The other trap is claiming setTimeout(fn, 0) means "run now" — it means "no sooner than 1 ms, at the next timers step."

Follow-up: "When does the poll phase block, and for how long?" — If there are no immediates queued, poll blocks waiting for I/O, but only up to the time the nearest timer is due. With no timers, no immediates and no active handles, the loop exits and the process ends.

Q: process.nextTick vs setImmediate

The names are backwards from what they do. process.nextTick does not wait for the next tick of the loop — it runs as soon as the current JavaScript operation finishes, before any promise callbacks and before the loop moves on. setImmediate is not immediate — it runs in the check phase, after the current poll phase.

// process.nextTick — fires BEFORE the event loop continues
// setImmediate — fires in the CHECK phase (after poll)

setImmediate(() => console.log('setImmediate'));
process.nextTick(() => console.log('nextTick'));
// Output: nextTick, setImmediate

// Recursive nextTick can STARVE the event loop
function danger() {
  process.nextTick(danger); // Never lets the loop advance to I/O
}
// This blocks all I/O, timers, and setImmediate callbacks

process.nextTick Can Starve I/O

Recursive process.nextTick prevents the event loop from reaching the poll phase. Use setImmediate for recursive/deferred work that should not block I/O.

When should you use nextTick at all? Mostly in library code that must emit an event after the caller had a chance to attach listeners, while still being "synchronous enough" to beat any I/O:

const { EventEmitter } = require('node:events');

class Job extends EventEmitter {
  constructor() {
    super();
    // Emitting synchronously here would fire before the caller's .on('start')
    process.nextTick(() => this.emit('start'));
  }
}
new Job().on('start', () => console.log('listener saw start')); // prints

The Node docs recommend queueMicrotask() or setImmediate() over nextTick for new code because they are standard and easier to reason about.

Common wrong answer / trap: "nextTick runs on the next iteration of the loop and setImmediate runs immediately." It is the exact reverse. A second trap: thinking nextTick and promises share one queue — they are two queues, and the whole nextTick queue empties before the promise queue starts.

Follow-up: "How would you break a long CPU loop into chunks so I/O still gets served?" — Process a batch, then schedule the next batch with setImmediate (not nextTick), so the poll phase runs between batches.

Q: What is the output?

const fs = require('fs');

// Main module context
setTimeout(() => console.log('T1'), 0);
setImmediate(() => console.log('I1'));
// Order is NON-DETERMINISTIC — depends on whether 1ms timer
// has elapsed by the time event loop reaches the timers phase

// Inside an I/O callback — order IS deterministic
fs.readFile(__filename, () => {
  setTimeout(() => console.log('T2'), 0);
  setImmediate(() => console.log('I2'));
});
// Always prints: I2, T2
// Because: after I/O callback runs (poll phase),
// check phase (setImmediate) comes BEFORE timers phase

Running only the main-module pair ten times on Node 22 printed IT TI IT IT IT IT IT IT IT IT — mostly immediate first, but not always. setTimeout(fn, 0) is clamped to 1 ms; whether 1 ms has passed by the time libuv first checks timers depends on how long process start-up took and on machine load. Inside an I/O callback you are in the poll phase, so the check phase is always next.

Common wrong answer / trap: Giving a single confident order for the main-module case. The correct answer is "it depends — and here is why." Interviewers ask this precisely to see if you know it is racy.

Follow-up: "How would you make T1 reliably run after I1 from the main module?" — Schedule the timer from inside the immediate (or from an I/O callback). Don't build logic on the race.

Q: Puzzle — nextTick, promises, queueMicrotask and timers in one script

// Run: node p1.js  (CommonJS file)
console.log('A');
setTimeout(() => console.log('B'), 0);
setImmediate(() => console.log('C'));
process.nextTick(() => console.log('D'));
Promise.resolve().then(() => console.log('E'));
queueMicrotask(() => console.log('F'));
process.nextTick(() => console.log('G'));
console.log('H');

Verified output: A H D G E F B C (the last two can swap — see the previous question).

  1. A, H — synchronous code runs to completion first.
  2. D, G — the nextTick queue drains first, in FIFO order.
  3. E, F — then the promise microtask queue; queueMicrotask uses the same queue as promise reactions, so it keeps insertion order.
  4. B, C — macrotasks: the timer and the immediate, in racy order from the main module.

Common wrong answer / trap: Putting F before E because "queueMicrotask is faster," or putting D/G after E/F because "they're all microtasks." nextTick is its own, higher-priority queue.

Follow-up: "Does the answer change if the file is an ES module?" — Yes. See the ESM ordering puzzle in the Senior section: in an .mjs file the promise prints before the nextTick.

Modules

Q: require vs import — CommonJS vs ES modules

CommonJS (require)ES modules (import)
LoadingSynchronous, at the point require() runsParsed and linked first, then evaluated; supports top-level await
Exportsmodule.exports object, resolved at runtimeStatic, named bindings known before evaluation
BindingsA copy of the value at the time of require (for primitives)Live bindings — importers see updates
Tree-shakingHard (dynamic)Easy (static)
__dirname, __filenameAvailableUse import.meta.dirname / import.meta.filename (Node 20.11+)
File extension in specifiersOptionalRequired for relative imports (./x.js)
Strict modeOpt-inAlways on
// counter.mjs
export let count = 0;
export function inc() { count++; }

// main.mjs — run: node main.mjs
import { count, inc } from './counter.mjs';
inc();
console.log(count); // 1 — live binding, not a snapshot

The same thing with CommonJS (module.exports = { count, inc }) prints 0, because count was copied into the exports object when the module evaluated.

Common wrong answer / trap: "ESM is asynchronous so it's slower." Loading is graph-based and async-capable, but once loaded the code runs at the same speed. Another trap: "you can't mix them." You can — with rules (see ESM/CJS interop in the Senior section).

Follow-up: "Which would you pick for a new library in 2026?" — ESM-first. Since require(esm) is enabled by default in every supported LTS line (see below), an ESM-only package is now consumable from CommonJS as long as it has no top-level await, which removes the main reason for dual-publishing.

Q: How does Node decide whether a file is CommonJS or ESM?

Node looks at, in order: the file extension (.mjs → ESM, .cjs → CJS), then the nearest package.json "type" field for .js files ("module" → ESM, "commonjs" or missing → CJS). Since Node 22.7 / 20.19-era releases, Node also has syntax detection: a .js file with no "type" that contains import/export syntax is retried as ESM instead of failing.

mkdir demo && cd demo
echo '{ "type": "module" }' > package.json
echo 'export const x = 1; console.log(import.meta.url)' > a.js
node a.js          # works: .js is ESM because of "type": "module"
echo 'console.log(typeof require)' > b.cjs
node b.cjs         # function — .cjs is always CommonJS

Common wrong answer / trap: Relying on syntax detection in published packages. It costs an extra parse and emits a warning in some versions; set "type" explicitly. Also: "type" affects only .js files in that package scope, not .mjs/.cjs.

Follow-up: "What does the "exports" field do?" — It defines the public entry points of a package (including conditional "import"/"require" targets) and blocks deep imports of anything not listed.

Errors

Q: How should you handle errors in Node.js?

There are five channels through which errors arrive, and each needs its own handling:

// 1. Synchronous — try/catch
try {
  JSON.parse(invalidJSON);
} catch (err) {
  console.error('Parse failed:', err.message);
}

// 2. Callbacks — error-first pattern
fs.readFile('/path', (err, data) => {
  if (err) {
    console.error('Read failed:', err.message);
    return;
  }
  processData(data);
});

// 3. Promises — .catch or try/catch with await
try {
  const data = await fs.promises.readFile('/path');
  processData(data);
} catch (err) {
  console.error('Read failed:', err.message);
}

// 4. Event emitters — 'error' event
const server = http.createServer();
server.on('error', (err) => {
  if (err.code === 'EADDRINUSE') {
    console.error('Port already in use');
    process.exit(1);
  }
});

// 5. Global handlers — last resort
process.on('uncaughtException', (err) => {
  console.error('Uncaught exception:', err);
  process.exit(1); // Must exit — state may be corrupted
});

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled rejection:', reason);
  process.exit(1); // Node 15+ does this by default
});

Never Swallow uncaughtException

After an uncaught exception, the process is in an undefined state. Log the error, flush logs, and exit. A process manager (PM2, systemd) should restart it.

A useful distinction from the Node docs is operational errors (expected failures: network timeout, file not found, invalid input — handle and recover) versus programmer errors (bugs: undefined is not a function, wrong argument types — crash and fix the code). Try/catch around a bug just hides it.

Common wrong answer / trap: Wrapping a callback-style call in try/catch and expecting to catch its async error:

try {
  require('node:fs').readFile('/nope', (err) => { if (err) throw err; });
} catch (e) {
  console.log('never reached'); // the throw happens later, on another stack
}

The throw happens on a later turn of the loop and becomes an uncaughtException.

Follow-up: "How do you attach context to an error when you rethrow it?" — Use new Error('loading config failed', { cause: err }) (ES2022). Node's util.inspect and most loggers print the cause chain.

Q: What happens if an EventEmitter emits 'error' and nobody is listening?

'error' is special: if there is no listener, emit('error', err) throws err. On a server or stream, that usually means the process crashes.

const { EventEmitter, once } = require('node:events');
const e = new EventEmitter();

try {
  e.emit('error', new Error('no listener'));
} catch (err) {
  console.log('threw:', err.message); // threw: no listener
}

// events.once turns an event into a promise (and rejects on 'error')
(async () => {
  setTimeout(() => e.emit('ready', 1, 2), 5);
  const args = await once(e, 'ready');
  console.log('once ->', args); // once -> [ 1, 2 ]
})();

Adding an 11th listener for one event prints MaxListenersExceededWarning: Possible EventEmitter memory leak detected — verified on Node 22. It's a warning, not an error, and it's often the first symptom of a listener leak.

Common wrong answer / trap: "Emitters are async." emit() calls listeners synchronously, in registration order, on the current stack. If a listener throws, emit throws.

Follow-up: "How do you stop a stream error from crashing the server?" — Use stream.pipeline() (which attaches error handlers to every stream and destroys them all on failure) rather than .pipe().

Buffers

Q: What is a Buffer and when do you use it?

A Buffer is a fixed-size chunk of memory allocated outside the V8 heap. It is used for binary data — file I/O, network protocols, cryptography — where JavaScript strings (UTF-16) are too slow or inappropriate.

// Creating buffers
const buf1 = Buffer.alloc(16);           // 16 bytes, zero-filled
const buf2 = Buffer.from('hello');        // From string (UTF-8)
const buf3 = Buffer.from([0x48, 0x65]);   // From byte array
const buf4 = Buffer.allocUnsafe(16);      // Uninitialized (faster, may contain old data)

// Reading and writing
buf1.writeUInt32BE(0xDEADBEEF, 0); // Write 4 bytes at offset 0
buf1.readUInt32BE(0);               // 0xDEADBEEF

// Conversion
buf2.toString('utf8');     // 'hello'
buf2.toString('hex');      // '68656c6c6f'
buf2.toString('base64');   // 'aGVsbG8='

// Comparison
Buffer.compare(buf2, Buffer.from('hello')); // 0 (equal)

// Concatenation
const combined = Buffer.concat([buf2, Buffer.from(' world')]);
combined.toString(); // 'hello world'

Buffer.allocUnsafe Is Faster But Risky

Buffer.allocUnsafe() does not zero-fill the memory, so it may contain sensitive data from previous allocations. Use it only when you will immediately overwrite all bytes.

Buffer is a subclass of Uint8Array, so every typed-array API works on it. Small allocUnsafe / Buffer.from allocations are sliced from a shared pre-allocated pool (Buffer.poolSize is 8192 bytes), which is why they are cheap — and why the underlying ArrayBuffer of a small buffer can be much bigger than the buffer itself.

Common wrong answer / trap: Assuming buf.slice() / buf.subarray() copies. Both return a view on the same memory:

const b = Buffer.from('abcdef');
const s = b.subarray(0, 3);
s[0] = 0x58;            // 'X'
console.log(b.toString()); // Xbcdef — the original changed

(Buffer.prototype.slice is deprecated in favour of subarray precisely because people expected copy semantics from Array.prototype.slice.) Use Buffer.from(b) or Uint8Array.prototype.slice.call(b) to copy.

Follow-up: "Why is buf.buffer.byteLength sometimes 8192 when the buffer is 5 bytes?" — Pooling. If you pass buf.buffer to an API, also pass buf.byteOffset and buf.length.

Q: Why can a Buffer's length differ from the string's length, and what breaks when you split one?

string.length counts UTF-16 code units; buffer.length counts bytes. Any non-ASCII character takes 2–4 bytes in UTF-8.

const { StringDecoder } = require('node:string_decoder');

console.log(Buffer.from('é').length, 'é'.length); // 2 1

const euro = Buffer.from('€');
console.log(euro);                                  // <Buffer e2 82 ac>

// Naive: decode each chunk separately — corrupts the character
console.log(euro.subarray(0, 2).toString() + euro.subarray(2).toString()); // '��'

// Correct: StringDecoder holds incomplete bytes until the next chunk
const d = new StringDecoder('utf8');
console.log(d.write(euro.subarray(0, 2)) + d.write(euro.subarray(2)));   // '€'

This exact bug appears in hand-written stream code: data += chunk.toString() corrupts multibyte characters that straddle chunk boundaries. Use readable.setEncoding('utf8') (which uses a StringDecoder internally) or collect buffers and Buffer.concat before decoding.

Common wrong answer / trap: Setting Content-Length to body.length for a string body. For non-ASCII text that's wrong; use Buffer.byteLength(body).

Follow-up: "When would you use TextDecoder instead?" — In code that must also run in browsers or other runtimes; it's the web-standard equivalent and supports { stream: true } for the same chunk-boundary problem.

Everyday Tooling

Q: What does node --watch do and when would you still use nodemon?

node --watch app.js (stable since Node 22) restarts the process when the entry file or anything it imports changes. --watch-path=./src watches a directory explicitly, and --watch-preserve-output stops it clearing the console.

node --watch --env-file=.env server.js
node --watch-path=./src --watch-path=./config server.js
node --test --watch          # re-run tests on change

Common wrong answer / trap: Expecting --watch to reload config files that are read with fs — it tracks the module graph, not arbitrary reads. Add those paths with --watch-path. nodemon is still useful for custom extensions, delays, and non-Node commands.

Follow-up: "Would you use --watch in production?" — No. Production restarts belong to the process manager or orchestrator, triggered by a deploy, not file changes.

Q: Node has a built-in fetch — how does it differ from the browser's and from http.request?

Global fetch is implemented by undici, Node's modern HTTP/1.1 client. It was experimental in Node 18 and has been stable since Node 21. It returns WHATWG Response objects with web streams bodies.

// Run: node fetch.mjs — starts a local server so the example is self-contained
import http from 'node:http';

const srv = http.createServer((req, res) => {
  const delay = req.url === '/slow' ? 500 : 0;
  setTimeout(() => {
    res.setHeader('content-type', 'application/json');
    res.end(JSON.stringify({ ok: true, path: req.url }));
  }, delay);
});
await new Promise((r) => srv.listen(0, r));
const base = `http://127.0.0.1:${srv.address().port}`;

const r = await fetch(`${base}/hi`);
console.log(r.status, await r.json());          // 200 { ok: true, path: '/hi' }

try {
  await fetch(`${base}/slow`, { signal: AbortSignal.timeout(100) });
} catch (e) {
  console.log('slow:', e.name);                  // slow: TimeoutError
}
srv.closeAllConnections();
srv.close();

Differences from the browser: no CORS, no cookies jar, no cache; you can set any header. Differences from http.request: promise-based, connection pooling is managed by undici's global dispatcher (tune it with undici's Agent if you need per-host limits).

Common wrong answer / trap: Assuming fetch rejects on HTTP errors. It only rejects on network failure or abort; a 404 or 500 resolves with res.ok === false. Second trap: not consuming or cancelling the body — unread bodies keep the connection busy and can exhaust the pool.

Follow-up: "How do you add a timeout and a user-cancel?" — AbortSignal.any([AbortSignal.timeout(5000), controller.signal]).


Senior

Event Loop Puzzles

Q: Puzzle — what prints inside an I/O callback?

// Run: node p2.js
const fs = require('node:fs');
fs.readFile(__filename, () => {
  console.log('io');
  setTimeout(() => console.log('timeout'), 0);
  setImmediate(() => console.log('immediate'));
  process.nextTick(() => console.log('nextTick'));
  Promise.resolve().then(() => console.log('promise'));
});

Verified output (deterministic): io nextTick promise immediate timeout

The callback runs in the poll phase. When it returns, the nextTick queue then the promise queue drain. The loop then moves to check (immediate) and only later reaches timers (timeout).

Common wrong answer / trap: io immediate nextTick promise timeout — forgetting that microtasks drain as soon as the current callback finishes, before the loop moves to the next phase.

Follow-up: "Is setImmediate always before a 0 ms timer, no matter how many timers exist?" — Yes, when both are scheduled from inside an I/O callback; that is the documented advantage of setImmediate.

Q: Puzzle — do microtasks run between two timers?

// Run: node p3.js
setTimeout(() => {
  console.log('t1');
  Promise.resolve().then(() => console.log('t1-promise'));
  process.nextTick(() => console.log('t1-tick'));
}, 0);
setTimeout(() => console.log('t2'), 0);

Verified output on Node 22: t1 t1-tick t1-promise t2

Since Node 11, microtasks drain after each timer callback, matching browser behaviour. On Node 10 and older this printed t1 t2 t1-tick t1-promise.

Common wrong answer / trap: Answering with the Node 10 order — it's still in many old blog posts. If the interviewer quotes it, explain the Node 11 change.

Follow-up: "Does the same apply to setImmediate callbacks?" — Yes, microtasks drain between immediates too.

Q: Puzzle — nextTick scheduled from a promise, and a promise scheduled from nextTick

// Run: node p4.js
Promise.resolve().then(() => {
  console.log('p1');
  process.nextTick(() => console.log('tick inside promise'));
}).then(() => console.log('p2'));

process.nextTick(() => {
  console.log('tick1');
  Promise.resolve().then(() => console.log('promise inside tick'));
});

Verified output: tick1 p1 promise inside tick p2 tick inside promise

  1. Node drains the nextTick queue first: tick1, which queues a promise job.
  2. Node then hands control to V8's microtask queue, which runs until empty: p1 (queues a nextTick and resolves the chain), promise inside tick, then p2.
  3. Only after V8's queue is empty does Node look at the nextTick queue again: tick inside promise.

Common wrong answer / trap: "nextTick always beats promises," so tick inside promise before promise inside tick. nextTick only has priority when Node is choosing which queue to drain; once V8 is draining promise jobs, a newly queued nextTick waits.

Follow-up: "Can promises starve the event loop like nextTick?" — Yes. An infinite chain of .then that keeps queuing new promise jobs never lets the loop advance.

Q: Puzzle — does the same code print differently in an ES module?

// Run as nt.mjs (ESM): node nt.mjs
process.nextTick(() => console.log('tick'));
Promise.resolve().then(() => console.log('promise'));
setTimeout(() => {
  process.nextTick(() => console.log('tick in timeout'));
  Promise.resolve().then(() => console.log('promise in timeout'));
}, 0);

Verified output in .mjs: promise tick tick in timeout promise in timeout The same top-level two lines in a .js CommonJS file print tick promise.

Why: ES module evaluation itself runs inside a promise job (module evaluation is asynchronous to support top-level await). When the module body finishes, V8 is still draining its microtask queue, so the promise reaction runs first; Node's nextTick queue gets its turn only after. Inside the timer callback you're back to a normal macrotask, and the usual "nextTick first" rule applies.

Common wrong answer / trap: Insisting nextTick always wins. This puzzle is a staple precisely because migrating a codebase from CJS to ESM can reorder startup code that relied on nextTick.

Follow-up: "Does this matter in real code?" — Rarely, but it bites initialisation code that uses nextTick to "wait until all listeners are attached." Don't rely on cross-queue ordering; use explicit events or awaits.

Q: Puzzle — async/await ordering

// Run: node p7.js
async function a() { console.log('a1'); await b(); console.log('a2'); }
async function b() { console.log('b'); }

console.log('s');
a();
process.nextTick(() => console.log('tick'));
Promise.resolve().then(() => console.log('p'));
console.log('e');

Verified output: s a1 b e tick a2 p

a() runs synchronously until its first await — so a1 and b print right away. await b() awaits an already-resolved promise, which schedules the continuation (a2) as a microtask before the p reaction was queued. Then synchronous e, then the nextTick queue (tick), then promise jobs in queue order (a2, p).

Common wrong answer / trap: Thinking async functions start asynchronously (putting a1 after e). The body is synchronous up to the first await.

Follow-up: "What if b returned a non-native thenable?" — Awaiting a thenable costs extra microtask hops (it has to call then), so a2 can drop behind p. Since V8 7.2 awaiting a native promise takes one hop.

Q: Puzzle — setImmediate and setTimeout scheduled from inside a setImmediate

// Run: node p6.js several times
setImmediate(() => {
  console.log('imm1');
  setTimeout(() => console.log('timeout from imm'), 0);
  setImmediate(() => console.log('imm from imm'));
  process.nextTick(() => console.log('tick from imm1'));
});
setImmediate(() => console.log('imm2'));

Verified (8 runs on Node 22):

6x  imm1 tick from imm1 imm2 timeout from imm imm from imm
2x  imm1 tick from imm1 imm2 imm from imm timeout from imm

The deterministic part: imm1, its nextTick, then imm2 (an immediate queued during the check phase waits for the next iteration, so imm from imm never runs in the same check phase). The racy part: whether the 1 ms timer has expired by the next timers step.

Common wrong answer / trap: Saying imm from imm runs right after imm2 because "immediates run in the same phase." Immediates added during a check phase are deferred to the next iteration — this is what keeps recursive setImmediate from starving I/O.

Follow-up: "Which one would you use to yield to I/O in a chunked loop?" — setImmediate, for exactly this reason.

Q: What is libuv and why does Node need it?

libuv is the C library that provides Node.js with its event loop and thread pool. The operating system can handle some async operations natively (network I/O on Linux via epoll, macOS via kqueue), but filesystem operations, DNS lookups, and some crypto operations are blocking at the OS level. libuv runs these on a thread pool (default: 4 threads).

graph TD
    JS["JavaScript Code"] --> V8["V8 Engine<br/>Compiles & Executes JS"]
    V8 --> NB["Node.js Bindings<br/>(C++ layer)"]
    NB --> LIBUV["libuv"]
    LIBUV --> EL["Event Loop<br/>(single thread)"]
    LIBUV --> TP["Thread Pool<br/>(default 4 threads)"]
    EL --> NET["Network I/O<br/>(epoll/kqueue/IOCP)"]
    TP --> FS["File System"]
    TP --> DNS["DNS Lookups"]
    TP --> CRYPTO["Crypto (pbkdf2, etc.)"]
    TP --> ZLIB["Compression"]

    style EL fill:#059669,color:#fff
    style TP fill:#d97706,color:#fff
# Increase thread pool size (default is 4)
UV_THREADPOOL_SIZE=16 node server.js

You can see the pool with six concurrent pbkdf2 calls:

// Run: node tp.js   then: UV_THREADPOOL_SIZE=6 node tp.js
const crypto = require('node:crypto');
const start = Date.now();
for (let i = 1; i <= 6; i++) {
  crypto.pbkdf2('pw', 'salt', 200000, 64, 'sha512', () =>
    console.log(`hash ${i}: ${Date.now() - start}ms`));
}

Verified on an 8-core laptop: with the default pool, four hashes finished at ~125–170 ms and the last two at ~275 ms (they waited for a free thread). With UV_THREADPOOL_SIZE=6, all six finished within ~135–160 ms.

Important details:

  • dns.lookup (used by http.get, net.connect and fetch for hostnames) goes through the pool because it calls getaddrinfo. dns.resolve* uses c-ares on the network and does not.
  • The pool is process-wide and shared — a slow NFS mount can stall DNS lookups for HTTP calls.
  • UV_THREADPOOL_SIZE must be set before the pool is first used (in practice, in the environment); the maximum is 1024.

Common wrong answer / trap: "Network I/O uses the thread pool." Sockets don't — they use the OS's readiness APIs on the main loop. Only work that has no non-blocking OS API (files, getaddrinfo, CPU-heavy crypto/zlib) goes to the pool.

Follow-up: "Your service's outbound HTTP latency spikes whenever a nightly job reads lots of files. Why?" — Both compete for the four pool threads (fs and dns.lookup). Raise the pool size, cache DNS, or move the file job out of process.

Streams

Q: Explain the four types of streams.

Stream TypeDescriptionExample
ReadableSource of data you consumefs.createReadStream, http.IncomingMessage
WritableDestination you write data tofs.createWriteStream, http.ServerResponse
DuplexBoth readable and writablenet.Socket, zlib.createGzip
TransformDuplex that modifies data passing throughzlib.createGzip, crypto.createCipheriv
const fs = require('fs');
const zlib = require('zlib');
const { pipeline } = require('stream/promises');

// Stream a file through gzip compression to another file
await pipeline(
  fs.createReadStream('input.log'),
  zlib.createGzip(),
  fs.createWriteStream('input.log.gz')
);
// Memory efficient: processes chunks, never loads entire file

// Transform stream — uppercase text
const { Transform } = require('stream');

const upperCase = new Transform({
  transform(chunk, encoding, callback) {
    this.push(chunk.toString().toUpperCase());
    callback();
  }
});

process.stdin.pipe(upperCase).pipe(process.stdout);

Note (2026-11-09): the top-level await above only works in an ES module (or the REPL); in a .js CommonJS file wrap it in an async function.

The key idea is that Duplex has two independent sides (a socket's read and write sides are unrelated data), while a Transform's output is computed from its input. Streams default to byte mode. On Node 22 the highWaterMark is 64 KiB for fs read streams and 16 KiB for generic streams; objectMode: true streams count objects instead (default 16). Defaults can change between majors, so read them with stream.getDefaultHighWaterMark(objectMode) rather than hard-coding them.

Modern streams also support async iteration and array-like helpers:

// Run: node helpers.mjs
import { Readable } from 'node:stream';
const nums = await Readable.from([1, 2, 3, 4])
  .filter((n) => n % 2 === 0)
  .map((n) => n * 10)
  .toArray();
console.log(nums); // [ 20, 40 ]

Common wrong answer / trap: "A Transform is just a Readable piped to a Writable." It is a single object implementing both sides with coordinated backpressure. Second trap: in byte mode, chunk boundaries are arbitrary — your transform must not assume one chunk equals one line or one JSON object.

Follow-up: "How would you split a byte stream into lines?" — readline.createInterface({ input }) and for await (const line of rl), or a Transform that keeps the trailing partial line in a buffer.

Q: What is backpressure and how do you handle it?

Backpressure occurs when a writable stream cannot process data as fast as the readable stream produces it. Without handling backpressure, data accumulates in memory and causes OOM crashes.

graph LR
    R["Readable Stream<br/>(fast producer)"] -->|"data chunks"| W["Writable Stream<br/>(slow consumer)"]
    W -->|"buffer full → false"| R
    R -->|"pause reading"| R
    W -->|"'drain' event"| R
    R -->|"resume reading"| R

    style R fill:#059669,color:#fff
    style W fill:#dc2626,color:#fff
// BAD — ignoring backpressure
const readable = fs.createReadStream('huge-file.csv');
const writable = fs.createWriteStream('output.csv');

readable.on('data', (chunk) => {
  writable.write(chunk); // Ignores return value!
  // If writable buffer is full, data accumulates in memory
});

// GOOD — respecting backpressure manually
readable.on('data', (chunk) => {
  const canContinue = writable.write(chunk);
  if (!canContinue) {
    readable.pause(); // Stop reading until writable drains
  }
});

writable.on('drain', () => {
  readable.resume(); // Buffer drained, resume reading
});

// BEST — use pipeline (handles backpressure automatically)
const { pipeline } = require('stream/promises');

await pipeline(readable, transformStream, writable);
// Also handles error propagation and cleanup

You can watch the signal directly:

// Run: node bp.js
const { Writable } = require('node:stream');
const slow = new Writable({
  highWaterMark: 16,                         // bytes
  write(chunk, enc, cb) { setTimeout(cb, 1); }, // slow sink
});
let ok = true, i = 0;
while (ok && i < 100) { ok = slow.write('xxxxxxxx'); i++; }
console.log('write returned false after', i, 'writes; writableLength =', slow.writableLength);
slow.once('drain', () => console.log('drain fired, writableLength =', slow.writableLength));
// write returned false after 2 writes; writableLength = 16
// drain fired, writableLength = 0

write() returning false is advice, not refusal: the data was buffered. If you keep writing, Node keeps buffering — without limit. That is the bug.

Common wrong answer / trap: "Streams handle backpressure automatically." Only if you use pipe/pipeline/async iteration. Manual 'data' + write() code, or a for await loop that calls write() without awaiting 'drain', has none.

Follow-up: "Write the async-iteration version that respects backpressure." —

const { once } = require('node:events');
async function copy(readable, writable) {
  for await (const chunk of readable) {
    if (!writable.write(chunk)) await once(writable, 'drain');
  }
  writable.end();
}

Q: Implement a custom readable stream

const { Readable } = require('stream');

class DatabaseCursor extends Readable {
  constructor(query, options = {}) {
    super({ ...options, objectMode: true });
    this.query = query;
    this.offset = 0;
    this.batchSize = 100;
  }

  async _read() {
    try {
      const rows = await db.query(this.query, {
        offset: this.offset,
        limit: this.batchSize,
      });

      if (rows.length === 0) {
        this.push(null); // Signal end of stream
        return;
      }

      for (const row of rows) {
        this.push(row);
      }

      this.offset += rows.length;
    } catch (err) {
      this.destroy(err);
    }
  }
}

// Usage — process millions of rows without loading all into memory
const cursor = new DatabaseCursor('SELECT * FROM events');

for await (const row of cursor) {
  await processEvent(row);
}

_read() is called when the consumer wants more data. Node won't call it again until you push(), so an async _read that awaits a batch is safe. The consumer's for await naturally applies backpressure: if processEvent is slow, the internal buffer fills to highWaterMark, and _read stops being called.

A self-contained, runnable version with a fake database:

// Run: node cursor.mjs
import { Readable } from 'node:stream';

const table = Array.from({ length: 250 }, (_, i) => ({ id: i }));
const db = { async query(_, { offset, limit }) { return table.slice(offset, offset + limit); } };

// Simplest modern form: an async generator becomes a Readable
async function* rows(batch = 100) {
  for (let offset = 0; ; offset += batch) {
    const page = await db.query('SELECT * FROM events', { offset, limit: batch });
    if (page.length === 0) return;
    yield* page;
  }
}

let count = 0;
for await (const row of Readable.from(rows())) count++;
console.log(count); // 250

Common wrong answer / trap: Using OFFSET pagination for millions of rows — every page rescans the skipped rows, making the whole export O(n²) in the database. Use keyset pagination (WHERE id > $lastId ORDER BY id LIMIT 100).

Follow-up: "How do you stop the query if the consumer breaks out of the loop early?" — Breaking out of for await destroys the stream; implement _destroy(err, cb) (or a finally in the generator) to close the DB cursor.

Q: pipe() vs pipeline() — why does it matter?

a.pipe(b) handles backpressure but not errors or cleanup: if b errors, a keeps its file descriptor open; if a errors, b is never ended or destroyed. Errors don't propagate along a .pipe() chain, so each stream needs its own 'error' handler. stream.pipeline() (and its promise version in node:stream/promises) wires errors from every stage, destroys all streams on failure, and gives you one place to handle the result.

// Run: node pipeline.mjs
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';

const upper = new Transform({
  transform(chunk, enc, cb) { cb(null, chunk.toString().toUpperCase()); },
});
const out = [];
await pipeline(Readable.from(['a', 'b', 'c']), upper, async function* (src) {
  for await (const c of src) out.push(c.toString());
});
console.log(out); // [ 'ABC' ] — byte-mode chunks were coalesced in the buffer

try {
  await pipeline(
    Readable.from(['x']),
    new Transform({ transform(c, e, cb) { cb(new Error('bad chunk')); } }),
    async function* (s) { for await (const _ of s); },
  );
} catch (e) {
  console.log('pipeline rejected:', e.message); // pipeline rejected: bad chunk
}

Note the first output: three chunks went in, one came out. In byte mode chunk boundaries are not preserved — another reason never to rely on them.

Common wrong answer / trap: res in an HTTP handler with fs.createReadStream(p).pipe(res) — if the client disconnects, the file stream may leak until GC; with a missing file, the 'error' event crashes the process. Use pipeline(fs.createReadStream(p), res) with a catch.

Follow-up: "How do you abort a pipeline?" — Pass { signal } as the last argument; aborting destroys every stream and rejects the promise with an AbortError.


Concurrency: cluster, worker_threads, child_process

Q: When do you use cluster vs worker_threads?

Featureclusterworker_threads
Use caseScale HTTP servers across CPU coresCPU-intensive computation
Process modelSeparate processes (fork)Threads within one process
MemorySeparate memory per processShared memory possible (SharedArrayBuffer)
CommunicationIPC (serialized messages)MessagePort (faster, structured clone or SharedArrayBuffer)
Port sharingBuilt-in (multiple processes share one port)Not built-in
Crash isolationWorker crash does not affect masterUncaught error in a worker emits 'error' on the Worker object; native crashes or OOM of the whole process take everything down

Correction (2026-11-09): the table said a thread crash "can crash entire process." An uncaught JavaScript exception inside a worker ends only that worker: the main thread receives an 'error' event and then 'exit' with code 1 (verified below). What does take down the whole process is a native crash (a segfault in an addon), process.exit() semantics differences aside, or exhausting the shared process memory — use resourceLimits to cap a worker's heap.

// CLUSTER — scale HTTP server to all CPU cores
const cluster = require('cluster');
const http = require('http');
const os = require('os');

if (cluster.isPrimary) {
  const numCPUs = os.cpus().length;
  console.log(`Primary ${process.pid} forking ${numCPUs} workers`);

  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code) => {
    console.log(`Worker ${worker.process.pid} died (${code}). Restarting...`);
    cluster.fork(); // Auto-restart dead workers
  });
} else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Handled by worker ${process.pid}\n`);
  }).listen(3000);
}

Correction (2026-11-09): the worker_threads example below originally used top-level await in a CommonJS file (it uses require and __filename), which is a SyntaxError. It is now wrapped in an async IIFE. os.availableParallelism() (Node 18.14+) is also a better core count than os.cpus().length because it respects CPU affinity.

// WORKER THREADS — offload CPU-intensive work
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');

if (isMainThread) {
  // Main thread — offload heavy computation
  async function computeHash(data) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, { workerData: data });
      worker.on('message', resolve);
      worker.on('error', reject);
    });
  }

  (async () => {
    const result = await computeHash({ input: 'large-dataset' });
    console.log('Result:', result);
  })();
} else {
  // Worker thread — CPU-intensive work
  const crypto = require('crypto');
  const hash = crypto
    .createHash('sha256')
    .update(JSON.stringify(workerData))
    .digest('hex');

  parentPort.postMessage({ hash });
}

Production Recommendation

For HTTP servers, use a process manager like PM2 or the built-in cluster module. For CPU-intensive tasks in a server context, use a worker thread pool (e.g., piscina or workerpool) to avoid the overhead of spawning a new thread per request.

Rule of thumb: more HTTP throughput on one machine → cluster/PM2 or more replicas; CPU-heavy work inside a request → a worker_threads pool; running another program → child_process.

Common wrong answer / trap: "Use worker_threads to make my Express app faster." Workers don't help I/O-bound request handling — the event loop already overlaps I/O. They help only when a request does seconds of CPU work. Also: on Kubernetes, running cluster and many replicas often double-counts cores; one process per container with CPU limits is simpler.

Follow-up: "How does cluster share one port across processes?" — The primary accepts connections and hands them round-robin to workers (the default everywhere except Windows), or each worker accepts from a shared handle (SCHED_NONE). Either way the OS socket is created once and passed to the children.

Q: Show worker_threads failure handling, and explain how data crosses threads.

// Run: node wk.js
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');

if (isMainThread) {
  const w = new Worker(__filename, { workerData: { n: 35 } });
  w.on('message', (m) => console.log('result', m));
  w.on('exit', (c) => console.log('worker exit code', c));

  const w2 = new Worker('throw new Error("kaboom")', { eval: true });
  w2.on('error', (e) => console.log('w2 error event:', e.message));
  w2.on('exit', (c) => console.log('w2 exit', c, '- main still alive'));
} else {
  const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
  parentPort.postMessage(fib(workerData.n));
}
// Verified:
// w2 error event: kaboom
// w2 exit 1 - main still alive
// result 9227465
// worker exit code 0

postMessage uses the structured clone algorithm (copies). Pass ArrayBuffers in the transfer list to move them without copying; pass a SharedArrayBuffer to share them.

Common wrong answer / trap: Creating a new Worker per request. Start-up costs tens of milliseconds and a fresh V8 isolate (several MB); use a fixed pool sized to cores. Second trap: posting huge objects back and forth — cloning cost can exceed the work saved.

Follow-up: "Can workers share a database connection?" — No; handles and sockets aren't shareable. Each worker opens its own, so size the DB pool per worker.

Q: exec vs execFile vs spawn vs fork

APIShell?OutputUse for
exec(cmd)Yes (/bin/sh or cmd.exe)Buffered (default maxBuffer 1 MiB)Quick trusted one-liners with pipes
execFile(file, args)NoBufferedRunning a binary with arguments — the safe default
spawn(file, args)No (unless shell: true)Streamed (child.stdout)Long-running processes, large output
fork(modulePath)NoStreams + IPC channel (process.send)Another Node process you talk to
// Run: node cp.js
const { execFile, spawn, fork, exec } = require('node:child_process');
const { promisify } = require('node:util');

if (process.argv[2] === 'child') {
  process.on('message', (m) => { process.send({ got: m }); process.exit(0); });
} else {
  (async () => {
    const { stdout } = await promisify(execFile)(process.execPath, ['-e', 'console.log(1+1)']);
    console.log('execFile:', stdout.trim());                      // execFile: 2

    const child = spawn(process.execPath, ['-e', 'for (let i=0;i<3;i++) console.log("line", i)']);
    child.stdout.on('data', (d) => process.stdout.write(`spawn> ${d}`));
    child.on('close', (code) => {
      const f = fork(__filename, ['child']);
      f.on('message', (m) => console.log('fork reply:', m));      // fork reply: { got: 'hello' }
      f.send('hello');
    });
  })();
}

Common wrong answer / trap: Building commands with string interpolation:

const evil = 'x; echo INJECTED';
require('node:child_process').exec(`echo ${evil}`, (e, out) => console.log(out));
// On Linux/macOS (/bin/sh) prints: x  then  INJECTED — command injection
// execFile('echo', [evil]) prints the literal string: x; echo INJECTED

Also: exec kills the child when output exceeds maxBuffer — a classic "works in dev, fails with big logs in prod."

Follow-up: "How do you make sure children die when the parent is killed?" — Forward signals, kill on 'exit', use detached: false, and in containers run an init (tini, --init) so orphaned children are reaped.

Error Handling in Depth

Q: What happens to an unhandled promise rejection, and how should you handle them?

Since Node 15, the default --unhandled-rejections mode is throw: an unhandled rejection is raised as an uncaught exception and, with no uncaughtException handler, the process exits with code 1. Verified:

node -e "Promise.reject(1)"; echo "exit $?"
# UnhandledPromiseRejection: ... The promise rejected with the reason "1".
#   code: 'ERR_UNHANDLED_REJECTION'
# exit 1

"Unhandled" means no handler attached by the time the microtask queue drains after the rejection. Attaching one later fires 'rejectionHandled':

// Run: node late.js
process.on('unhandledRejection', (r) => console.log('unhandledRejection', r.message));
process.on('rejectionHandled', () => console.log('rejectionHandled'));
const p = Promise.reject(new Error('late'));
setTimeout(() => p.catch(() => console.log('caught late')), 10);
// unhandledRejection late
// caught late
// rejectionHandled

Production pattern: log with full context, flip a "not healthy" flag, stop accepting traffic and exit — the same as uncaughtException. Don't keep running "because it was only a promise"; the code path that rejected may have left half-finished state behind.

Common wrong answer / trap: Fire-and-forget calls like sendEmail(user) without await or .catch(). One SMTP timeout kills the whole API process. Either await it, or .catch(log) explicitly. The ESLint rule @typescript-eslint/no-floating-promises catches these.

Follow-up: "What's the trap with Promise.all and rejections?" — When one promise rejects, Promise.all rejects but the other promises keep running; if more of them reject later, those rejections are already handled by all's internal handler, so they're silently swallowed. Use Promise.allSettled when you need every outcome.

Memory Management and V8

Q: How does V8 manage memory?

V8 uses a generational garbage collector. Memory is divided into regions:

graph TD
    subgraph "V8 Heap"
        NG["New Generation (Young)<br/>a few MB to tens of MB<br/>Short-lived objects"]
        OG["Old Generation<br/>sized from available memory<br/>Long-lived objects"]
        LO["Large Object Space<br/>Objects too big for a regular page"]
        CS["Code Space<br/>Compiled machine code"]
        MAP["Map Space<br/>(removed in modern V8 —<br/>maps now live in old space)"]
    end

    NG -->|"Survives 2 GC cycles"| OG
    NG -->|"Scavenge (Minor GC)<br/>Very fast, ~1ms"| NG
    OG -->|"Mark-Sweep-Compact (Major GC)<br/>Slower, 5-50ms"| OG

    style NG fill:#059669,color:#fff
    style OG fill:#d97706,color:#fff

Correction (2026-11-09): V8 no longer has a separate Map Space — hidden classes ("maps") are allocated in old space. Running v8.getHeapSpaceStatistics() on Node 22 lists read_only_space, new_space, old_space, code_space, shared_space, trusted_space and several large-object spaces, with no map space. The original diagram also gave fixed sizes ("~1-8 MB", "~700 MB - 4 GB", "> 512 KB"); those depend on the V8 version, page size and machine, so they have been replaced with descriptions. Check real numbers with v8.getHeapStatistics().

GC TypeTargetsAlgorithmSpeedPause
Scavenge (Minor GC)New generationSemi-space copy (Cheney's algorithm)Very fast~1ms
Mark-Sweep (Major GC)Old generationTri-color marking + sweepSlower5-50ms
Mark-CompactOld generationMark + compact (defragment)SlowestLonger
Incremental MarkingOld generationInterleaved with JS executionReduced pausesSpread out

Modern V8 (the "Orinoco" project) also does most marking concurrently on helper threads and scavenges in parallel, so main-thread pauses are much shorter than the total GC work.

# Check heap usage
node -e "console.log(process.memoryUsage())"
# {
#   rss: 30000000,      # Resident Set Size (total OS memory)
#   heapTotal: 7000000, # V8 heap allocated
#   heapUsed: 5000000,  # V8 heap in use
#   external: 1000000,  # C++ objects bound to JS
#   arrayBuffers: 500000 # ArrayBuffer / SharedArrayBuffer
# }

# Increase old-generation heap limit (the default is derived from available memory)
node --max-old-space-size=4096 server.js  # 4 GB

Correction (2026-11-09): the default old-space limit is not a fixed "~1.5 GB on 64-bit" any more. Since Node 12, V8 sizes the heap from available system memory (and recent Node versions take container memory limits into account). On a 16 GB laptop, Node 22 reports heap_size_limit ≈ 4144 MB; with --max-old-space-size=512 it reports ≈ 560 MB (old space plus young generation). In containers, set the flag explicitly to about 75% of the memory limit so V8 GCs harder before the kernel OOM-kills you.

node -e "console.log(Math.round(require('v8').getHeapStatistics().heap_size_limit/1048576), 'MB')"

Common wrong answer / trap: "Buffers count toward the heap limit." Buffer contents live outside the V8 heap (external / arrayBuffers), so a process can blow past --max-old-space-size in RSS without a heap OOM. Watch RSS, not just heapUsed.

Follow-up: "What does 'JavaScript heap out of memory' tell you?" — Old space hit its limit after repeated full GCs failed to free enough. It's either a real leak or a legitimately large working set; a heap snapshot tells you which.

Q: Common memory leak patterns and detection

Pattern 1 — Global accumulation:

// LEAK: array grows forever
const cache = [];

app.get('/api/data', (req, res) => {
  const result = processRequest(req);
  cache.push(result); // Never cleared
  res.json(result);
});

// FIX: use an LRU cache with a max size
const { LRUCache } = require('lru-cache');
const cache = new LRUCache({ max: 1000 });

Correction (2026-11-09): lru-cache v7+ no longer exports a default constructor; const LRU = require('lru-cache'); new LRU(...) throws LRU is not a constructor. Use the named export { LRUCache } as above. If you can't add a dependency, a Map is already insertion-ordered and makes a correct 10-line LRU:

class LRU {
  constructor(max) { this.max = max; this.m = new Map(); }
  get(k) {
    if (!this.m.has(k)) return undefined;
    const v = this.m.get(k); this.m.delete(k); this.m.set(k, v); return v;
  }
  set(k, v) {
    this.m.delete(k); this.m.set(k, v);
    if (this.m.size > this.max) this.m.delete(this.m.keys().next().value);
    return this;
  }
}
const c = new LRU(2); c.set('a', 1).set('b', 2); c.get('a'); c.set('c', 3);
console.log([...c.m.keys()]); // [ 'a', 'c' ] — 'b' was least recently used

Pattern 2 — Closures holding references:

// LEAK: closure retains reference to large object
function processData() {
  const hugeData = loadGigabyteFile(); // 1 GB

  return function getMetadata() {
    return { size: hugeData.length }; // Only needs .length
    // But the closure retains the entire hugeData object
  };
}

// FIX: extract what you need before closing over it
function processData() {
  const hugeData = loadGigabyteFile();
  const size = hugeData.length; // Extract needed value

  return function getMetadata() {
    return { size }; // Only closes over the number
  };
}

Pattern 3 — Event listener accumulation:

// LEAK: adding listeners without removing them
class Connector {
  connect(eventBus) {
    // New listener on each connect() call
    eventBus.on('data', this.handleData.bind(this));
    // bind() creates a NEW function each time — cannot remove
  }
}

// FIX: store reference, remove on disconnect
class Connector {
  #handler = null;

  connect(eventBus) {
    this.#handler = (data) => this.handleData(data);
    eventBus.on('data', this.#handler);
  }

  disconnect(eventBus) {
    eventBus.off('data', this.#handler);
  }
}

Other frequent leaks: setInterval never cleared; unbounded Map keyed by request ID; per-request listeners on a long-lived socket or process; promises that never settle (each holds its closure); and large strings retained by a tiny substring (V8 "sliced strings").

Detection tools:

# Heap snapshot
node --inspect server.js
# Then open Chrome DevTools → Memory → Take Heap Snapshot

# Track heap growth over time
node --inspect server.js
# Memory → Allocation Timeline → Look for non-GC'd allocations

# CLI — heap dump on demand
kill -USR2 <pid>  # If using heapdump module

# Programmatic monitoring
setInterval(() => {
  const { heapUsed, heapTotal } = process.memoryUsage();
  const usedMB = (heapUsed / 1024 / 1024).toFixed(1);
  const totalMB = (heapTotal / 1024 / 1024).toFixed(1);
  console.log(`Heap: ${usedMB}MB / ${totalMB}MB`);
}, 10000);

Signs of a Memory Leak

  • heapUsed grows steadily over time without returning to a baseline
  • Response times gradually increase
  • Process OOM-killed periodically
  • Node.js emits MaxListenersExceededWarning

Common wrong answer / trap: Calling a sawtooth graph a leak. Heap usage that rises and drops back after major GCs is normal; a leak is a rising baseline (the troughs climb).

Follow-up: "Do you need the heapdump package?" — No. Node has built-in --heapsnapshot-signal=SIGUSR2, v8.writeHeapSnapshot() and --heapsnapshot-near-heap-limit=N (see next question).

Q: Walk me through finding a leak with heap snapshots.

The reliable technique is the three-snapshot comparison:

  1. Start the service and warm it up (caches filled, JIT done). Take snapshot 1.
  2. Apply the suspect load (e.g. 10,000 requests). Force a GC (DevTools trash-can button, or --expose-gc + global.gc()). Take snapshot 2.
  3. Repeat the same load again. Take snapshot 3.
  4. In DevTools, open snapshot 3, choose Comparison against snapshot 2 (or "Objects allocated between snapshots 1 and 2" that still exist in 3). Sort by # Delta / Retained Size.
  5. Click the growing constructor and read the Retainers panel bottom-up: it shows the chain from a GC root (a module-level Map, an emitter's listener array, a timer) to your objects. That chain is the bug.
// Run: node --expose-gc leak-demo.js
const v8 = require('node:v8');
const fs = require('node:fs');
const leaks = new Map(); // the bug: never evicted

function handleRequest(id, round) { leaks.set(id, { id, payload: new Array(1000).fill(round) }); }

for (let round = 1; round <= 3; round++) {
  for (let i = 0; i < 2000; i++) handleRequest(`${round}-${i}`, round);
  global.gc();
  const file = v8.writeHeapSnapshot(); // writes Heap.<date>.<time>.<pid>.0.<n>.heapsnapshot
  console.log(`round ${round}: heapUsed=${(process.memoryUsage().heapUsed / 1e6).toFixed(1)}MB -> ${file}`);
}
// Verified: heapUsed 20.5MB -> 36.8MB -> 53.1MB (~16 MB per round, never freed).
// Load the files in DevTools > Memory and compare: the delta is Array objects retained by `leaks`.
for (const f of fs.readdirSync('.')) if (f.endsWith('.heapsnapshot')) fs.unlinkSync(f); // tidy up

In production, prefer:

node --heapsnapshot-near-heap-limit=2 server.js   # auto-write up to 2 snapshots as the heap nears its limit
node --heapsnapshot-signal=SIGUSR2 server.js      # kill -USR2 <pid> writes a snapshot

Common wrong answer / trap: Taking a snapshot of a live production process without thinking — writing a snapshot pauses the event loop and needs roughly the heap size again in memory. On a 3 GB heap that can mean a multi-second pause and an OOM-kill. Drain the instance from the load balancer first.

Follow-up: "The heap is flat but RSS keeps growing. Now what?" — Look outside the JS heap: external/arrayBuffers (Buffers held somewhere), native addons, or allocator fragmentation (glibc malloc arenas — try MALLOC_ARENA_MAX=2 or jemalloc).

ESM / CommonJS Interop

Q: How do you import CommonJS from ESM, and why do named imports sometimes fail?

ESM can import CommonJS. The default import is always module.exports. Named imports work only for names Node can find by statically analysing the CJS source (the cjs-module-lexer), because ESM must know export names before any code runs.

// cjs2.cjs
exports.named = 'n';
exports.other = 1;

// imp2.mjs — run: node imp2.mjs
import cjs, { named } from './cjs2.cjs';
console.log(cjs, named); // { named: 'n', other: 1 } n

But with an object literal of values the lexer can't see:

// cjsmod.cjs
module.exports = { named: 'n', other: 1 };

// imp.mjs
import { named } from './cjsmod.cjs';
// SyntaxError: Named export 'named' not found. The requested module './cjsmod.cjs'
// is a CommonJS module, which may not support all module.exports as named exports.

The fix the error itself suggests: import pkg from './cjsmod.cjs'; const { named } = pkg;. Also available in ESM: createRequire(import.meta.url) gives you a require function, and import.meta.dirname / import.meta.filename replace __dirname / __filename.

Common wrong answer / trap: "Named imports from CJS always work" or "never work." They work when the exports are detectable (exports.x = …, module.exports = { a, b } with shorthand identifiers, re-exports via require), and fail for dynamically built exports.

Follow-up: "What is the dual-package hazard?" — Publishing both CJS and ESM builds can load two copies of your package in one app (one via require, one via import), so instanceof checks and singletons break. Mitigate with an ESM-only package plus require(esm), or a CJS core with a thin ESM wrapper.

Q: Can you require() an ES module now?

Yes. require(esm) lets CommonJS synchronously load an ES module that has no top-level await. It shipped unflagged in Node 22.12 and 20.19 (and 23+), so it is on by default in every supported LTS line in 2026. process.features.require_module is true when it's available.

// esm-lib.mjs
export const answer = 42;
export default function hello() { return 'hi'; }

// cjs-req.cjs — run: node cjs-req.cjs   (Node 22.13, no flags)
const m = require('./esm-lib.mjs');
console.log(m.answer, typeof m.default, m.default()); // 42 function hi
console.log(process.features.require_module);        // true

Requiring an ESM module that uses top-level await throws ERR_REQUIRE_ASYNC_MODULE (verified), because require is synchronous and cannot wait. You get the module namespace object back, so the default export is m.default, not m (unless the module exports a "module.exports" named export to customise what require returns).

Common wrong answer / trap: "You must use dynamic import() from CommonJS." That was true until late 2024. Dynamic import() still works and is required when the module uses top-level await.

Follow-up: "Does this mean libraries can go ESM-only?" — Mostly yes for consumers on supported Node versions. Bundlers and tools like Jest's CJS mode can still lag, so check your consumers' toolchain.

Testing

Q: How do you test with the built-in node:test runner?

node:test (stable since Node 20) gives you test/describe/it, hooks, subtests, mocking (functions, methods, timers, modules in recent versions), snapshot testing, coverage (--experimental-test-coverage) and reporters (TAP, spec, JUnit). Paired with node:assert/strict, many projects no longer need Jest or Mocha.

// Run: node --test sum.test.mjs
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';

const sum = (a, b) => a + b;

describe('sum', () => {
  test('adds', () => assert.equal(sum(2, 3), 5));

  test('mock timers', (t) => {
    t.mock.timers.enable({ apis: ['setTimeout'] });
    const fn = t.mock.fn();
    setTimeout(fn, 1000);
    t.mock.timers.tick(1000);           // no real waiting
    assert.equal(fn.mock.callCount(), 1);
  });

  test('async rejects', async () => {
    await assert.rejects(Promise.reject(new Error('x')), /x/);
  });
});
// # tests 3   # suites 1   # pass 3   # fail 0

Useful flags: node --test (auto-discovers *.test.*, test/** etc.), --test-only with test.only, --test-name-pattern="sum", --test --watch, --test-concurrency, --test-reporter=spec. Each test file runs in its own subprocess by default, which gives isolation.

Common wrong answer / trap: Using non-strict assert.equal (== semantics, so assert.equal(1, '1') passes). Import node:assert/strict. Second trap: forgetting to await an async assertion — assert.rejects returns a promise; without await the test passes before it checks.

Follow-up: "When would you still choose Vitest or Jest?" — Front-end code needing jsdom, a large existing suite, or ecosystem plugins. See Jest vs Vitest.

Security

Q: Common Node.js security issues

VulnerabilityExamplePrevention
Prototype pollutionJSON.parse of untrusted input setting __proto__Validate input, use Object.create(null), freeze prototypes
Path traversalfs.readFile(req.query.file)Validate and resolve paths, use path.resolve + check prefix
ReDoSRegex with catastrophic backtrackingUse re2 library, test regex with rxxr2, set timeouts
Command injectionexec('ls ' + userInput)Use execFile with argument arrays, never string interpolation
Denial of serviceNo request size limitSet maxBodySize, use rate limiting, timeouts

Correction (2026-11-09): the "GOOD" path-traversal example used filePath.startsWith(SAFE_DIR). That accepts sibling directories that share the prefix: path.resolve('/var/app/uploads', '../uploads-evil/x') is /var/app/uploads-evil/x, which starts with /var/app/uploads. The check must compare against SAFE_DIR + path.sep (or use path.relative), as fixed below. Verified results: a.png → allowed, ../../etc/passwd → blocked, ../uploads-evil/x → naive check allowed, fixed check blocked, /etc/passwd → blocked.

// PATH TRAVERSAL — BAD
app.get('/files/:name', (req, res) => {
  res.sendFile(req.params.name); // ../../etc/passwd
});

// PATH TRAVERSAL — GOOD
const path = require('path');
const SAFE_DIR = '/var/app/uploads';

app.get('/files/:name', (req, res) => {
  const filePath = path.resolve(SAFE_DIR, req.params.name);
  if (!filePath.startsWith(SAFE_DIR + path.sep)) {
    return res.status(403).send('Forbidden');
  }
  res.sendFile(filePath);
});

// COMMAND INJECTION — BAD
const { exec } = require('child_process');
exec(`convert ${userInput} output.png`); // Shell injection!

// COMMAND INJECTION — GOOD
const { execFile } = require('child_process');
execFile('convert', [userInput, 'output.png']); // Arguments array

The runnable check, which also works on Windows paths:

// Run: node path.js
const path = require('node:path');
function isInside(base, userPath) {
  const target = path.resolve(base, userPath);
  const rel = path.relative(base, target);
  return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
}
const base = path.resolve('uploads');
for (const p of ['a.png', '../../etc/passwd', '../uploads-evil/x', '/etc/passwd']) {
  console.log(p.padEnd(20), isInside(base, p));
}
// a.png true, ../../etc/passwd false, ../uploads-evil/x false, /etc/passwd false

Even with this check, symlinks inside the directory can point outside it; resolve with fs.realpath before checking if users can create links, and URL-decode exactly once before checking. For broader coverage see Secure Coding.

Common wrong answer / trap: "Just strip ../ from the input." Attackers use ....//, URL-encoding (%2e%2e%2f), absolute paths and backslashes on Windows. Resolve then check containment; never sanitise by string replacement.

Follow-up: "Which of these does npm audit catch?" — Only known-vulnerable dependencies. Your own path, regex and injection bugs need code review, linters (e.g. eslint-plugin-security) and SAST.

Q: What is prototype pollution, and how do you prevent it?

If code recursively merges attacker-controlled JSON into an object, a key named __proto__ walks up to Object.prototype and adds properties to every object in the process.

// Run: node proto.js
function merge(t, s) {
  for (const k in s) {
    if (typeof s[k] === 'object' && s[k] !== null) { t[k] ??= {}; merge(t[k], s[k]); }
    else t[k] = s[k];
  }
  return t;
}
merge({}, JSON.parse('{"__proto__":{"isAdmin":true}}'));
console.log(({}).isAdmin); // true  <- every object is now an admin
delete Object.prototype.isAdmin;

JSON.parse itself is safe — it creates an own property literally named "__proto__". The danger is the merge: t['__proto__'] is the accessor that returns Object.prototype. Real CVEs of this shape hit lodash.merge, jQuery.extend and many query-string parsers; impact ranges from auth bypass (if (user.isAdmin)) to RCE via polluted options passed to child_process.spawn.

Defences, strongest first:

  1. Validate input against a schema (zod, ajv with additionalProperties: false) before merging.
  2. Skip dangerous keys: if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;.
  3. Use Object.create(null) or Map for dictionaries built from user keys — 'toString' in Object.create(null) is false.
  4. Run with node --disable-proto=delete (removes the __proto__ accessor) or freeze Object.prototype at startup in services that can tolerate it.

Common wrong answer / trap: "Object.assign is safe so I'm fine." Object.assign with a parsed __proto__ key doesn't pollute globally, but it sets the target's prototype (verified: o.x === 1, ({}).x === undefined, and Object.getPrototypeOf(o) !== Object.prototype). Spread ({...obj}) defines own properties and is safe in that respect.

Follow-up: "Find the gadget." — Pollution needs a gadget to matter: code that reads a property that's usually undefined (options.shell, opts.isAdmin). Interviewers like asking how pollution turns into RCE through spawn options.

Q: What is ReDoS and how do you defend against it?

V8's regex engine (Irregexp) is a backtracking engine. Patterns with nested quantifiers or overlapping alternatives can take exponential time on inputs that almost match. Because Node runs your code on one thread, one malicious request can freeze the entire server.

// Run: node redos.js
const re = /^(a+)+$/;
re.test('aaaa!'); // warm up
for (const n of [22, 24, 26, 28]) {
  const s = 'a'.repeat(n) + '!';
  const t = performance.now();
  re.test(s);
  console.log(n, (performance.now() - t).toFixed(0) + 'ms');
}
// Verified on Node 22: 22 26ms, 24 88ms, 26 322ms, 28 1459ms  (~2x per extra char)

const fixed = /^a+$/;
const t = performance.now();
fixed.test('a'.repeat(100000) + '!');
console.log('fixed', (performance.now() - t).toFixed(2) + 'ms'); // fixed 0.15ms

Defences: rewrite the pattern to remove ambiguity ((a+)+ → a+; (\w+\s?)+$ → a tokenizer); cap input length before matching; use a linear-time engine (re2 bindings) for user-supplied patterns; lint with eslint-plugin-regexp / safe-regex; move risky parsing into a worker with a timeout. More on how backtracking works in Regex Mastery.

Common wrong answer / trap: "Set a timeout on the regex." JavaScript has no regex timeout — a running test() can't be interrupted on the main thread. The only way to time-box it is to run it in a worker and terminate the worker.

Follow-up: "Which common patterns are dangerous?" — Email and URL validators with nested groups, (.*a){n}, and ^(\d+)*$-style anchors. Many real CVEs (e.g. in ua-parser-js, moment, semver) were ReDoS.

Graceful Shutdown and Cancellation

Q: How do you shut down an HTTP server gracefully?

When an orchestrator stops a container it sends SIGTERM, waits a grace period (30 s by default in Kubernetes), then sends SIGKILL. A graceful shutdown uses that window to:

  1. Fail the readiness probe so the load balancer stops sending new traffic (and wait a few seconds for endpoints to update).
  2. server.close() — stop accepting new connections; in-flight requests continue.
  3. Close idle keep-alive sockets (server.closeIdleConnections(), Node 18.2+), otherwise close() waits for clients to hang up.
  4. Close databases, queues and flush logs/telemetry.
  5. Exit with 0, with a hard timeout fallback that exits 1.
// Run: node shutdown.js — simulates SIGTERM during an in-flight request
const http = require('node:http');
const server = http.createServer((req, res) => setTimeout(() => res.end('done\n'), 300));

server.listen(0, async () => {
  const port = server.address().port;
  const inflight = fetch(`http://127.0.0.1:${port}/`).then((r) => r.text());
  setTimeout(() => process.emit('SIGTERM'), 50); // pretend the orchestrator sent it
  console.log('in-flight response:', (await inflight).trim());
});

let shuttingDown = false;
process.on('SIGTERM', () => {
  if (shuttingDown) return;
  shuttingDown = true;
  console.log('SIGTERM: stop accepting');
  server.close(() => { console.log('all connections closed, exiting'); process.exit(0); });
  server.closeIdleConnections();
  setTimeout(() => { console.error('force exit'); process.exit(1); }, 10_000).unref();
});
// Verified:
// SIGTERM: stop accepting
// in-flight response: done
// all connections closed, exiting
sequenceDiagram
    participant K as "Orchestrator"
    participant N as "Node process"
    participant LB as "Load balancer"
    K->>N: SIGTERM
    N->>LB: readiness probe now fails
    N->>N: server.close() and close idle sockets
    N->>N: finish in-flight requests
    N->>N: close DB pool and flush logs
    N->>K: exit 0 before grace period ends

Common wrong answer / trap: Running Node as PID 1 via npm start in Docker. npm (and some shells) don't forward SIGTERM to the child, so the app never sees it and is SIGKILLed after the grace period. Use CMD ["node", "server.js"] or docker run --init. Also: the hard-timeout timer must be .unref()ed so it doesn't itself keep the process alive.

Follow-up: "How do you stop long-running work (a big export) during shutdown?" — Pass an AbortSignal down to it and abort on SIGTERM (next question).

Q: How does AbortController work in Node, and where can you use it?

AbortController is the web-standard cancellation primitive. Most Node async APIs accept { signal }: fetch, fs.readFile, timers/promises, events.once, stream.pipeline, child_process.spawn, readline, and more. AbortSignal.timeout(ms) and AbortSignal.any([...]) cover timeouts and combined cancellation.

// Run: node ab.mjs
import { setTimeout as sleep } from 'node:timers/promises';

try {
  await sleep(1000, null, { signal: AbortSignal.timeout(50) });
} catch (e) { console.log(e.name, e.code); }          // AbortError ABORT_ERR

const ac = new AbortController();
const p = sleep(1000, null, { signal: ac.signal });
ac.abort();
try { await p; } catch (e) { console.log(e.name); }   // AbortError

const any = AbortSignal.any([AbortSignal.timeout(20), new AbortController().signal]);
any.addEventListener('abort', () => console.log('any aborted:', any.reason.name)); // TimeoutError
await sleep(40);

In your own functions, check signal.throwIfAborted() between steps and listen for 'abort' to clean up.

Common wrong answer / trap: Believing abort stops the underlying work everywhere. It only works for code that checks the signal. A synchronous CPU loop or a database driver that ignores the signal keeps running. Second trap: adding an 'abort' listener per request to a long-lived shared signal without { once: true } — that's a listener leak.

Follow-up: "Note the different error names?" — fetch aborted by AbortSignal.timeout rejects with TimeoutError; a manual abort() gives AbortError. Check err.name for both.


Staff

Sandboxing and Isolation

Q: What is the Node.js permission model and is it a security boundary?

The permission model restricts what a Node process can touch. Enable it with --permission and grant capabilities explicitly:

node --permission --allow-fs-read=/app --allow-fs-write=/app/tmp server.js
# other grants: --allow-child-process, --allow-worker, --allow-addons, --allow-wasi
# (newer releases add --allow-net and more)
node --permission -e "console.log(process.permission.has('fs.read'))"   # false

A denied access throws ERR_ACCESS_DENIED with a permission field (verified on Node 22.13: reading C:\Windows\win.ini with only the temp directory granted gives permission: 'FileSystemRead'). At runtime, process.permission.has(scope, ref) checks a grant and process.permission.drop() irreversibly gives one up — useful to read config at startup and then drop file access.

Correction (2026-11-09): the quick-fire table said the flag is --experimental-permission. The permission model left experimental status in Node 22.13.0 and 23.5.0, and the flag is now --permission (Node.js permissions docs).

It is not a sandbox for malicious code. The docs call it a "seat belt" for trusted code: symbolic links are followed outside granted paths, existing file descriptors bypass checks, workers don't inherit it if you pass explicit execArgv, and some modules aren't covered. For untrusted code, use OS-level isolation (containers with seccomp, gVisor, separate VMs, or V8 isolates in a separate process).

Common wrong answer / trap: "Run user plugins in vm.runInNewContext with --permission and you're safe." vm is explicitly not a security mechanism (this.constructor.constructor('return process')() escapes classic contexts), and the permission model can be bypassed by malicious code.

Follow-up: "How would you use it for supply-chain defence?" — Run build scripts and CLIs with no --allow-child-process and only the project directory readable, so a compromised dependency can't read ~/.ssh or spawn curl. Combine with npm ci --ignore-scripts.

Performance and Profiling

Q: How do you measure event-loop health with perf_hooks?

Three numbers tell you whether a Node service is CPU-starved:

  • Event loop delay (monitorEventLoopDelay): how late timers fire. p99 above ~50–100 ms means requests are queuing behind synchronous work.
  • Event loop utilization (performance.eventLoopUtilization()): fraction of time the loop was busy, 0–1. Unlike CPU %, it isolates the main thread. ~0.9+ means saturation — scale out or move work off-thread.
  • User timings (performance.mark/measure, PerformanceObserver, performance.timerify): your own spans.
// Run: node perf2.js
const { performance, monitorEventLoopDelay } = require('node:perf_hooks');
const h = monitorEventLoopDelay({ resolution: 10 });
h.enable();
const elu1 = performance.eventLoopUtilization();

setTimeout(() => {
  performance.mark('a');
  const end = Date.now() + 200; while (Date.now() < end) {} // block 200 ms
  performance.mark('b');
  const m = performance.measure('busy loop', 'a', 'b');
  console.log(m.name, Math.round(m.duration) + 'ms');
}, 50);

setTimeout(() => {
  h.disable();
  console.log('p99 loop delay ~', Math.round(h.percentile(99) / 1e6), 'ms, max ~', Math.round(h.max / 1e6), 'ms');
  console.log('ELU', performance.eventLoopUtilization(elu1).utilization.toFixed(2));
}, 400);
// Verified: busy loop 200ms / p99 loop delay ~ 218 ms, max ~ 218 ms / ELU 0.49

Export these as metrics (Prometheus prom-client has built-in event-loop-lag collectors; OpenTelemetry has runtime metrics) and alert on p99 delay and ELU, not just CPU.

Common wrong answer / trap: Measuring blocking that happens before the loop starts. A busy loop at the top of the main script isn't visible to the histogram or ELU — ELU is measured from loop start. The demo above blocks inside a timer for this reason. Also: CPU 100% on a container with 4 cores can mean one saturated main thread (25%) plus GC threads — use ELU.

Follow-up: "ELU is 0.95 but CPU-heavy code is nowhere in your code. What's using the loop?" — Usually JSON serialisation of large responses, GC (check --trace-gc or perf_hooks GC entries), sync crypto/zlib, logging with sync destinations, or template rendering. Profile it.

Q: How do you find a CPU hotspot? Explain flamegraphs.

A CPU profile samples the call stack every ~1 ms. A flamegraph draws those samples: the x-axis is the share of samples (not time order), the y-axis is stack depth, and each box's width is the proportion of time that function was on the stack. Wide boxes near the top ("plateaus") are where the CPU actually burns.

# 1. Built-in V8 profiler — writes a .cpuprofile you open in Chrome DevTools > Performance
node --cpu-prof --cpu-prof-dir=./profiles server.js
#    (generate load with autocannon, then stop the process)
npx autocannon -c 50 -d 20 http://localhost:3000/

# 2. Live: attach DevTools
node --inspect server.js   # chrome://inspect → Profiler → Start/Stop

# 3. Flamegraph tooling
npx 0x server.js           # produces an interactive HTML flamegraph
#    Linux perf with JIT symbols:
node --perf-basic-prof server.js & perf record -F 99 -p $! -g -- sleep 30
// Run: node --cpu-prof hot.js  → open the CPU.*.cpuprofile in DevTools
const crypto = require('node:crypto');
function slowHash(s) { // the hotspot: sync pbkdf2 on the main thread
  return crypto.pbkdf2Sync(s, 'salt', 50_000, 32, 'sha256').toString('hex');
}
function handler(i) { return slowHash(`user-${i}`).slice(0, 8); }
let out = '';
for (let i = 0; i < 50; i++) out = handler(i);
console.log('last', out);
// The flamegraph shows handler → slowHash → pbkdf2Sync as one wide tower.

The fix here is crypto.pbkdf2 (async, threadpool) or moving it into a worker. --heap-prof does the same sampling for allocations, which finds GC pressure.

Common wrong answer / trap: Reading the x-axis as time. Flamegraphs are aggregated and sorted alphabetically; use a "flame chart" (DevTools timeline) for chronology. Another trap: profiling in dev with NODE_ENV=development — frameworks like Express do extra work in dev mode, so you optimise the wrong thing.

Follow-up: "The profile is mostly (garbage collector). Now what?" — Allocation profile (--heap-prof), look for per-request large allocations (big JSON.parse, string concatenation, array copies), and consider raising --max-semi-space-size to reduce scavenge frequency for high-allocation services.

Scaling HTTP Servers

Q: How do you scale a Node HTTP service from one core to many machines?

A layered answer interviewers look for:

  1. Make one process efficient. Keep the event loop free (ELU < ~0.7 at peak), stream large responses, use connection pools for DBs and an HTTP keep-alive agent for upstreams (undici pools by default), cache hot reads, avoid sync APIs.
  2. Use all cores. One process per core, via cluster/PM2 on VMs, or one process per container with N replicas on Kubernetes. Prefer the orchestrator: it already does restarts, rolling deploys and health checks.
  3. Stay stateless. Sessions in Redis or signed cookies, uploads in object storage, WebSocket fan-out through a pub/sub (Redis, NATS), so any instance can serve any request.
  4. Put a proxy/load balancer in front. TLS termination, HTTP/2 to clients, buffering slow clients, rate limiting.
  5. Set timeouts deliberately. server.requestTimeout (default 300 s), server.headersTimeout (default 60 s) and server.keepAliveTimeout (default 5 s). The keep-alive timeout must be longer than the load balancer's idle timeout, or you get sporadic 502s when Node closes a socket the LB is about to reuse.
  6. Shed load. When ELU or event-loop delay passes a threshold, return 503 quickly (e.g. under-pressure for Fastify) instead of queuing until everything times out.
// Run: node server-tuned.js
const http = require('node:http');
const { performance } = require('node:perf_hooks');

let elu = performance.eventLoopUtilization();
let busy = 0;
setInterval(() => {
  const next = performance.eventLoopUtilization();
  busy = performance.eventLoopUtilization(next, elu).utilization;
  elu = next;
}, 500).unref();

const server = http.createServer((req, res) => {
  if (busy > 0.9) { res.writeHead(503, { 'retry-after': '1' }); return res.end('overloaded\n'); }
  res.end('ok\n');
});
server.keepAliveTimeout = 65_000;    // > typical 60 s LB idle timeout
server.headersTimeout = 66_000;      // must exceed keepAliveTimeout
server.requestTimeout = 30_000;      // bound slow uploads
server.listen(3000, () => console.log('listening on 3000'));

Common wrong answer / trap: "Add more cluster workers" as the answer to every scaling question. If the bottleneck is the database, more Node processes make it worse (more connections, more contention). Measure first: ELU high → CPU-bound Node, scale out or optimise; ELU low but latency high → downstream bottleneck.

Follow-up: "How many DB connections do 10 pods × 8 workers × pool size 20 open?" — 1,600. That's more than a default Postgres max_connections (100) allows; you need PgBouncer or smaller pools. Interviewers love this arithmetic.

Observability

Q: How do you propagate a request ID through async code without passing it everywhere?

AsyncLocalStorage (from node:async_hooks, stable) stores a value that follows the async call chain — through await, timers, promises and event callbacks — the way thread-locals work in threaded runtimes. Logging libraries, OpenTelemetry and APM agents use it for trace context.

// Run: node als.js
const { AsyncLocalStorage } = require('node:async_hooks');
const als = new AsyncLocalStorage();

function log(msg) { console.log(`[${als.getStore()?.reqId ?? '-'}] ${msg}`); }

for (const reqId of ['r1', 'r2']) {
  als.run({ reqId }, () => setTimeout(() => log('handled'), reqId === 'r1' ? 20 : 5));
}
log('outside');
// Verified:
// [-] outside
// [r2] handled
// [r1] handled

In an HTTP server, wrap each request: server.on('request', (req, res) => als.run({ reqId: req.headers['x-request-id'] ?? crypto.randomUUID() }, () => handler(req, res))).

Common wrong answer / trap: Storing the ID in a module-level variable ("currentRequestId"). With concurrent requests, request A's logs get request B's ID as soon as A awaits. Another trap: libraries with their own connection pools or custom thenables can "lose" the context — test it and bind with AsyncResource.bind if needed.

Follow-up: "What does it cost?" — Since Node 16 with the promise-hook optimisation it's small (low single-digit percent in most benchmarks), and newer V8 builds implement it via AsyncContextFrame for even lower overhead. Measure with your workload.

Q: Design question — p99 latency doubled after a deploy, with no errors. How do you investigate?

A structured answer:

  1. Scope it. All routes or one? All pods or some? Correlate with the deploy diff, traffic volume and downstream latency (DB, caches, third-party APIs) on the dashboards.
  2. Check the event loop. Event-loop delay and ELU per pod. High delay → something synchronous got added (bigger JSON payloads, a sync library call, a regex). Low delay but slow requests → waiting on something downstream, or threadpool saturation.
  3. Threadpool. New fs, dns.lookup, zlib or crypto usage can queue behind 4 threads — every hostname lookup waits. UV_THREADPOOL_SIZE and DNS caching are quick tests.
  4. GC. Compare heap and GC time before/after (--trace-gc on one canary, or runtime metrics). A new per-request allocation can push scavenges from rare to constant.
  5. Profile one canary. --cpu-prof or a 30 s DevTools profile under production-like load; compare flamegraphs before and after.
  6. Connection pools. Pool size changes, a lost keep-alive agent (new TLS handshake per call), or keepAliveTimeout mismatches with the LB.
  7. Mitigate first. Roll back while investigating if the impact is real; diagnose on a canary.
// Runtime snapshot to log (or expose behind auth) on each pod — Run: node doctor.js
const { performance, monitorEventLoopDelay } = require('node:perf_hooks');
const h = monitorEventLoopDelay(); h.enable();
setTimeout(() => {
  const m = process.memoryUsage();
  console.log({
    elu: performance.eventLoopUtilization().utilization.toFixed(2),
    loopDelayP99ms: Math.round(h.percentile(99) / 1e6),
    heapUsedMB: Math.round(m.heapUsed / 1e6), rssMB: Math.round(m.rss / 1e6),
    activeResources: process.getActiveResourcesInfo(),
  });
}, 1000);

Common wrong answer / trap: Jumping straight to "add more pods." If the cause is a sync call or a downstream slowdown, more pods hide the symptom and multiply the downstream load. Another trap: profiling locally with no load — most event-loop problems only appear under concurrency.

Follow-up: "Event-loop delay is flat, CPU is low, latency is still high. Name three causes." — Threadpool saturation (fs/dns), connection-pool exhaustion (waiting for a DB connection), and a slower downstream dependency; distributed tracing spans make the third obvious.


Quick-Fire Questions

QuestionAnswer
require vs import?require is CommonJS (synchronous, dynamic). import is ESM (asynchronous, static analysis, tree-shakeable).
What is package.json "type": "module"?Tells Node to treat .js files as ESM instead of CommonJS.
What does --permission do?The permission model (added in Node 20 as --experimental-permission, stable as --permission since 22.13/23.5) — restricts file system, child process, worker and addon access. Not a sandbox for malicious code.
How to read env vars?process.env.MY_VAR. Use dotenv or Node 20.6+ --env-file flag.
What is AbortController?Cancellation mechanism for async operations. Pass signal to fetch, setTimeout, fs.readFile, etc.
Express vs Fastify?Fastify is ~3x faster in hello-world benchmarks (schema-based serialization, radix-tree routing rather than regex matching). Express has larger ecosystem. Note (2026-11-09): the gap is benchmark-dependent and shrinks to a few percent once a route does real I/O; Express 5 (stable since late 2024) now forwards rejected promises from async handlers to error middleware.
What is node: prefix?require('node:fs') — explicitly import built-in modules. Prevents name collision with npm packages.
Can Node run TypeScript directly?Yes, by type stripping: --experimental-strip-types in Node 22.6+, enabled by default in newer releases. Only erasable syntax is supported (no enum or namespace unless you add --experimental-transform-types), and there is no type-checking — still run tsc --noEmit in CI.
What does process.exitCode = 1 do vs process.exit(1)?exitCode sets the code but lets pending work (log flushes, stdout writes) finish; exit() terminates immediately. Prefer exitCode.
What is --inspect?Opens the V8 inspector (Chrome DevTools protocol) on 127.0.0.1:9229. Never bind it to 0.0.0.0 in production — it is remote code execution.