Node.js interview questions and answers for backend developers
Node.js interview questions center on one idea: JavaScript runs on a single thread, and everything slow is handed to the operating system or a small thread pool while the event loop keeps serving requests. Expect questions on event loop phases, process.nextTick versus promises, streams and backpressure, error handling, scaling across cores, and API security. Senior rounds add production scenarios such as a blocked event loop, a memory leak or a slow endpoint.
By Evin JohnPublished 7 min read
How Node.js questions show up
A Node.js developer interview is usually a backend interview with Node as the runtime. Expect a language round (shared with JavaScript interview questions), a Node-specific round on the runtime, a practical task such as building a small REST endpoint with validation and tests, and for experienced engineers an API or system design discussion. The runtime questions are where Node candidates stand out: anyone can write an Express route, fewer can explain why a CPU-heavy route slows every other request.
- Runtime conceptsThe event loop, non-blocking I/O, the thread pool and modules.
- Predict the orderA snippet mixing nextTick, promises, timers, setImmediate and file reads.
- Build an endpointRouting, input validation, a database call, error handling and a test, often in Express, Fastify or NestJS.
- Production scenariosLatency spikes, memory growth, crashes on deploy and how you would find the cause.
Node.js fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Is Node.js single-threaded? | Runtime model | Your JavaScript runs on one main thread. libuv uses the operating system's async I/O for sockets, and a thread pool (four threads by default) for file system calls, DNS lookups, some crypto and compression. |
| What is non-blocking I/O? | Concurrency | The main thread starts an I/O operation and moves on; the result arrives as a callback later. That lets one process hold thousands of idle connections. |
| What blocks the event loop? | Throughput | Synchronous CPU work: large JSON parsing, heavy loops, sync file APIs, slow regular expressions. While it runs, no other request is served. |
| CommonJS or ES modules? | Modules | require is synchronous and resolved at runtime; import is static, supports top-level await and live bindings. The package.json type field and file extensions decide how a file is loaded. |
| module.exports versus exports? | CommonJS detail | exports is a shortcut reference to module.exports. Reassigning exports breaks the link; reassign module.exports instead. |
| What happens the second time you require the same module? | Module cache | The cached exports are returned. The module's top-level code runs only once per process. |
| Why commit package-lock.json? | Dependencies | It pins the exact tree so CI and production install what you tested. Use npm ci in pipelines. |
| What is a Buffer? | Binary data | A fixed-size chunk of raw bytes outside the JavaScript heap, used for files, sockets and encodings. |
| How is EventEmitter.emit scheduled? | Events | Synchronously: listeners run in registration order before emit returns. Async behavior comes only from what the listener does. |
| What are environment variables used for? | Configuration | Secrets and settings per environment, read through process.env and validated at startup so a missing value fails fast. |
Event loop questions
The loop runs in phases: timers (setTimeout and setInterval), pending callbacks, poll (waiting for and running I/O callbacks), check (setImmediate) and close callbacks. Between callbacks, Node drains the process.nextTick queue and then the promise microtask queue.
const fs = require("node:fs");
console.log("start");
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
fs.readFile(__filename, () => {
setTimeout(() => console.log("io: timeout"), 0);
setImmediate(() => console.log("io: immediate"));
});
console.log("end");
// start, end, nextTick, promise, then the rest.
// timeout and immediate may print in either order here,
// and the io lines can interleave with them, but
// "io: immediate" always prints before "io: timeout".- Why does nextTick run before the promise here? In a CommonJS script, Node empties the nextTick queue before the promise microtask queue. In an ES module the top-level code itself runs inside a promise job, so the promise callback can come first. Saying that is a strong signal.
- Why is setImmediate first inside the readFile callback? The callback runs in the poll phase, and the check phase (setImmediate) comes before the loop returns to timers.
- Can recursive nextTick calls starve the loop? Yes. The queue is drained completely before moving on, so a nextTick that schedules another nextTick blocks I/O. Prefer setImmediate for yielding.
- What prints first: a listener's log or the line after emitter.emit()? The listener, because emit calls listeners synchronously.
- How would you measure event loop lag in production?
perf_hooks.monitorEventLoopDelayor a timer that compares scheduled and actual run times, exported as a metric with alerts. - What does UV_THREADPOOL_SIZE change? The number of libuv pool threads. It helps when many file, DNS or crypto calls queue, and does nothing for network sockets.
Streams, errors and API questions
const fs = require("node:fs");
const zlib = require("node:zlib");
const { pipeline } = require("node:stream/promises");
async function compress(src, dest) {
await pipeline(
fs.createReadStream(src),
zlib.createGzip(),
fs.createWriteStream(dest)
);
}| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is backpressure? | Streams | A fast producer filling a slow consumer's buffer. write() returning false means wait for drain; pipeline and pipe handle it for you. |
| Why stream a file instead of readFile? | Memory | readFile holds the whole file in memory; a stream processes chunks, so a large upload or export does not exhaust the heap. |
| How does middleware work in Express? | Request pipeline | Functions run in registration order with req, res and next. Order matters: parsing and auth before routes, the error handler last. |
| How do you handle errors in async route handlers? | Error flow | Catch and pass to next(err), use a wrapper, or a framework that handles rejected promises. One central error middleware maps errors to status codes and logs them. |
| What should happen on an uncaught exception? | Process health | Log it and exit, letting the supervisor restart the process. State after an unknown exception cannot be trusted. |
| How do you validate request input? | API safety | A schema at the edge (Zod, Joi, JSON Schema in Fastify) for body, query and params, returning 400 with clear messages. |
| How do you talk to a database efficiently? | Pools | A connection pool sized for the database's limits, parameterized queries, and timeouts. Query questions are in SQL interview questions. |
| How do you protect an API from abuse? | Rate limiting | Per-key or per-IP limits in a shared store such as Redis, with 429 responses; the design is in rate limiter system design. |
app.get("/users/:id", async (req, res, next) => {
try {
const user = await users.findById(req.params.id);
if (!user) return res.status(404).json({ error: "not found" });
res.json(user);
} catch (err) {
next(err);
}
});
app.use((err, req, res, next) => {
logger.error({ err, path: req.path });
res.status(err.status ?? 500).json({ error: "something went wrong" });
});Senior Node.js and scenario questions
- Worker threads, cluster or child processes? Worker threads for CPU-heavy JavaScript that shares memory with the process; cluster or several containers to use every core for HTTP traffic; child_process to run another program.
- How do you scale a Node.js API? Keep processes stateless, run one per core or per container behind a load balancer, move sessions and caches to Redis, and scale out horizontally.
- How do you shut down gracefully on deploy? On SIGTERM, stop accepting connections with server.close, finish in-flight requests, close database pools, and exit, with a hard timeout as a backstop.
- How do you find a memory leak? Watch heap usage over time, take heap snapshots a few minutes apart under load and compare retained objects. Common culprits: unbounded caches, listeners never removed, timers holding closures.
- What does MaxListenersExceededWarning tell you? More than ten listeners were added to one event on one emitter, which usually means listeners are being added per request and never removed.
- How do you profile a slow endpoint? Reproduce with load, run with
--inspector--cpu-prof, read the flame graph for wide frames, and check whether time is CPU on the main thread or waiting on I/O. - Which security issues are specific to Node.js apps? Prototype pollution from merging untrusted objects, regular expressions that backtrack catastrophically, path traversal in file serving, dependency risk, and secrets leaking into logs.
- How do you keep dependencies safe? A lockfile,
npm ci, automated updates in small batches,npm auditin CI with judgment about severity, and few dependencies for small tasks. - How do you test a Node.js service? Unit tests with the built-in node:test runner or Jest or Vitest, integration tests against a real database in a container, and contract tests for the API.
| Scenario | Likely cause | What to say you would check |
|---|---|---|
| p99 latency jumps for every route when one report endpoint is called. | Blocked event loop | The report does CPU work on the main thread. Confirm with event loop lag, then move the work to a worker thread or a job queue. |
| Memory climbs steadily until the container is killed. | Leak | Heap snapshots under load, look for growing maps, arrays of listeners or retained request objects. |
| Requests hang when traffic rises. | Pool exhaustion | The database pool is full and queries wait. Check pool metrics, slow queries and connections not released on error paths. |
| The service crashes after a third-party API timeout. | Unhandled rejection | A promise without a catch. Recent Node versions exit on unhandled rejections; add handling and a timeout per outbound call. |
| File uploads use gigabytes of memory. | Buffering | The body is read fully into memory. Stream it to storage with limits on size. |
Fictional example
- Our order API started timing out every afternoon, and it was every route, not one. That pattern pointed at the event loop rather than the database, so I added an event loop delay metric and saw spikes of several seconds. A CPU profile during a spike showed most time in JSON.stringify inside a CSV export endpoint that finance used in the afternoons: it built the entire file in memory. I rewrote the export to stream rows from the database cursor through a CSV transform straight to the response, and moved the heaviest variant to a background job that emails a link. The delay spikes disappeared and memory per process dropped as well. Since then I add the event loop metric to every service on day one.
Node.js practice plan
- Days 1 to 3: write ten event loop ordering puzzles with nextTick, promises, timers, setImmediate and fs callbacks, run them as CommonJS and as ES modules, and explain the differences.
- Days 4 to 6: build a small REST API with validation, a database pool, central error handling and tests. Add graceful shutdown.
- Days 7 to 9: streams. Process a large CSV with constant memory, then deliberately block the event loop and measure the lag.
- Days 10 to 12: take heap snapshots of a leaking toy service, read a CPU flame graph, and prepare two stories about production issues you handled.
For the wider role, see backend developer interview questions. Typed Node.js services come up in TypeScript interview questions, and containerizing a service is covered in Docker interview questions.
Explaining the event loop clearly takes rehearsal more than reading. Natively, an AI interview assistant for Mac and Windows, transcribes a mock backend round on your machine so you can check whether your explanation of phases and queues held together. In practice it can also read a code task or stack trace from a screenshot and offer a hint or an approach, and with Pro or the free trial it can work from your résumé and the job description you added. Every session keeps its transcript and notes for later.
Questions people ask
What Node.js questions are asked in interviews?
The event loop and its phases, process.nextTick versus promises, what blocks the loop, the libuv thread pool, streams and backpressure, CommonJS versus ES modules, Express middleware and error handling, and how to scale across cores.
Is Node.js single-threaded?
Your JavaScript runs on one main thread. Network I/O uses the operating system's async mechanisms, and a small libuv thread pool handles file system calls, DNS lookups and some crypto and compression work.
What do senior Node.js developer interviews cover?
Production scenarios: a blocked event loop, memory leaks, database pool exhaustion, graceful shutdown, profiling a slow endpoint, worker threads versus clustering, and dependency and API security.
How do I explain the Node.js event loop in an interview?
Name the phases (timers, pending callbacks, poll, check, close callbacks), say that nextTick and promise microtasks run between callbacks, and show it with a short ordering example, noting what is not guaranteed.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
