Skip to main content
Backend & Systems

Node.js Interview Questions

All Levels (Junior to Staff)16 Questions

Node.js runtime internals: libuv thread pool sizing, non-blocking I/O, event emitter patterns, stream backpressure, cluster module, and worker threads.

22 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Node.js Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

How do CommonJS (CJS) and ES Modules (ESM) differ in Node.js module loading and interoperability?

Senior Engineering Answer

CommonJS (require/module.exports) loads modules synchronously at runtime, caches the exported object by resolved file path, and allows conditional dynamic requires inside functions. ES Modules (import/export), enabled via '.mjs' or "type": "module" in package.json, resolve the entire static dependency graph asynchronously before execution, support top-level await, and expose live read-only bindings. An ESM file can import a CJS module, and modern Node.js (v22.12+/v20.19+) also supports synchronous require() of ESM graphs that do not contain top-level await.

Production Code Example
// package.json: { "type": "module" }
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";

// Load legacy CJS-only JSON or native addon cleanly inside ESM
const require = createRequire(import.meta.url);
const pkg = require("./package.json");
Common Interview Trap / Anti-Pattern:

In ESM, __filename and __dirname do not exist; use import.meta.dirname and import.meta.filename (Node 20.11+) or fileURLToPath(import.meta.url).

Question #2FundamentalJunior

Why does calling fs.readFileSync() or JSON.parse() on huge payloads inside an HTTP handler degrade Node.js throughput?

Senior Engineering Answer

Node.js executes JavaScript application code on a single main event-loop thread. Synchronous methods like fs.readFileSync(), crypto.pbkdf2Sync(), or synchronous parsing of a 50MB JSON string block that thread until completion—preventing the event loop from accepting new TCP connections, firing timers, or flushing responses for thousands of concurrent requests. Always use async fs/promises or streaming parsers inside request handlers.

Production Code Example
import { readFile } from "node:fs/promises";
import http from "node:http";

const server = http.createServer(async (req, res) => {
  const config = await readFile(new URL("./config.json", import.meta.url), "utf8");
  res.writeHead(200, { "content-type": "application/json" });
  res.end(config);
});
Common Interview Trap / Anti-Pattern:

Synchronous fs calls are acceptable ONLY during one-time startup initialization before the HTTP server begins listening, never inside per-request handlers.

Question #3FundamentalJunior

What is a Node.js Buffer, and why does calling chunk.toString('utf8') on streaming binary chunks corrupt multi-byte characters?

Senior Engineering Answer

A Node.js Buffer is a fixed-size, raw binary memory allocation outside the V8 JS heap (a subclass of Uint8Array) used for TCP sockets, file I/O, and cryptography. In UTF-8, emojis and non-ASCII characters take 2 to 4 bytes; a network or file stream can split a multi-byte character across two consecutive Buffer chunks. Calling chunk.toString('utf8') independently on each chunk turns split trailing/leading bytes into U+FFFD replacement characters. Use StringDecoder (or setEncoding('utf8')) to buffer incomplete trailing sequences until the next chunk arrives.

Production Code Example
import { StringDecoder } from "node:string_decoder";

const decoder = new StringDecoder("utf8");
const part1 = Buffer.from([0xF0, 0x9F]);       // first half of rocket emoji
const part2 = Buffer.from([0x9A, 0x80]);       // second half

console.log(decoder.write(part1)); // '' (holds incomplete bytes)
console.log(decoder.write(part2)); // '🚀'
console.log(decoder.end());
Common Interview Trap / Anti-Pattern:

Using Buffer.allocUnsafe(size) without overwriting every byte can leak sensitive stale process memory (secrets, prior keys) if sent over a socket; prefer Buffer.alloc(size) for untrusted outputs.

Question #4FundamentalJunior

How does Node.js EventEmitter dispatch events, and why does an unhandled 'error' event crash the process?

Senior Engineering Answer

EventEmitter invokes registered listeners synchronously in registration order when emit(eventName, ...args) is called—meaning slow listeners block the caller and throw exceptions directly up the emit stack. Special-cased by Node.js, emitting an 'error' event when zero 'error' listeners are attached throws the Error object uncaught and terminates the Node process immediately so silent failures do not go unnoticed.

Production Code Example
import { EventEmitter } from "node:events";

const bus = new EventEmitter();
bus.on("error", (err) => {
  console.error("Handled stream/bus error:", err.message);
});

