Node.js Interview Questions and Answers
Node.js interview questions with answers and code: the event loop, async patterns, streams, modules, Express and APIs, performance, worker threads, security and production practices.
Key takeaways
- Node.js interviews center on the event loop and what blocks it.
- Expect async patterns: promises, async/await, error handling, concurrency limits.
- Streams and backpressure distinguish mid-level candidates.
- Backend loops add API design, security, scaling and observability in Node.
Contents
Node.js interviews test whether you understand how the runtime works (the event loop, non-blocking I/O, streams) and how to build reliable APIs on top of it. Below are 30 common questions grouped by topic and level, with code.
What Node.js interviews cover
Editorial estimate.
- Event loop and runtime25%
- Async patterns20%
- APIs and frameworks20%
- Streams and performance15%
- Security and operations10%
- Coding exercise10%
The event loop phases
Between callbacks, process.nextTick callbacks run first, then promise microtasks. See also JavaScript and backend interview questions.
Runtime and event loop
1What is Node.js, and when is it a good choice?
JuniorA JavaScript runtime built on V8 with an event-driven, non-blocking I/O model. It shines for I/O-heavy services: APIs, real-time apps (WebSockets), proxies and tooling. It is a poor fit for heavy CPU work on the main thread unless you offload it to workers or other services.
2Explain the Node.js event loop phases.
MidThe loop cycles through phases: timers (setTimeout, setInterval), pending callbacks, poll (I/O events), check (setImmediate) and close callbacks. Between callbacks, Node runs process.nextTick callbacks and then promise microtasks. libuv’s thread pool handles some operations such as file system and crypto.
3process.nextTick vs setImmediate vs setTimeout(fn, 0)?
Midprocess.nextTick runs before other microtasks, right after the current operation, and can starve I/O if overused. setImmediate runs in the check phase after I/O polling. setTimeout(fn, 0) runs in the timers phase; relative order with setImmediate depends on context, but inside an I/O callback setImmediate always runs first.
4What blocks the event loop, and how do you detect it?
MidSynchronous CPU-heavy work: large JSON parsing, complex regular expressions, crypto with sync APIs, big loops, synchronous file APIs. Detect it with event loop lag metrics (perf_hooks.monitorEventLoopDelay), profiling (--cpu-prof, clinic.js) and slow request traces.
5What is the libuv thread pool used for?
MidOperations without a non-blocking OS interface: file system calls, DNS lookups via dns.lookup, some crypto and zlib functions. Its default size is 4 (UV_THREADPOOL_SIZE), which can become a bottleneck under heavy file or crypto load.
Async patterns
6Callbacks vs promises vs async/await?
JuniorCallbacks were the original pattern and lead to nesting and scattered error handling. Promises chain results and errors. async/await makes asynchronous code read like synchronous code with try/catch. Most modern Node APIs offer promise versions (fs/promises).
7How do you run async operations with limited concurrency?
MidAvoid launching thousands of requests at once with Promise.all. Use a small pool:
async function mapLimit(items, limit, fn) {
const results = new Array(items.length);
let i = 0;
const workers = Array.from({ length: limit }, async () => {
while (i < items.length) {
const idx = i++;
results[idx] = await fn(items[idx]);
}
});
await Promise.all(workers);
return results;
}
Libraries such as p-limit do the same.
8What happens with unhandled promise rejections?
MidIn modern Node.js, an unhandled rejection terminates the process by default. Always handle errors with try/catch or .catch(), and add a global unhandledRejection handler for logging, while still letting the process restart cleanly.
9What is an EventEmitter?
MidA class for publish-subscribe within a process: on, once, emit, off. Many core modules (streams, HTTP servers) extend it. Always handle the error event; an unhandled error event crashes the process. Remove listeners to avoid leaks.
Get Node.js answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.
Streams and buffers
10What are streams, and why use them?
MidAbstractions for processing data piece by piece: readable, writable, duplex and transform streams. They keep memory usage constant for large files or responses and let you start processing before all data arrives.
11What is backpressure, and how does pipeline help?
MidWhen a consumer is slower than a producer, data piles up in memory. Streams signal this (write() returns false), and the producer should pause. stream.pipeline connects streams, handles backpressure and propagates errors and cleanup:
import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";
await pipeline(createReadStream("big.log"), createGzip(), createWriteStream("big.log.gz"));
12What is a Buffer?
JuniorA fixed-size chunk of raw binary data outside the V8 heap, used for files, network data and binary protocols. Convert with encodings (buf.toString("utf8"), Buffer.from(str, "base64")).
Modules and tooling
13CommonJS vs ES modules in Node.js?
JuniorCommonJS uses require and module.exports and loads synchronously. ES modules use import/export, support top-level await and are enabled with "type": "module" in package.json or .mjs files. New projects usually use ES modules.
14dependencies vs devDependencies, and why commit the lock file?
Juniordependencies are needed at runtime; devDependencies only for development and builds. The lock file pins exact versions of the whole dependency tree, so installs are reproducible; use npm ci in CI.
15How do you manage configuration and secrets?
MidRead configuration from environment variables, validate it at startup (for example with a schema), fail fast if something is missing, and keep secrets in a secrets manager rather than .env files committed to the repository.
APIs and frameworks
16How does middleware work in Express?
JuniorMiddleware functions receive (req, res, next) and run in order: they can modify the request, end the response, or call next() to pass control. Error-handling middleware has four arguments (err, req, res, next).
17How do you handle errors in an Express API?
MidCatch async errors (Express 5 forwards rejected promises automatically; in Express 4 wrap handlers), use a central error middleware that maps known errors to status codes, hides internal details in production, and logs with a request ID.
18Express vs Fastify vs NestJS?
MidExpress is minimal and ubiquitous. Fastify is faster with built-in schema validation and serialization. NestJS is an opinionated framework with modules, dependency injection and decorators, popular for large teams. Choose based on team size and structure needs.
19How do you validate request data?
MidValidate every input at the boundary with a schema library (Zod, Joi, or JSON Schema in Fastify), reject unknown fields where appropriate, and return clear 400 errors. Types in TypeScript don’t validate data at runtime.
Performance and scaling
20How do you use all CPU cores in Node.js?
MidRun several processes: the cluster module, a process manager like PM2, or (most commonly today) multiple containers behind a load balancer. Each process has its own event loop; shared state must live outside, in Redis or a database.
21When do you use worker threads?
MidFor CPU-intensive work (image processing, parsing, compression) that would block the event loop. Workers run JavaScript in parallel threads and communicate via messages or shared memory. Use a pool rather than creating a worker per request.
22How do you find a memory leak in a Node.js service?
SeniorWatch heap usage over time, take heap snapshots (--inspect, v8.writeHeapSnapshot) at intervals and compare retained objects in Chrome DevTools. Common causes: growing caches or maps, listeners never removed, closures holding large objects, and global arrays of requests.
23How do you shut down a Node.js server gracefully?
SeniorOn SIGTERM, stop accepting new connections (server.close()), let in-flight requests finish with a timeout, close database pools and queues, flush logs, then exit. Kubernetes and other orchestrators rely on this for zero-downtime deployments.
Security
24What are common security risks in Node.js apps?
MidInjection (SQL, NoSQL, command injection via child_process), prototype pollution from unsafe object merging, vulnerable dependencies, ReDoS from catastrophic regular expressions, leaking stack traces, and missing rate limits. Use parameterized queries, input validation, npm audit or similar scanning, and security headers.
25How do you store passwords and handle auth?
MidHash passwords with Argon2 or bcrypt, never store them in plain text, issue short-lived tokens or server sessions in HttpOnly cookies, check authorization on every resource, and rate limit login attempts.
Testing and operations
26How do you test a Node.js API?
MidUnit tests with the built-in node:test runner, Vitest or Jest; integration tests against a real database in a container; HTTP tests with Supertest or the framework’s injection API; and mocking external services at the network boundary.
27What do you log and monitor in production?
MidStructured JSON logs (pino) with request IDs, latency and error metrics per route, event loop lag, heap usage, and distributed traces with OpenTelemetry. Alert on error rates and latency, not on every log line.
Coding exercises
28Implement a simple in-memory rate limiter middleware.
Midfunction rateLimit({ windowMs, max }) {
const hits = new Map();
return (req, res, next) => {
const key = req.ip, now = Date.now();
const entry = hits.get(key) ?? { count: 0, start: now };
if (now - entry.start > windowMs) { entry.count = 0; entry.start = now; }
entry.count++;
hits.set(key, entry);
if (entry.count > max) return res.status(429).json({ error: "Too many requests" });
next();
};
}
Mention that production setups across several instances use Redis instead of process memory.
29Read a large CSV file and count rows by a column without loading it into memory.
Midimport { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
const counts = new Map();
const rl = createInterface({ input: createReadStream("data.csv") });
for await (const line of rl) {
const country = line.split(",")[2];
counts.set(country, (counts.get(country) ?? 0) + 1);
}
Use a real CSV parser for quoted fields.
30Implement a retry helper with exponential backoff.
Seniorasync function retry(fn, { retries = 3, base = 200 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt >= retries) throw err;
const delay = base * 2 ** attempt * (0.5 + Math.random());
await new Promise(r => setTimeout(r, delay));
}
}
}
Retry only idempotent operations and errors that are likely transient.
How to prepare
- Draw the event loopPhases, nextTick, microtasks and what blocks the loop.
- Practice async codeConcurrency limits, retries, cancellation and error handling.
- Use streams in exercisesLarge files, transforms and pipeline with backpressure.
- Know your frameworkMiddleware, validation, error handling and graceful shutdown.
- Prepare a production storyA memory leak, event loop block or scaling problem you solved.
Get answer points in real time during your interview
Sottena listens to the interviewer, detects each question and shows short answer points in about a second. 150 free credits, no card required.