bus.emit("error", new Error("upstream reset")); // does not crash
Common Interview Trap / Anti-Pattern:

Attaching a new listener inside a per-request handler without calling emitter.off(...) on teardown leaks memory and triggers MaxListenersExceededWarning once >10 listeners accumulate.

Question #5IntermediateMid

Walk through the 6 phases of the Node.js event loop and compare process.nextTick(), queueMicrotask(), and setImmediate().

Senior Engineering Answer

Libuv's event loop cycles through 6 phases: (1) Timers (expired setTimeout/setInterval callbacks), (2) Pending callbacks (deferred OS I/O errors), (3) Idle/Prepare (internal), (4) Poll (waits for and executes incoming network/fs I/O callbacks), (5) Check (setImmediate callbacks), and (6) Close callbacks (socket.on('close')). Between callbacks/phases, Node drains the nextTick queue FIRST, followed by the Promise/queueMicrotask queue. Consequently, recursive process.nextTick() starves I/O completely, whereas setImmediate() runs in the Check phase right after Poll—and inside an I/O callback, setImmediate() always fires before setTimeout(..., 0).

Production Code Example
import fs from "node:fs";

fs.readFile(import.meta.filename, () => {
  setTimeout(() => console.log("3: setTimeout 0"), 0);
  setImmediate(() => console.log("2: setImmediate (Check phase)"));
  process.nextTick(() => console.log("1: nextTick (before next phase)"));
});
Common Interview Trap / Anti-Pattern:

Calling process.nextTick() recursively in a retry loop prevents the event loop from ever reaching the Poll phase, starving all incoming HTTP requests.

Question #6IntermediateMid

Which Node.js APIs actually use libuv's thread pool (UV_THREADPOOL_SIZE) versus non-blocking OS kernel sockets?

Senior Engineering Answer

TCP/UDP sockets, HTTP servers, pipes, and timers do NOT use the libuv thread pool—they use OS kernel asynchronous I/O multiplexing (epoll on Linux, kqueue on macOS, IOCP on Windows) on the single event loop thread. However, operations lacking portable async kernel primitives—all fs.* file I/O, dns.lookup() (POSIX getaddrinfo), CPU-bound crypto (pbkdf2, scrypt, randomBytes), and zlib compression—are dispatched to libuv's worker thread pool, which defaults to only 4 threads (configurable via UV_THREADPOOL_SIZE up to 1024).

Production Code Example
// Increasing UV_THREADPOOL_SIZE must happen BEFORE the first pool-using call
// Better: pass UV_THREADPOOL_SIZE=16 in process environment
import crypto from "node:crypto";

// Each call occupies 1 of the 4 default libuv worker threads
const hash = await new Promise((resolve, reject) => {
  crypto.scrypt("password", "salt", 64, (err, key) => (err ? reject(err) : resolve(key)));
});
Common Interview Trap / Anti-Pattern:

Heavy bcrypt/scrypt or fs calls can saturate all 4 libuv threads and silently stall dns.lookup() for outbound HTTP requests; set UV_THREADPOOL_SIZE appropriately or offload heavy crypto to Worker Threads.

Question #7IntermediateMid

How does stream backpressure work in Node.js, and why should you use stream.pipeline() instead of readable.pipe()?

Senior Engineering Answer

Backpressure prevents a fast Readable (e.g., reading a 10GB file from NVMe) from flooding RAM when piping to a slow Writable (e.g., a congested TCP socket). When writable.write(chunk) returns false (internal highWaterMark buffer reached), the producer must pause reading until the writable emits 'drain'. While readable.pipe() manages pause/resume automatically, it does NOT forward errors or destroy upstream/downstream streams when one side fails—leaking file descriptors and sockets. stream.pipeline() (or stream/promises pipeline) handles backpressure, propagates errors cleanly, and destroys all streams in the chain on error or abort.

Production Code Example
import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";

await pipeline(
  createReadStream("access.log"),
  createGzip(),
  createWriteStream("access.log.gz")
);
Common Interview Trap / Anti-Pattern:

Ignoring the boolean return value of res.write(chunk) in custom streaming endpoints silently buffers gigabytes into Node's heap until an OOM crash.

Question #8IntermediateMid

Why should you NOT try to keep a Node.js server alive after an 'uncaughtException', and how do you handle graceful shutdown?

Senior Engineering Answer

When an uncaughtException reaches the top level, synchronous invariants, locks, or module state may be half-mutated in an undefined state; continuing to serve requests causes subtle data corruption or leaked sockets. Log the error synchronously, initiate graceful shutdown with a fail-safe timeout, and exit non-zero so your orchestrator (Kubernetes/systemd) restarts a clean process. For normal SIGTERM shutdown, stop accepting new connections with server.close(), return 503 on health checks if needed, close idle keep-alive sockets, drain DB pools, and exit cleanly.

Production Code Example
process.on("SIGTERM", () => {
  server.close(async (err) => {
    await dbPool.end();
    process.exit(err ? 1 : 0);
  });
  setTimeout(() => process.exit(1), 10_000).unref();
});
Common Interview Trap / Anti-Pattern:

Forgetting .unref() on the shutdown force-exit timer keeps the Node event loop alive for the full 10 seconds even after all connections and DB pools finished draining in 50ms.

Question #9SeniorSenior

Compare node:cluster, node:worker_threads, and child_process: when should you choose each?

Senior Engineering Answer

node:cluster forks multiple isolated OS Node processes that share a single listening TCP port (round-robin on Linux/macOS) with independent V8 heaps and event loops—ideal for scaling HTTP/WebSocket I/O across CPU cores (though container orchestrators like Kubernetes often prefer 1 process per container scaled via pod replicas). node:worker_threads spawns multiple V8 isolates inside ONE OS process, allowing low-overhead MessagePort Transferables and SharedArrayBuffer + Atomics shared memory—ideal for offloading CPU-bound tasks (PDF generation, image encoding, ML tokenization) without blocking the HTTP loop. child_process executes external binaries (ffmpeg, python, git) in separate OS processes.

Production Code Example
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

if (isMainThread) {
  const runTask = (n: number) => new Promise((resolve, reject) => {
    const w = new Worker(new URL(import.meta.url), { workerData: n });
    w.on("message", resolve);
    w.on("error", reject);
  });
} else {
  parentPort?.postMessage(workerData * 2);
}
Common Interview Trap / Anti-Pattern:

Spawning a brand-new Worker per incoming HTTP request incurs ~30-50ms V8 isolate startup overhead and memory bloat; always maintain a bounded fixed-size worker pool (like Piscina).

Question #10SeniorSenior

How does AsyncLocalStorage propagate request trace IDs and user context safely across async/await chains?

Senior Engineering Answer

AsyncLocalStorage (from node:async_hooks) wraps V8/Node promise and callback context propagation to bind a store object to an asynchronous execution tree. Entering `als.run(store, fn)` makes `als.getStore()` return that exact request's store inside any nested promise, timer, or DB driver callback spawned within `fn`, without threading `ctx` through every function signature or risking cross-request leakage on module globals.

Production Code Example
import { AsyncLocalStorage } from "node:async_hooks";
import crypto from "node:crypto";

const requestCtx = new AsyncLocalStorage<{ traceId: string }>();

function log(msg: string) {
  const traceId = requestCtx.getStore()?.traceId ?? "none";
  console.log(`[${traceId}] ${msg}`);
}

export function handleRequest(fn: () => Promise<void>) {
  return requestCtx.run({ traceId: crypto.randomUUID() }, fn);
}
Common Interview Trap / Anti-Pattern:

Callbacks queued before entering als.run() (such as a custom internal connection pool queue or EventEmitter created outside the request) run in the queue creator's async context rather than the caller's unless wrapped with AsyncLocalStorage.bind().

Question #11SeniorSenior

Why do Node.js services behind AWS ALB or Nginx occasionally emit intermittent 502 Bad Gateway errors, and how do keepAliveTimeout and headersTimeout fix them?

Senior Engineering Answer

By default, Node's HTTP server sets server.keepAliveTimeout to 5,000ms (5s), whereas load balancers like AWS ALB default to 60s idle timeout. If Node closes a pooled TCP connection at 5.000s at the exact microsecond the ALB reuses that socket to forward a new client request, the ALB receives an unexpected TCP FIN/RST and returns 502 Bad Gateway to the client. Set `server.keepAliveTimeout` slightly HIGHER than the load balancer's idle timeout (e.g., 65,000ms) and `server.headersTimeout` slightly higher than `keepAliveTimeout` (e.g., 66,000ms).

Production Code Example
import http from "node:http";

const server = http.createServer(app);
server.keepAliveTimeout = 65_000; // > ALB 60s idle timeout
server.headersTimeout = 66_000;   // must exceed keepAliveTimeout
Common Interview Trap / Anti-Pattern:

Setting keepAliveTimeout higher than headersTimeout causes Node to abort incoming requests prematurely because headersTimeout guards header arrival across keep-alive reuse.

Question #12SeniorSenior

How does Node.js DNS resolution via dns.lookup() create hidden stalls under high outbound HTTP load?

Senior Engineering Answer

Node's default HTTP clients (http.request, fetch/undici without custom lookup) resolve hostnames with dns.lookup(), which calls the blocking C stdlib getaddrinfo() inside the 4-thread libuv pool—and performs zero DNS caching. Under bursts of outbound API calls or slow upstream DNS servers, all 4 libuv threads block on getaddrinfo(), stalling unrelated file reads and crypto calls across the entire process. Mitigate by using HTTP keep-alive connection pooling (undici Agent/Pool), caching DNS or using dns.resolve4() (true async c-ares UDP queries), or running a local node DNS cache (systemd-resolved / dnsmasq).

Production Code Example
import { Agent, setGlobalDispatcher } from "undici";

// Reuse persistent TCP+TLS connections so DNS lookup happens only on pool connect
setGlobalDispatcher(new Agent({
  connections: 50,
  keepAliveTimeout: 30_000
}));
Common Interview Trap / Anti-Pattern:

Creating a new http.Agent or disabling keep-alive per outbound request triggers a fresh TCP handshake, TLS handshake, AND blocking dns.lookup() on every single API call.

Question #13PrincipalStaff

How do you diagnose a production Node.js memory leak or P99 event-loop spike without guessing?

Senior Engineering Answer

First, separate V8 JS heap growth (process.memoryUsage().heapUsed) from native off-heap Buffer/C++ RSS growth (rss minus heapTotal / arrayBuffers). Measure event loop stalls continuously via `perf_hooks.monitorEventLoopDelay({ resolution: 20 })` exported to Prometheus. For JS heap leaks, capture two V8 heap snapshots minutes apart via `v8.writeHeapSnapshot()` or `--heapsnapshot-signal=SIGUSR2` and use Chrome DevTools Memory 'Comparison' view to inspect retained delta objects and their retainer paths. For CPU/event-loop spikes, trigger `node --cpu-prof` or `inspector` CPU profiles to spot synchronous JSON parsing, ReDoS, or megamorphic hot loops.

Production Code Example
import { monitorEventLoopDelay } from "node:perf_hooks";

const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();

setInterval(() => {
  console.log({ p99DelayMs: Math.round(h.percentile(99) / 1e6) });
  h.reset();
}, 10_000).unref();
Common Interview Trap / Anti-Pattern:

Taking a V8 heap snapshot on a container with a 2GB heap pauses the event loop for seconds and temporarily doubles RAM usage; drain the instance from the load balancer first so health checks do not kill the pod mid-snapshot.

Question #14PrincipalStaff

How do you implement zero-downtime rolling deployments for a stateful Node.js HTTP/gRPC server on Kubernetes?

Senior Engineering Answer

Because Kubernetes EndpointSlice propagation is asynchronous with SIGTERM delivery, a pod can continue receiving new traffic for 1-3 seconds after SIGTERM arrives. On SIGTERM: (1) flip a readiness flag so `/readyz` returns 503 immediately while keeping the server open briefly (`preStop: sleep 5` or short grace period) until kube-proxy/Ingress stops routing new connections, (2) call `server.close()` to stop accepting new sockets and add `Connection: close` to new responses, (3) call `server.closeIdleConnections()` (Node 18.2+) to drop idle keep-alive sockets immediately without waiting 65s, and (4) await in-flight requests/DB transactions before `process.exit(0)`.

Production Code Example
let shuttingDown = false;

function onShutdown() {
  if (shuttingDown) return;
  shuttingDown = true;
  setTimeout(() => {
    server.closeIdleConnections();
    server.close(() => process.exit(0));
  }, 3_000); // allow k8s endpoints propagation
}
Common Interview Trap / Anti-Pattern:

Immediately closing the listening socket on SIGTERM while kube-proxy still routes traffic causes connection-refused 502 errors during every deployment rollout.

Question #15PrincipalStaff

What Node.js-specific security vulnerabilities can take down or compromise a backend service, and how do you mitigate them?

Senior Engineering Answer

Key Node-specific risks include: (1) ReDoS (Regular Expression Denial of Service)—a catastrophic backtracking regex like `(a+)+$` locks the single event loop thread for seconds on a 30-byte input, taking down all concurrent users; use linear-time engines like `re2` or static regex analyzers. (2) Command injection via `child_process.exec(userCmd)` spawning `/bin/sh`; always use `execFile`/`spawn` with `shell: false` and an argument array. (3) Prototype pollution on untrusted JSON merges (`--disable-proto=delete` plus `Object.hasOwn` guards). (4) Unbounded `JSON.parse` / `stream` bodies exhausting heap; enforce strict byte-size limits.

Production Code Example
import { execFile } from "node:child_process";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);

// Safe: no shell interpolation; filename passed directly to argv
export async function convertImage(filePath: string) {
  return execFileAsync("magick", [filePath, "-resize", "800x800", `${filePath}.webp`], {
    timeout: 5_000
  });
}
Common Interview Trap / Anti-Pattern:

Passing `{ shell: true }` to `spawn()` reintroduces shell metacharacter injection (`; rm -rf`) even when arguments are passed as an array.

Question #16PrincipalStaff

How should you configure V8 heap limits inside Docker/Kubernetes containers to avoid silent OOMKills?

Senior Engineering Answer

V8 enforces a default old-space heap cap (typically ~2GB-4GB depending on host/cgroup visibility), which can exceed a container's cgroup memory limit (e.g., 512MiB or 1GiB) and cause the Linux kernel OOM killer to SIGKILL the pod before V8 triggers an aggressive garbage collection. Set `NODE_OPTIONS="--max-old-space-size=<70-75% of container limit in MB>"` so V8 runs full mark-sweep GC cleanly within container bounds and leaves 25-30% headroom for V8 code space, libuv stacks, Buffers, and RSS overhead.

Production Code Example
// Example for a 1024 MiB Kubernetes container limit:
// NODE_OPTIONS="--max-old-space-size=768"
import v8 from "node:v8";

console.log({
  heapLimitMB: Math.round(v8.getHeapStatistics().heap_size_limit / 1024 / 1024)
});
Common Interview Trap / Anti-Pattern:

Setting --max-old-space-size equal to 100% of the container memory limit still triggers Linux OOMKills because Buffers, native addons, and V8's non-heap memory live outside the old-space heap limit.

Node.js Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This Node.js preparation set groups 16 prompts across Junior (4), Mid (4), Senior (4), Staff (4) roles with 4 fundamental, 4 intermediate, 4 senior, 4 principal exercises tailored to Backend & Systems.

JuniorFundamental

How do CommonJS (CJS) and ES Modules (ESM) differ in Node.js module loading and interoperability?

JuniorFundamental

Why does calling fs.readFileSync() or JSON.parse() on huge payloads inside an HTTP handler degrade Node.js throughput?

JuniorFundamental

What is a Node.js Buffer, and why does calling chunk.toString('utf8') on streaming binary chunks corrupt multi-byte characters?

JuniorFundamental

How does Node.js EventEmitter dispatch events, and why does an unhandled 'error' event crash the process?

MidIntermediate

Walk through the 6 phases of the Node.js event loop and compare process.nextTick(), queueMicrotask(), and setImmediate().

MidIntermediate

Which Node.js APIs actually use libuv's thread pool (UV_THREADPOOL_SIZE) versus non-blocking OS kernel sockets?

Frequently Asked Technical Interview Questions (Node.js)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

How does the Node.js event loop process its 6 phases and microtask queues?
Libuv runs Timers, Pending Callbacks, Idle/Prepare, Poll (I/O), Check (setImmediate), and Close Callbacks. Between tasks and phase transitions, Node drains process.nextTick() first and Promise microtasks second before advancing.
What is the difference between Worker Threads and the Cluster module?
The Cluster module spawns separate OS processes sharing a listening port with isolated memory, suited for multi-core HTTP I/O scaling. Worker Threads run multiple V8 isolates inside one process with SharedArrayBuffer support, suited for CPU-heavy work.
How does stream backpressure work and why prefer stream.pipeline()?
Backpressure pauses fast Readable streams when a slow Writable's internal buffer fills, preventing heap exhaustion. stream.pipeline() automates backpressure, propagates errors across all stages, and destroys every stream cleanly on failure.
How does AsyncLocalStorage propagate request context across async operations?
AsyncLocalStorage hooks into Node's async promise and callback tracking so a request-scoped store entered via als.run() remains accessible via als.getStore() across nested awaits, timers, and callbacks without manual parameter passing.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks