Node.js interviews should test whether candidates can build and operate a service, not just name JavaScript syntax. A backend engineer needs to know what blocks the event loop, how streaming changes resource use, how modules load in deployment and how to expose failures without leaking sensitive detail.
These 120 questions start with JavaScript in the Node.js runtime, then move into I/O, testing, and production troubleshooting. Ask candidates to trace a request or explain what they would measure before increasing concurrency. A strong answer should connect the runtime behavior to what callers experience.
How can you tell whether a candidate understands the Node.js service they just described?
Ask them to trace where backpressure starts when a download slows down, then change one condition and ask them to adapt their explanation. In remote interviews, Sherlock AI can help reviewers examine evidence of possible AI-assisted cheating, deepfakes, impersonation or other unauthorized assistance alongside the candidate’s technical reasoning.
Node.js Interview Questions
Use the question bank to pick a progression appropriate to the role, from basic runtime semantics to maintaining a production backend.
Node.js Interview Questions for Beginners
Start with the runtime, asynchronous control flow, files, modules and the lifecycle of a simple HTTP service.
What is Node.js?
How does Node.js differ from running JavaScript in a browser?
When is Node.js a good fit for a backend?
Does Node.js run everything on one thread?
What does the event loop do?
What is blocking I/O?
What is the error-first callback convention?
How do promises improve asynchronous control flow?
Does await block the whole Node.js process?
When would you use Promise.all instead of sequential awaits?
How do you handle errors from an awaited operation?
What is EventEmitter?
How do on and once differ on EventEmitter?
What is special about an EventEmitter error event?
What is a Buffer used for?
Why can a string's length differ from its UTF-8 byte length?
When should you use Buffer.alloc rather than Buffer.allocUnsafe?
What are the four main kinds of Node.js streams?
Why stream a file instead of using readFile?
What is a stream chunk?
What does backpressure mean?
What does stream.pipeline do?
How do CommonJS and ES modules differ?
How does Node decide how to interpret a JavaScript module?
What does the node: prefix in an import indicate?
How does a relative ES module import resolve a local file?
What is the purpose of package.json?
Why commit a dependency lockfile for an application?
What is the difference between dependencies and devDependencies?
How do you read an environment variable safely?
What is the difference between process.cwd() and an absolute file location?
What does setTimeout guarantee about its delay?
What is the difference between setImmediate and setTimeout with a zero delay?
How do you start a basic HTTP server in Node.js?
How are request and response bodies represented in node:http?
When are HTTP response headers committed?
How can a Node.js service parse an incoming URL?
How do you write a simple automated test with Node.js?
What does an exit code tell a caller?
What makes a Node.js service ready to receive traffic?
Node.js Interview Questions for Intermediate
Move from definitions to behavior: event-loop scheduling, backpressure, module interoperability, cancellation and test isolation.
What are the main event-loop phases a Node.js engineer should recognize?
How do nextTick and promise microtasks interact?
How could nextTick starve network I/O?
Which operations can compete for the libuv worker pool?
How does dns.lookup differ from dns.resolve?
What does highWaterMark control?
What changes when a stream uses object mode?
What is a robust way to send a large compressed export?
What should an async iterator over a Readable do on cancellation?
How would you parse newline-delimited JSON from a stream?
Why do repeated EventEmitter subscriptions cause problems?
How do you handle asynchronous listener failures?
How would you cancel an outbound HTTP request?
What is the difference between a request timeout and an end-to-end deadline?
What should you do if fetch returns HTTP 503?
How can Node.js HTTP connection reuse affect performance?
How should a service handle slow clients uploading request bodies?
How do you handle a client disconnect during a long operation?
How do you map backend errors to HTTP responses?
What is the purpose of the package exports field?
How would you import a CommonJS package from an ES module?
What can cause duplicate module-level state in one process?
How should a team replace process-wide mutable configuration in tests?
How do spawn and exec differ for child processes?
What is the difference between child-process exit and close events?
When should you use worker threads rather than child processes?
How are worker thread data and results transferred?
Why use a pool of workers rather than one worker per task?
What does AsyncLocalStorage help with?
How should you use structured logging for a Node.js service?
How do you distinguish event-loop lag from event-loop utilization?
How can you test timer-driven logic without making tests slow or flaky?
What should an HTTP integration test check beyond status code?
How would you reliably test a stream failure path?
How do source maps help diagnose production errors?
What should your service do with rejected promises that are not handled?
How do you validate a JSON body without trusting its apparent shape?
How would you make a write request safe to retry?
How do you prevent a burst of outbound operations from overwhelming dependencies?
What should happen after a service receives SIGTERM?
Node.js Interview Questions for Experienced
Use these scenarios to test how candidates diagnose and operate a high-traffic service under failures, overload and deployment changes.
A service's p99 latency doubles while median latency stays flat. How would you investigate?
A Node.js process has rising RSS but stable heapUsed. What do you check?
How would you confirm a JavaScript heap retention problem?
How would you investigate CPU spikes without guessing which route caused them?
What indicates libuv pool contention rather than event-loop saturation?
How would you select worker pool size in a container?
How do you design an overload policy for mixed cheap and expensive routes?
How do you decide whether to scale a Node.js API across processes or instances?
What trade-offs arise when choosing sticky routing for real-time connections?
How would you drain a deployment that supports HTTP keep-alive?
How would you update a message consumer without losing accepted jobs?
How do you design bounded retries across nested Node.js services?
How would you handle half-success when writing to a database and emitting an event?
How would you process huge request payloads without holding them in RAM?
How should you limit decompression in a Node.js ingestion pipeline?
A proxied download sometimes ends early with status 200. How would you diagnose it?
How do you choose a buffering threshold for a multi-stage stream?
How do you ensure a stream-based protocol handles split UTF-8 characters?
How do you safely prioritize or discard work in a queue shared by tenants?
How do you examine where asynchronous request context is lost?
What would you instrument through Diagnostics Channel?
How would you design baseline observability for a Node.js service?
How can JSON serialization become a production bottleneck?
How do you reduce user-impacting garbage collection pressure?
What safeguards matter when running a CPU-heavy library in a worker?
How would you reduce worker messaging overhead for binary inputs?
Why might a child process keep a Node.js parent from shutting down?
How would you roll out a module-system migration in a shared Node.js package?
How would you diagnose an import that works in development but not production?
How do you keep dependency upgrades reproducible and low risk?
How would you handle cancellation when two requests share the same upstream work?
How would you enforce separate DNS, connection and response budgets?
How do you avoid leaking event listeners in timeout races?
How do you distinguish a recoverable request failure from a fatal process error?
How would you use diagnostic reports in a production incident?
How would you make a startup dependency failure diagnosable and safe?
How do you test graceful shutdown under actual concurrent traffic?
How would you compare two Node.js implementations fairly under load?
When is a Node.js core benchmark misleading for a real service?
How would you establish an operational contract for a critical Node.js API?
Node.js Interview Questions and Answers
Use the answers as calibration, not a script. Give credit for correct trade-offs or alternative designs when a candidate states their assumptions.
Node.js Interview Questions and Answers for Beginners
Use these answers to check that candidates distinguish JavaScript behavior from the APIs that Node.js provides.
1. What is Node.js?
Node.js is a JavaScript runtime, not a web framework. It uses V8 to execute JavaScript and supplies APIs for files, networking, processes and other server-side work. Express can run on top of Node, but a service can also use node:http directly.
For example, an order API can open a socket to receive requests, use asynchronous filesystem APIs to load a template, and call a database client from the same application. The runtime provides the building blocks; routing conventions, validation and business behavior remain application or framework responsibilities.
2. How does Node.js differ from running JavaScript in a browser?
They share the language, but expose different host APIs. Node supplies process, filesystem and server networking APIs; browser scripts ordinarily use a DOM and sandboxed web APIs. Shared APIs such as fetch do not make the two execution environments interchangeable.
A library that calls document.querySelector cannot run unchanged in a normal Node process because no page document exists. Conversely, code that opens a local file by arbitrary path with node:fs needs Node or another compatible host. Organize shared validation or parsing code separately from host-specific adapters.
3. When is Node.js a good fit for a backend?
It fits services that spend much of their time waiting on I/O, such as a gateway that queries several APIs. Long CPU-bound work can delay other callbacks on the same JavaScript thread; benchmark it and move or isolate it when needed.
A service that fans out to a customer directory and billing API can let those network waits overlap. A service that runs a large image transform synchronously per request will instead compete with its own lightweight routes. Evaluate the actual mix of work, not the number of concurrent connections alone.
4. Does Node.js run everything on one thread?
No. A typical process executes application JavaScript on one event-loop thread per isolate, while the runtime can use OS facilities and native threads for work. Explicit worker threads add separate JavaScript execution threads. Asynchronous does not necessarily mean a new thread.
For example, two requests can have database operations outstanding while Node executes only one request callback at a time on the main loop. A large synchronous computation still hurts both requests. Worker threads can help with that computation but require a communication mechanism and still share the process's resource budget.
5. What does the event loop do?
It lets Node handle ready callbacks and I/O events without blocking on each request. A busy JavaScript callback still prevents other JavaScript on that loop from running. Nonblocking APIs let the loop work elsewhere while results are pending.
Suppose one client is waiting for a network packet and another request is ready to validate a small payload. Node can run the ready callback without waiting for the first client. However, if the second callback parses a huge object synchronously, incoming events must wait until that callback yields.
6. What is blocking I/O?
A blocking call prevents the calling thread from doing other work until it returns. readFileSync can be reasonable for small configuration at process startup, but doing it in every HTTP handler can stall concurrent requests.
Compare a startup script that reads a certificate once with a route that repeatedly reads a large file under peak traffic. They use similar code but have very different consequences. Async operations still do work, and without concurrency limits they can saturate other resources even when the loop is responsive.
7. What is the error-first callback convention?
A callback receives an error first, typically as callback(err, result). If the error is present, handle it and return before using result. This pattern remains common in legacy APIs even when new code prefers native promise variants.
For a callback that retrieves a profile, branch on the error before checking whether the profile is missing. Returning an error response and then continuing to the success path can attempt to send two responses. If you own the callback API, make its single-completion requirement explicit and test it.
8. How do promises improve asynchronous control flow?
They represent eventual fulfillment or rejection and compose with chaining or await. Return a promise from a then callback when the next stage depends on it; forgetting to return often causes later code to run too early or miss an error.
If a then callback starts a database write but does not return its promise, a caller can start sending a success response while the write is still pending. An explicit return or an awaited statement gives the caller a reliable completion point and places the rejection in the intended chain.
9. Does await block the whole Node.js process?
No. It suspends the containing async function and lets other eligible work proceed, though synchronous work before or after await still runs on the JavaScript thread. Awaiting a promise cannot make a CPU-heavy parser nonblocking.
For example, await a network call and a lightweight handler can run while its response is pending. If the resumed handler immediately sorts millions of entries, that sort still monopolizes the loop. Splitting work into async functions improves readability, not automatic scheduling of CPU work.
10. When would you use Promise.all instead of sequential awaits?
Use it for independent operations when their combined concurrency is acceptable. Promise.all rejects after an input rejection but does not cancel the other operations. For thousands of items, use bounded concurrency instead of starting everything together.
Fetching a profile and its public preferences can run together when neither result is required to start the other. Fetching an invoice needs to wait if the first query determines its authorized account ID. Also consider whether partial failures are acceptable before choosing all versus allSettled or an explicit fallback.
Node.js (JavaScript) example
Results are returned in input order, even if completion order differs. This fixture tests the result shape, not whether any network work was actually overlapped.
11. How do you handle errors from an awaited operation?
Put the await inside try/catch when that code can handle or translate the failure. Preserve useful context and rethrow unknown failures. A promise started but not awaited or returned can reject outside the intended error boundary.
In a route, translate a known upstream deadline into an appropriate service response and propagate a programming error to the central error handler. A catch block that returns a generic success would make monitoring and client recovery misleading. Make sure cleanup still runs, for example by owning it in finally.
12. What is EventEmitter?
It manages named events and their listeners. emit calls listeners synchronously in registration order, so a slow listener delays the caller. Treat it as an in-process coordination primitive, not a durable queue.
An emitter can notify a connection manager that a connection has closed. If a billing email must survive a crash or run on another process, emitting an event alone will not provide those guarantees. Use a durable job system for durable work, with an explicit acknowledgement model.
13. How do on and once differ on EventEmitter?
on continues listening until removed; once removes its listener before the first invocation. Use once for a one-time completion, but unregister explicitly if the operation is abandoned before that event occurs.
For a temporary upload listener, attach once to the completion event and also clean it up after a deadline or failure. If completion never arrives, a once listener can still hold a reference to the request. Pair subscriptions with the lifecycle of the operation that registered them.
14. What is special about an EventEmitter error event?
Emitting error with no listener throws, and an uncaught throw can terminate the process. Attach error handling where the emitter is owned or use a higher-level API that propagates errors, such as stream.pipeline.
For a custom stream, a missing error listener is not equivalent to a handled rejected promise. A listener that merely logs without ending the dependent operation can also leave the caller hanging. Give one owner responsibility for surfacing failure and releasing resources.
15. What is a Buffer used for?
A Buffer holds bytes, which makes it appropriate for network payloads, file blocks and binary formats. A JavaScript string represents text. Convert deliberately with the correct encoding when moving between the two.
Read a binary header as bytes when comparing its signature or interpreting a numeric field; converting arbitrary file bytes to text could lose information. On the other hand, decode a UTF-8 payload before applying text rules. The format, encoding and byte order are separate choices.
16. Why can a string's length differ from its UTF-8 byte length?
String length counts UTF-16 code units; UTF-8 uses a variable number of bytes per character. For example, the euro sign has a JavaScript length of one but occupies three UTF-8 bytes. Use Buffer.byteLength when framing encoded content.
A header or file record with a declared length of one for the euro sign will split a UTF-8 payload incorrectly. Length checks also matter for quotas: a character budget might be useful for a form, but a transport or storage limit generally needs a byte budget.
Node.js (JavaScript) example
The assertions pass because the string contains one UTF-16 code unit but its UTF-8 encoding requires three bytes.
17. When should you use Buffer.alloc rather than Buffer.allocUnsafe?
Use alloc when you need initialized bytes. allocUnsafe may expose previously allocated memory if you read or transmit unwritten bytes. Only use it when every byte is fully overwritten before exposure and the optimization is justified.
Use Buffer.alloc for a response of fixed size when some positions may remain empty. For a performance-critical parser that rewrites an entire scratch region, verify both the success and early-error paths before considering allocUnsafe. A partial fill followed by logging or serialization can expose the remaining bytes.
18. What are the four main kinds of Node.js streams?
Readable provides data, Writable consumes it, Duplex can do both, and Transform is a Duplex whose output is produced from its input. A file reader is Readable; gzip compression is Transform.
A file reader piped through a compressor to a socket shows three different responsibilities: reading source bytes, deriving new output and consuming it. For a Duplex socket, the input and output sides need not transform the same data. That distinction matters when deciding how to close each side.
19. Why stream a file instead of using readFile?
Streaming can keep memory bounded and start forwarding bytes before the full file is read. readFile is simpler for small inputs but normally reads the whole file into memory. Enforce overall file and time limits either way.
A report endpoint serving a 500 MB file to slow clients should not allocate a 500 MB buffer per request. Streaming can lower that peak, but concurrent streams and slow sinks still consume memory, descriptors and time. Measure these under slow-client traffic rather than assuming a small file test represents production.
20. What is a stream chunk?
It is one unit of data delivered by a stream. Chunk boundaries are not necessarily record, line or character boundaries. A parser must carry incomplete state across chunks instead of assuming each chunk is a full record.
A stream may deliver half of a CSV line in one chunk and the other half alongside the next record. If text is multibyte, even a single character can span two byte chunks. Pick a parser or streaming decoder that handles both cases and verify it with deliberately awkward chunk boundaries.
21. What does backpressure mean?
It is the signal that a consumer cannot keep up with a producer. For a Writable, write returning false means the chunk was accepted for buffering but the producer should pause until drain. Ignoring this signal can lead to memory growth.
Imagine reading file chunks faster than a client can receive them. If every write is pushed immediately, the destination queue can grow well beyond expectations. Use a library pipeline where it fits, or pause production and also handle errors or closure while waiting for drain.
Node.js (JavaScript) example
The first chunk is accepted but write returns false. The next step waits for drain; a real stream owner must also account for premature close.
22. What does stream.pipeline do?
It wires stream stages together and handles transfer, backpressure and many failure-cleanup cases. With the promise API you await completion. If piping to HTTP, remember a failure may already have destroyed the socket or committed the response.
For a disk export, await the pipeline before treating the result as complete, and remove an incomplete temporary file on failure. A pipeline can clean up streams without automatically rolling back files or database effects that your application created. Make those effects part of the surrounding lifecycle.
23. How do CommonJS and ES modules differ?
CommonJS commonly uses require and module.exports; ES modules use import and export. ES module bindings and loading rules differ from CommonJS, and interoperability depends on Node's supported rules rather than textual substitution.
For instance, a file can use named imports in ESM but not rely on require being implicitly available. A package that serves both formats should test the shapes real consumers receive. Merely replacing require with import without checking resolution, export shape and initialization order can break consumers.
24. How does Node decide how to interpret a JavaScript module?
Explicit extensions matter: .mjs is ESM and .cjs is CommonJS. A package.json type field sets how relevant .js files are interpreted. Declare the format explicitly instead of relying on defaults or syntax detection that can differ with runtime version.
A migration can keep legacy setup code in a .cjs file while application files use an explicit module type. A test runner or bundler might handle extensions differently from the deployed Node loader. Run checks directly against the built artifact before changing module settings for a whole package.
25. What does the node: prefix in an import indicate?
It identifies a Node built-in module, for example node:fs or node:test. It clarifies that the dependency comes from the runtime, not from an installed third-party package. The built-in still must exist in the version you deploy.
Spelling an import node:test makes it clear that tests rely on the built-in runner and not a third-party package. That does not remove the need to agree on the supported version and feature set. Test with the same release line targeted by build and production.
26. How does a relative ES module import resolve a local file?
Use a relative specifier such as ./config.js and include the file extension. Node's ESM resolver does not generally add an extension or auto-select a directory index for a relative specifier. Do not confuse bundler conventions with runtime resolution.
For a source file that becomes dist/config.js, verify that the compiled import names the file that actually exists. An editor or bundler may let a shorthand extensionless import pass locally. That convenience is not evidence that a published package or unbundled server will load in Node.
27. What is the purpose of package.json?
It declares package metadata and settings such as dependencies, scripts, module type and entry points. Changing a field such as type or exports affects how code is loaded, not just how it is described.
For example, adding a module type to support a new component can also change interpretation of existing .js scripts. Put unrelated changes in separate reviews and run the test, build and startup scripts with the selected type. Treat package configuration as behavior, not decoration.
28. Why commit a dependency lockfile for an application?
It records the resolved dependency graph, including transitives, so CI and peers can install the intended graph. Keep it synchronized with the manifest, use deterministic install commands, and review changes for both correctness and dependency risk.
If a package release introduces an incompatible transitive dependency, a lockfile keeps one runner from silently resolving a different graph from another. It does not guarantee that every platform has the same optional native packages or that the recorded packages are safe. Keep platform and provenance checks separate.
29. What is the difference between dependencies and devDependencies?
dependencies belong to the installed runtime package graph; devDependencies support activities such as builds and tests. If production directly imports a package, declaring it only as a dev dependency can break a production install that omits them.
A server that imports a validation library at request time needs it in the runtime installation. A linting package used only in CI usually belongs in devDependencies. Verify the production artifact itself, because a full local install can hide a wrongly declared runtime dependency.
30. How do you read an environment variable safely?
Read process.env and validate required values at startup. Its values are strings or absent, so parse explicit booleans and ranges rather than using truthiness. Never include secret environment values in startup errors or logs.
For example, the string false is truthy, so a Boolean conversion can enable a feature an operator meant to turn off. Accept a defined vocabulary and fail clearly on values outside it. A required unset variable and an explicitly empty string may need different messages and handling.
31. What is the difference between process.cwd() and an absolute file location?
process.cwd returns the directory from which the process is currently operating, which may change. A module-relative location follows the module itself. Use the latter for bundled assets and a configured path for operator-provided files.
A scheduled job and a developer command may run the same module from different directories. Resolving a bundled schema from the module location makes it stable across both. Resolving an operator-provided path should follow the documented deployment convention instead of silently depending on whoever launched the process.
32. What does setTimeout guarantee about its delay?
It schedules a callback to be eligible after a delay, not an exact execution time. Busy callbacks or runtime scheduling can push it later. Do not build precise timekeeping around timer tick counts.
A 100 ms timeout can fire much later if the service is busy with synchronous work. It therefore does not guarantee a caller's latency objective or replace upstream time limits. Measure elapsed time using an appropriate clock and use timeouts as policy signals rather than precision scheduling.
33. What is the difference between setImmediate and setTimeout with a zero delay?
setImmediate schedules work for the check phase; setTimeout schedules timer work after a threshold. At top level, relative ordering is not a portable assumption. Within a typical I/O callback, an immediate runs before a newly scheduled zero-delay timer.
A simple local script showing one order at startup can accidentally teach a guarantee that fails when the same work moves into a network callback or module initialization. Use immediates deliberately to let other loop work run, and design business logic so its correctness does not depend on incidental queue ordering.
34. How do you start a basic HTTP server in Node.js?
Use node:http createServer with a request handler, then listen on a configured address and port. Every code path should finish the response or hand it to a stream, and the server should handle listen and transport errors.
For a health-only server, validate the method and path and complete a response for both matched and unmatched requests. Also handle failure to bind, for example when a port is already in use. Without a completed response, the client sees a timeout rather than the intended error.
Node.js (JavaScript) example
Using port 0 lets the OS assign a test port. The response is completed for both matching and unmatched routes; the check serves only local fixture traffic.
35. How are request and response bodies represented in node:http?
IncomingMessage is Readable; ServerResponse is Writable. You can process chunks incrementally or collect a small body under a strict limit. Core HTTP does not automatically turn JSON request bodies into objects.
For a small JSON request, count bytes while reading, reject malformed input distinctly and then validate fields. A streamed upload uses a different approach: feed the body to a destination and handle its cancellation and backpressure. Both flows need explicit limits regardless of HTTP parsing provided by Node.
36. When are HTTP response headers committed?
They are committed when explicitly sent or when the response begins writing, such as its first body write. Set status and headers first. If a failure occurs afterward, you cannot turn the streamed response into a clean new JSON error.
If a server starts a report download and the storage read later fails, a proxy or client may still see the already committed 200. Decide whether to validate more before committing, terminate incomplete streams clearly, or add a completion mechanism the consumer can check.
37. How can a Node.js service parse an incoming URL?
Use the WHATWG URL constructor with a fixed trusted base for relative request targets and read pathname and searchParams. If the target may be absolute, validate its resulting origin separately. Do not trust a Host header for security decisions without validation.
For a route matching a search endpoint, use the parsed path and read the query separately instead of splitting and decoding the raw request repeatedly. Define how duplicates and invalid values are handled. Routing and authorization should share a consistent interpretation so the same target is not evaluated differently.
38. How do you write a simple automated test with Node.js?
Use node:test to declare a test and node:assert/strict to check the result. Return or await asynchronous work so failures are observed before the test ends. Run the suite using node --test.
Test a parser's successful result and an explicit rejection, then add an integration test for behavior involving transport or streaming. Async assertions need to finish before the test does. Avoid tests that pass because no assertion ran on a discarded asynchronous result.
39. What does an exit code tell a caller?
Zero conventionally indicates normal success and nonzero indicates failure. Prefer setting process.exitCode and allowing pending cleanup to finish over immediately calling process.exit, which may interrupt asynchronous output.
A command-line export might finish with a nonzero code after writing a useful diagnostic to stderr. Setting exitCode preserves time for that write, but it will not force an exit if a socket remains open. Close resources deliberately and use a supervisor-level deadline for long-running services.
40. What makes a Node.js service ready to receive traffic?
Listening on a port means it can accept connections, not necessarily serve them. Readiness should reflect required startup work and essential dependencies; it should turn false during draining. Liveness is a separate signal for a stuck process.
A service should not become ready just because the socket bound successfully if its required schema initialization has failed. Conversely, liveness checks triggered by a transient downstream outage can cause every replica to restart unnecessarily. Decide which failures need traffic removed, degraded handling, or a restart.
Node.js Interview Questions and Answers for Intermediate
Look for answers that explain the contract and describe where that contract can fail in real service code.
41. What are the main event-loop phases a Node.js engineer should recognize?
Know timers, pending callbacks, poll, check and close callbacks, plus internal phases. Poll deals with I/O readiness, and check runs setImmediate callbacks. Promise microtasks and nextTick callbacks are not phases; avoid promising identical ordering in every context.
For example, a follow-up scheduled during a socket callback can run through check while application timers have not yet become eligible. A newer libuv release can change timing details without invalidating the phase model. In an interview, explain the relevant context instead of memorizing one console-log ordering as universal.
42. How do nextTick and promise microtasks interact?
nextTick uses Node's own queue, while promise reactions and queueMicrotask use the microtask queue. At a typical CommonJS boundary nextTick drains first, but ES module evaluation itself runs as a microtask, so top-level examples can differ. Prefer queueMicrotask for portable deferral unless Node-specific ordering matters.
Moving an initialization example from .cjs to .mjs is enough to change some observed ordering without changing the callback bodies. If the requirement is that initialization has completed before a listener executes, define an explicit promise or lifecycle event rather than depending on which queue happens to win.
43. How could nextTick starve network I/O?
A callback that continually queues another nextTick keeps the queue busy before control returns to the loop. Bound the work and yield to a later turn, for example with setImmediate, so I/O can run. Monitor lag under realistic input size.
A queue that processes one item and recursively schedules the next through nextTick can indefinitely postpone incoming sockets if work keeps arriving. Batch a limited number of cheap tasks and return control before processing more. This changes the fairness of scheduling without pretending one expensive operation magically becomes cheap.
44. Which operations can compete for the libuv worker pool?
Asynchronous filesystem calls and several crypto, zlib and DNS operations can share the pool. A burst of expensive crypto can delay file operations even if event-loop lag stays modest. Identify the actual APIs in use before tuning the pool.
For a service that performs password derivation and reads small templates, compare operational latency when the two traffic classes run together and separately. If the same pool is competing for work, cache safe immutable template content or constrain derivation concurrency. Increase worker count only after checking CPU and memory headroom.
45. How does dns.lookup differ from dns.resolve?
lookup uses the operating system's name resolution facilities, so local configuration such as hosts files can matter. resolve issues DNS queries using Node's DNS resolver. The calls may give different results and have different worker-pool behavior.
For example, an internal name resolved through a hosts file might work for an HTTP client using lookup but produce no answer from a direct DNS query. Align tests with production's networking and resolution mechanism. Don't replace one call with the other solely because the alternative looks faster on a laptop.
46. What does highWaterMark control?
It is a buffering threshold governing when a stream asks for more data or signals backpressure, not a hard universal memory limit. The unit can be bytes or objects depending on mode. Budget across all stages and concurrent streams, including individual oversized chunks.
If four stages each buffer data, the same system can hold data in more than one stage. A single chunk can also exceed the threshold and still be accepted. Start with observed per-stream memory and slow-consumer throughput, then multiply by admitted concurrency as a rough budget and test actual behavior.
47. What changes when a stream uses object mode?
Chunks are arbitrary objects rather than just raw byte-oriented payloads, and the relevant threshold counts objects. Twenty tiny records and twenty huge records can have very different memory footprints. Also enforce per-object size and bound concurrency.
An object-mode transformer buffering parsed rows is convenient until one row contains a very large field. Count alone cannot express that cost. Validate declared record sizes as early as possible, and separately bound the number of simultaneous transforms when individual objects can have unpredictable processing time.
48. What is a robust way to send a large compressed export?
Use a pipeline from the source through compression to the destination and propagate cancellation when the client leaves. Validate before committing response headers. Test partial reads, a slow client, and source errors so a truncated download is not logged as successful.
For a CSV-to-gzip download, obtain authorization and establish the data source before sending success headers. If a later cursor error leaves the HTTP response incomplete, record partial failure rather than another success response. Ensure the database cursor is closed even when the recipient disconnects first.
Node.js (JavaScript) example
The arrays deliberately retain output for a tiny correctness check. A production export should not accumulate the compressed response in an array.
49. What should an async iterator over a Readable do on cancellation?
Stop consuming and clean up the source, not just the loop's bookkeeping. Breaking a regular for-await traversal normally destroys a Node Readable. If reusing the stream is intentional, choose an iterator option with matching destruction behavior and verify the lifecycle.
For example, inspecting only the first chunk of a file through a normal async iterator can close the stream on loop exit. If later code must continue reading it, define who owns final closure and use a compatible non-destroying iterator deliberately. Otherwise, the simplest policy is to destroy on abandonment.
50. How would you parse newline-delimited JSON from a stream?
Decode bytes with boundary-aware decoding, keep an incomplete trailing line across chunks, and parse each completed line independently. Define whether a malformed record stops the pipeline or goes to a separate error path. Cap line size before parsing.
A producer can send two lines in one chunk or split a single line at an arbitrary position, including inside a multibyte character. Test both and define behavior for a final line without a newline. Streaming parsing should not become an unbounded buffer for an input with no delimiter.
51. Why do repeated EventEmitter subscriptions cause problems?
Listeners can accumulate, retain captured objects and perform duplicate work. A listener warning is a useful diagnostic, not an automatic cleanup or proof of a leak. Fix the owner's create-and-remove lifecycle and verify listener count returns to baseline.
A reconnect loop that adds a data listener to the same long-lived emitter each time can double-process every item after reconnect. Find the exact owning component and make disposal symmetric with registration. Raising the maximum listener threshold can hide the signal without eliminating duplicated work.
52. How do you handle asynchronous listener failures?
An ordinary emit call does not await the promise returned by a listener. Catch failures explicitly or use captureRejections with appropriate error handling. If the emitting caller must wait for completion, use an explicit async contract instead of assuming events provide one.
If an event triggers an async audit write, the publisher cannot assume the write happened when emit returns. Use a request-response function when the producer needs a confirmation. If the audit must survive process failure, give it a durable delivery contract rather than relying on an in-memory callback.
53. How would you cancel an outbound HTTP request?
Pass an AbortSignal to an API that honors it, and trigger it on deadline or parent cancellation. Propagate the same cancellation into related tasks and clean up resources. A timer that merely rejects a wrapper promise does not stop the underlying request.
For a dashboard request that fans out to three systems, propagate cancellation when the dashboard client disconnects. Distinguish a caller deadline from an upstream technical error in diagnostics. Also confirm the APIs downstream honor the signal so a canceled response really releases useful capacity.
54. What is the difference between a request timeout and an end-to-end deadline?
A request timeout may apply only to an individual operation or phase. A deadline caps the whole action, including connecting, retries, reading and handling data. Pass the remaining time to each step so nested calls do not multiply the latency budget.
If an API has 500 ms overall and spends 300 ms reaching a dependency, a retry cannot safely start with another independent 500 ms budget. Pass a deadline through the chain. Reserve a small response window so the service has time to return a meaningful failure rather than abandon work at the last boundary.
55. What should you do if fetch returns HTTP 503?
Check response status explicitly because an HTTP error response is not itself a rejected fetch promise. Consume or cancel the response body as appropriate. Retry only if the operation is safe to repeat and the remaining deadline allows it.
For a safe GET, respect server retry guidance only within your own deadline and admission rules. For a mutation, a 503 or socket failure does not establish that the operation had no effect. Retrying without an idempotency contract may create a duplicate even though the original response was never observed.
56. How can Node.js HTTP connection reuse affect performance?
Reusing connections avoids repeated DNS, TCP and TLS setup, but a pool can queue requests or hit stale connections. Set downstream concurrency and lifecycle policies for the relevant client. Fetch and node:http do not share one generic pool configuration.
A burst to one host may fill its connection slots and put later calls into a queue before they ever connect. Measure queue time separately from downstream service time. Tune idle behavior and maximum connections in coordination with the server instead of increasing sockets to mask a saturated dependency.
57. How should a service handle slow clients uploading request bodies?
Set bounded header and body-receive windows, enforce an application body-size cap, and cancel or stop reading when the request exceeds policy. Align timeouts with the proxy. Listen-time controls alone do not protect every processing stage.
A proxy can time out while the application is still reading, or buffer a body that the application expected to receive incrementally. Configure the public entry point and Node service together. Exercise slow headers, slow body and oversized body as separate cases since a single timer does not cover them all.
58. How do you handle a client disconnect during a long operation?
Observe request or response lifecycle and distinguish completed responses from premature closure. Abort downstream calls and destroy unneeded streams when work can be abandoned. Decide separately whether an already accepted durable job should continue.
For a preview that only matters to the current caller, abort rendering and free its temporary files when the connection is lost. For a job already committed durably, record the job ID and let worker policy decide completion or cancellation. The socket lifecycle is not proof of business cancellation.
59. How do you map backend errors to HTTP responses?
Classify failures at the boundary: malformed input, authorization, expected conflicts and missing data differ from internal failures. Keep the client message safe and stable; log richer context with request IDs and redaction. Do not leak upstream exception text by default.
A conflicted version on a write is expected and useful to the caller, while an unavailable datastore may require a retryable service error. Centralized mapping keeps those policies consistent. Record the internal cause without embedding exploitable details or raw private input in client responses.
60. What is the purpose of the package exports field?
It defines public package entry points and can select conditions such as import and require. Adding it can hide paths consumers previously deep-imported, so treat public entry-point changes as compatibility work. Export the supported subpaths explicitly.
A package can keep internal modules private while permitting a documented subpath for shared types or utilities. Before adding exports to an existing library, test actual consumer import patterns. A file still present in the package is not necessarily importable through a package subpath.
61. How would you import a CommonJS package from an ES module?
A default import typically gives the CommonJS module.exports value. Named exports may depend on static analysis and are not the same as native live ESM bindings. Use the documented entry point rather than assuming every object property is a reliable named import.
If a package mutates a property on its CommonJS export after initialization, do not assume an inferred ESM named import updates like a native ESM export. Prefer a documented default interface where that shape is intentional, and test consumer behavior using the actual package, not a mock resolver.
62. What can cause duplicate module-level state in one process?
Separate installed copies, differently resolved paths or separate ESM and CommonJS entry points can create distinct instances. A library that assumes a singleton registry can then behave inconsistently. Inspect resolution and dependency trees and prefer explicit shared state where feasible.
If instrumentation registers into one package instance and the request code imports another, the expected spans may never appear. Inspect the dependency graph and compare which entry points are resolved under import and require. A shared datastore or injected registry can be more reliable than module identity.
63. How should a team replace process-wide mutable configuration in tests?
Parse environment at startup into a config object and inject it into dependent modules. Tests can provide isolated values without racing on process.env. Reserve environment-mutation tests for the parser or a subprocess with controlled inputs.
For a feature flag, pass separate configuration objects to two parallel tests instead of setting and restoring a shared environment variable. A stopped or failed test can otherwise leak its modifications. Test that configuration is rejected at startup in isolation rather than mutating the environment throughout service code.
64. How do spawn and exec differ for child processes?
spawn can stream stdout and stderr and takes an executable plus arguments when not using a shell. exec runs a command string through a shell and buffers output. Prefer a fixed executable and argument array for untrusted values, and still validate allowed options.
An imaging command can be launched as a fixed binary with controlled arguments and consumed incrementally rather than through a command string. Even without a shell, input that resembles an option can alter invoked-program behavior. Keep an allowlist of supported operations and verify resource and exit limits.
65. What is the difference between child-process exit and close events?
exit reports process termination; close follows when its stdio streams have closed. If you need all captured output, wait for the appropriate close and stream handling. Handle spawn errors separately and avoid resolving your wrapper twice.
In an export wrapper, receiving a zero exit code does not by itself mean all captured logs reached your application. Consume both pipes as needed and settle on the lifecycle event that matches the contract. Ensure startup failures and nonzero exit codes are not mistaken for a successful empty result.
66. When should you use worker threads rather than child processes?
Choose workers for CPU-intensive JavaScript when message passing or transferable data fits and process isolation is not necessary. Separate processes offer stronger fault and memory isolation. Benchmark startup, message size and failure recovery before deciding.
A parallel image transform might fit a reusable worker pool when it only passes typed data and returns results. A separate subprocess may be preferable when isolation from a native library crash is critical. Neither approach removes the need to cap work and arrange a predictable shutdown.
67. How are worker thread data and results transferred?
Messages normally use structured cloning, transferable objects can move ownership of compatible storage, and SharedArrayBuffer permits shared memory. Cloning large inputs costs time and memory; ownership transfer can invalidate sender-side views. Use explicit message contracts.
A worker processing a large binary block can receive a transferable owned buffer without cloning its bytes. That changes what the sender may still access. If two tasks need the original, clone deliberately or arrange ownership so it remains clear which side can use or mutate the data.
68. Why use a pool of workers rather than one worker per task?
A pool amortizes initialization and bounds CPU concurrency and memory. Add a bounded queue, deadlines and explicit worker failure handling. An unbounded queue in front of a fixed pool still permits overload.
For instance, a pool with four workers and room for a finite number of jobs can accept normal bursts while refusing sustained overload. Measure the queue deadline from admission, not the moment a worker starts. Count canceled and expired entries so pending work does not quietly occupy the entire buffer.
69. What does AsyncLocalStorage help with?
It propagates context such as request ID through associated asynchronous operations, reducing the need to pass that ID through every utility. Initialize each request with run and test custom callback integrations. It is not a substitute for explicit authorization checks.
Set the context at request entry and verify the same request ID appears inside promises and integration callbacks. A detached background job may need its own new context with an explicit parent ID. That context ties logs together but does not establish identity or entitlement to data.
Node.js (JavaScript) example
Each concurrent operation reads its own request ID. This test proves propagation through the chosen callback, not across workers or every third-party integration.
70. How should you use structured logging for a Node.js service?
Write machine-readable events with levels, timestamps, request IDs and stable operation names. Redact credentials and personal data before serialization. Record a failure at the ownership boundary rather than logging the same exception in every stack layer.
For a dependency timeout, record the upstream operation, elapsed time and retry outcome under one correlation ID. Avoid putting session tokens or arbitrary headers into logs by default. Choose a small schema that monitoring can query across versions and keep high-cardinality values out of metric labels.
71. How do you distinguish event-loop lag from event-loop utilization?
Lag measures how late the loop can attend scheduled work, while utilization estimates the share of time the loop spends active instead of idle. Compare percentiles and utilization deltas over a window and read both with CPU, latency and resource metrics.
An application can show a small number of very long event-loop delays even when average utilization looks reasonable. Conversely, short frequent callbacks can keep utilization high without large spikes. Compare utilization and histograms within the same traffic window before diagnosing which condition is hurting callers.
72. How can you test timer-driven logic without making tests slow or flaky?
Inject a clock or use supported timer mocks and advance time deliberately. Keep deadlines and business state separable from real time. Confirm which timer APIs the test double covers, and test at least one real integration path for cancellation.
For a retry policy, advance an injected clock past the first delay, assert the attempt, then advance beyond the total deadline and assert that no new attempt starts. A fake timer does not validate actual socket behavior. Keep separate tests for HTTP client cancellation against a real local endpoint.
73. What should an HTTP integration test check beyond status code?
Assert response shape, headers and effects such as persistence or idempotency. Start the service on an OS-selected port and close it after the test. Include malformed input and canceled-request cases when the application owns those behaviors.
A POST returning 201 can still be broken if a retry creates a second row or if the body contains an unstable identifier. Assert what the database or stub recorded. Test using an isolated account and fixture so a failure can be attributed to the request under test.
74. How would you reliably test a stream failure path?
Use a controlled source that emits one valid chunk and then fails, or a writable that rejects a specific write. Assert rejection, resource cleanup and whether any partial data escaped. Avoid assuming a successful byte count implies a complete stream.
A test sink can record which chunks arrived before failing its second write, then expose whether close or destroy ran for the whole operation. Include a slow sink as a separate test because immediate failure does not exercise backpressure. Completion metrics should distinguish partial output from success.
Node.js (JavaScript) example
A pipeline rejection and a destroyed sink are separate assertions. If the sink is a file or a partially committed response, test its external state as well.
75. How do source maps help diagnose production errors?
They map generated locations back to original source when the runtime or monitoring tooling is configured to use them. Test with a known throw in the deployed build. Keep source maps out of public responses unless deliberate sharing is acceptable.
A minified bundle often produces stack positions unfamiliar to an engineer on call. Confirm the deployed build ships or records the appropriate maps for authorized tooling and that versions match. Mismatched maps can point to the wrong file and line, making a plausible stack trace misleading.
76. What should your service do with rejected promises that are not handled?
Fix missing awaits, returns and ownership. At process level, collect diagnostic context and follow a defined fail-and-restart policy instead of blindly swallowing failures. Runtime behavior can depend on flags; make the production configuration explicit.
The process-level handler is a last line of visibility, not a substitute for owning every background task. For instance, explicitly catch a scheduled cleanup rejection and apply a retry or alert policy at that boundary. Keep application behavior distinct from flags controlling what an unhandled error does to the process.
77. How do you validate a JSON body without trusting its apparent shape?
Limit the bytes, parse safely and validate the resulting value against an explicit schema, including types, required fields and bounds. A successful JSON parse does not verify semantics. Validate authorization and uniqueness independently.
A JSON object with a string where a numeric quantity belongs can parse successfully while still being invalid. Reject or deliberately coerce according to one documented policy. Distinguish syntax, value and permission errors to make handling testable without exposing unnecessary details.
78. How would you make a write request safe to retry?
Use a stable idempotency key tied to the operation and a durable uniqueness boundary. Record outcome and request identity atomically with the effect where possible. Reject reuse of the same key with a different payload instead of treating it as a replay.
If a billing client cannot tell whether a request succeeded, a second request with the same key should return or resolve the recorded outcome rather than charge again. Put expiry and conflict behavior in the contract. Also test concurrent requests with the same key, not only sequential replay.
79. How do you prevent a burst of outbound operations from overwhelming dependencies?
Use a concurrency limit as well as a bounded admission queue and sensible deadlines. Separate limits by dependency when one failure domain should not starve another. Reject or defer excess work rather than growing Promise.all batches without a bound.
If one upstream slows, calls to that upstream can occupy every slot in a shared global pool. Allocate a limited budget to each important dependency and expose saturation signals. Decide whether the service rejects immediately or queues briefly based on the caller's deadline and recovery options.
80. What should happen after a service receives SIGTERM?
Mark readiness false, stop accepting new work, let bounded in-flight work finish, close pools and connections, and enforce an overall shutdown deadline. Handling the signal changes the default exit behavior, so ensure the process really terminates.
For a rolling release, an instance can still receive traffic while routing updates propagate. Test both new requests and existing long-lived connections during drain. Make the process exit before the host's hard-kill deadline, leaving time to report which accepted jobs completed or must be retried.
Node.js Interview Questions and Answers for Experienced
Strong responses identify what to measure before choosing a fix and make the intended failure and recovery behavior explicit.
81. A service's p99 latency doubles while median latency stays flat. How would you investigate?
Break latency down by route, payload size and dependency, then compare timing percentiles with queue depth, GC pauses and event-loop delay. Profile a representative slow window. A small CPU-heavy request class can degrade the tail for unrelated requests sharing the loop.
As an isolation step, reproduce with expensive report requests present and then absent while holding total request rate and downstream latency fixed. If only the mixed workload causes tail spikes on unrelated endpoints, try admission isolation or offloading and remeasure the same percentile. Avoid using CPU averages as a substitute for timing under peaks.
82. A Node.js process has rising RSS but stable heapUsed. What do you check?
Compare external and arrayBuffers metrics, in-flight streams, native allocations and allocator behavior. A stable V8 heap does not rule out growing Buffer or native memory. Check trends at equal load and inspect process-level limits before calling it a JavaScript object leak.
If external and arrayBuffers climb during slow downloads, sample memory with the same traffic after temporarily limiting export concurrency. If only RSS rises and later plateaus, allocator behavior can be a different explanation. Compare container-level memory and process metrics; these numbers measure different things and are not meant to sum neatly.
83. How would you confirm a JavaScript heap retention problem?
Compare retained-object paths and heap growth after comparable workload cycles and garbage collection. Look for owners such as unbounded caches, listeners or pending jobs. Capture snapshots on a safe replica because snapshot generation can pause the process and increase memory pressure.
For example, growing request objects retained through one global event bus are stronger evidence than seeing a lot of request-shaped allocations in a single snapshot. Remove the subscription owner in a reproduction and verify the retained graph and steady-state trend improve. Treat any snapshot as sensitive diagnostic data.
84. How would you investigate CPU spikes without guessing which route caused them?
Collect CPU profiles under matching traffic and correlate samples with route and event-loop metrics. Separate user-code cost, parsing, serialization and GC. Narrow the workload to reproduce the hot path before blaming a library or adding hardware.
If a profile points to synchronous serialization rather than database access, measure response size and isolate the largest routes. Separate several possible fixes: return fewer fields, change pagination, or move processing off the main loop. Label the expected bottleneck and re-run the same test so changes are comparable.
85. What indicates libuv pool contention rather than event-loop saturation?
Long native operation waits with relatively healthy loop delay can point toward the pool or an underlying resource. Compare measured filesystem, crypto or lookup latency independently and inspect CPU and disk metrics. Treat larger pool sizes as a controlled experiment, not a diagnosis.
If independent filesystem work slows only during encryption or password-derivation bursts, measure each workload in isolation and repeat with controlled concurrency. Disk queueing, CPU pressure and task pool saturation can all look similar from request latency alone. An improvement when limiting a class is more informative than merely observing a large queue.
86. How would you select worker pool size in a container?
Start with effective CPU quota and profile tasks of realistic size. Leave capacity for the event loop and native pool; more threads than useful CPU often raise contention. Scale queue capacity separately and test p95, throughput and cancellation under load.
A container can see a machine with many cores while being allowed only a small fraction of that capacity. A one-worker experiment may beat a large pool if CPU is being throttled. Measure delay when the pool is full, and set limits with the real topology rather than characterizing throughput on an unconstrained workstation.
87. How do you design an overload policy for mixed cheap and expensive routes?
Classify work by resource profile and apply distinct concurrency and queue limits to avoid head-of-line blocking. Keep response deadlines finite and return a deliberate overload result. Load test both isolated routes and their production mix.
For instance, give an expensive export its own small concurrency pool and stop admitting work once its queue budget is reached. Keep interactive reads independent when possible. Distinguish quota rejections from unexpected failures so alerts and client retry behavior reflect why the service declined work.
88. How do you decide whether to scale a Node.js API across processes or instances?
Use multiple isolated processes or instances when one loop cannot use the available capacity or when failure isolation matters. Account for replica memory and shared dependency limits. Move session and other required state out of process, or explicitly design affinity and its failure behavior.
If adding replicas increases throughput until connections to the datastore saturate, the next replica can make every request slower. Size per-replica pools against the global dependency budget. Compare process isolation and operational complexity with a worker-only design when most of the load comes from one bounded CPU path.
89. What trade-offs arise when choosing sticky routing for real-time connections?
Affinity keeps a client on its existing connection owner, but complicates failover and rebalancing. Use explicit reconnect behavior and share durable state or fan-out through a broker. Test instance loss during an active connection rather than trusting steady-state routing.
A live dashboard should reconnect with a durable cursor rather than assume the same instance still holds replayable state. If a broker fans out only new notifications, the reconnection protocol should fill the gap before live events resume. Limit catch-up work so a reconnect storm does not cause a second outage.
90. How would you drain a deployment that supports HTTP keep-alive?
Fail readiness, stop accepting new connections and coordinate the proxy's routing update. Close appropriate idle connections and stop work on long-lived or upgraded connections using an explicit drain policy. Set a deadline and verify behavior on the deployed Node version.
A stale pooled socket may remain even after the load balancer stops choosing the old backend. Test multiple requests on the same connection before, during and after signaling drain. WebSockets are a separate lifecycle and should not be assumed to close automatically with the ordinary HTTP listener.
91. How would you update a message consumer without losing accepted jobs?
Stop fetching before shutdown, let bounded work finish and commit acknowledgment only after the durable result is safe. If the deadline expires, let unfinished deliveries return to the broker according to its semantics. Design replay-safe side effects because a crash can happen between effect and acknowledgment.
For example, a worker that commits a row and dies immediately before acknowledging should make the replay see the existing durable result. Test that exact ordering using a controlled failure. Acknowledging before the effect avoids replay but can permanently lose the work, which is a different and usually unacceptable contract.
92. How do you design bounded retries across nested Node.js services?
Put retries at the layer best placed to classify errors and share a total deadline and attempt budget. Use backoff with jitter and avoid repeating non-idempotent effects. With retries at every layer, even a small attempt count can amplify load during an outage.
If the client, gateway and downstream each try a failing call three times, one user action can produce many more attempts than expected. Assign ownership, log the attempt at that layer and propagate the remaining budget. Back off on sustained overload instead of allowing retry volume to preserve the original rate indefinitely.
93. How would you handle half-success when writing to a database and emitting an event?
Use a transactional outbox where the DB change and pending event are committed together. Publish outbox entries with retries and design consumers for duplicate deliveries. A successful local commit does not prove the broker received the event.
A relay may send the same outbox entry twice if it crashes after the broker accepted it but before marking it complete. Give messages stable IDs, put deduplication near the consumer's durable effect, and monitor outbox age. This distinguishes a durable pending event from one that has actually been consumed successfully.
94. How would you process huge request payloads without holding them in RAM?
Stream with budgeted chunking and pause reads when downstream processing cannot keep up. Enforce limits on compressed and expanded size when applicable, and clean up partial files or writes on error. Do not call a streaming design bounded until pressure testing confirms it.
For a multi-gigabyte upload, stream to a temporary object with an explicit completion action. If validation fails after writing some bytes, abort or remove that object so partial data cannot be mistaken for complete. Test with a deliberately slow destination and inspect total memory across multiple simultaneous uploads.
95. How should you limit decompression in a Node.js ingestion pipeline?
Set an upper bound on decoded bytes, combine it with time and concurrency budgets, and abort the pipeline when the limit is exceeded. A Content-Length for compressed bytes is insufficient. Place cleanup around every resource acquired before validation completes.
For example, count expanded bytes while decoding instead of waiting for decompression to finish and then testing the size. The write target must also be disposable if validation stops partway. Choose clear metrics for cancellation, limit trips and natural completion so later operators can distinguish them.
96. A proxied download sometimes ends early with status 200. How would you diagnose it?
Correlate source, transform, destination and proxy lifecycle events using a request ID. A 200 reports committed headers, not complete transfer. Check premature closes and expected byte count or integrity checks; add tests for midstream upstream errors and disconnects.
If the upstream object declares a size, compare bytes observed at each boundary rather than trusting frontend logs alone. Correlate the failure with timeout and close reasons. In a protocol where consumers need integrity assurance, check a checksum or explicit completion indicator rather than inferring success from a percentage of bytes.
97. How do you choose a buffering threshold for a multi-stage stream?
Measure throughput and memory with realistic producer speed, slow consumers and concurrent requests. Consider each stage's readable and writable buffering separately. Larger thresholds may improve batching but increase residency and cancellation waste, especially with object mode.
For a report moving from a fast database cursor to a slow network, increasing the transform buffer may improve burst throughput while consuming considerably more RAM at peak time. Test with slow clients and vary only one threshold at a time. A configuration that wins a single-stream benchmark may lose under concurrency.
98. How do you ensure a stream-based protocol handles split UTF-8 characters?
Use a streaming decoder that carries an incomplete multibyte sequence and finalize it at end of input. Decide explicitly whether invalid bytes are rejected or replaced. Test boundaries by splitting a multibyte character at every possible byte position.
An input byte split inside a euro sign can produce replacement characters if each chunk is decoded independently. Treat end-of-stream flushing as part of the parser contract, especially when the final byte sequence is incomplete. Add cases for valid boundary splits and malformed tails so behavior stays deliberate across refactors.
Node.js (JavaScript) example
Every possible two-chunk split reconstructs the valid text. StringDecoder can replace malformed data; if a protocol must reject it, use an appropriate strict decoder and add malformed-input tests.
99. How do you safely prioritize or discard work in a queue shared by tenants?
Set per-tenant and global limits, enforce fairness and define expiration before choosing scheduling order. Apply policy before allocating expensive resources and give callers a clear retry or reject response. Measure drops and wait time by class without logging raw tenant payloads.
A tenant that submits many expensive jobs can exhaust a globally bounded queue even when total memory remains safe. Combine quotas with fairness or reservation for smaller tenants, and define how stale queued work is removed. Assess fairness with a mixed workload, not aggregate throughput alone.
100. How do you examine where asynchronous request context is lost?
Create a reproducible request with a unique context, then check each boundary and custom callback where the ID disappears. Use AsyncResource or a correctly bound wrapper if the integration does not preserve context. A worker thread or separate process needs explicit context propagation.
If context disappears only after a pooled callback library invokes completion, add tracing at enqueue, dispatch and callback execution. Preserve context per job rather than binding the worker once at process start, which could attach the wrong request. Test two concurrent jobs so context mixing is detectable.
101. What would you instrument through Diagnostics Channel?
Use documented channels or a carefully defined library channel for low-coupling diagnostic events. Keep subscribers cheap, avoid secrets in messages and check if subscribers exist before expensive payload construction. Test behavior when no observer is present.
A database adapter might expose a stable event with operation name, duration and a coarse outcome. Capture it without copying query arguments or customer data. Benchmark subscriber overhead at expected traffic and give instrumentation code its own failure handling so diagnostic work does not become a source of latency.
102. How would you design baseline observability for a Node.js service?
Record request rate, errors and duration, then add queue depth, event-loop delay, saturation, memory and downstream timing. Pair these with correlation IDs and explicit error classes. Choose bounded metric labels rather than IDs that make time series unbounded.
For a real incident, a slow endpoint and a busy loop plus normal upstream time suggest a different hypothesis than a full dependency queue with low loop lag. Start with a small set of signals that distinguish those states. Verify alerts in a failure exercise so each tells an operator what to inspect next.
103. How can JSON serialization become a production bottleneck?
Creating and sending a large JSON structure can allocate significant memory and spend time synchronously on the loop. Profile serialization and reduce payloads with projections or pagination. If streaming changes the response format or error semantics, make that an explicit client contract.
If a backend builds a huge nested response before calling JSON.stringify, switching network writes to streams may still leave the original allocation and CPU cost intact. The input construction and encoding both need examination. Pagination or projecting the requested fields can lower costs before adding format complexity.
104. How do you reduce user-impacting garbage collection pressure?
Measure allocation rate, heap growth and pause timing first. Bound caches and in-flight batches, shorten object lifetimes and reduce large temporary copies. Increasing heap size can delay collection but cannot correct retention or a high allocation rate by itself.
For instance, a cache that retains a fresh copy of every normalized payload can create steadily increasing allocation and retention. Put a real byte or entry budget around it and measure eviction behavior under skew. A larger heap might simply postpone a later pause without improving the service over time.
105. What safeguards matter when running a CPU-heavy library in a worker?
Bound input size, queue length and execution time; handle worker crash and replacement. Ensure side effects are idempotent before retrying work after termination. Passing an AbortSignal to a caller does not automatically interrupt arbitrary CPU code in another thread.
A timed-out job may already have written part of its result when a worker is terminated. Give the parent an ownership protocol, use temporary outputs when practical and decide what can be replayed. Test forced worker replacement explicitly instead of treating cooperative cancellation as representative of all failures.
106. How would you reduce worker messaging overhead for binary inputs?
Transfer compatible ArrayBuffer ownership when the sender no longer needs it, or use deliberately shared memory with synchronization. Ensure the backing store is safe to transfer and not unexpectedly shared by other views. Benchmark against copying on representative buffer sizes.
With a typed-array slice, the visible segment may occupy only part of a larger backing allocation. Do not assume transferring its backing buffer is always safe for sibling views or always allowed. Establish ownership and bytes transmitted before trying to optimize away a copy.
107. Why might a child process keep a Node.js parent from shutting down?
Open stdio, IPC channels, process references and output that is never drained can hold resources. Decide which party owns termination, close or consume pipes, and supervise process exit. unref does not automatically close every independent handle.
A subprocess with an open stdout pipe can block if the parent does not consume output, preventing expected completion. Test a verbose child and a child that does not exit on its own. Make it clear whether termination, retained logs and cleanup belong to the wrapper or a supervisor.
108. How would you roll out a module-system migration in a shared Node.js package?
Inventory runtime versions and supported import paths, then add compatibility tests for real consumers in both module formats. Preserve explicit supported subpaths and check that dual entry points do not accidentally split singleton state. Release any breaking API changes deliberately.
Before shipping a dual-format package, load both published entry points in one real consumer process and test shared registration or cache behavior. Gradually migrate dependent packages rather than treating the change as a build-only refactor. Record the supported module and Node versions in the release contract.
109. How would you diagnose an import that works in development but not production?
Compare actual runtime version, package type, emitted extensions, export conditions, installation contents and deployment paths. A bundler can resolve imports the Node loader rejects. Reproduce with the shipped artifact in a production-like runtime rather than re-running the development toolchain.
A local runner may resolve a TypeScript alias that the deployed JavaScript imports literally. Inspect the effective output and package layout before modifying production flags. Keep one minimal smoke test that starts the shipped service with a production-style dependency install.
110. How do you keep dependency upgrades reproducible and low risk?
Use a committed lockfile and the matching package-manager version in CI, then review changed transitives and run representative tests on the built artifact. Deploy gradually and keep rollback compatible with any database changes. A clean audit report is not proof of runtime compatibility.
If an upgrade changes a native addon or build step, test on the operating system and architecture you actually deploy. Lockfile reproducibility alone will not expose incompatible binaries or externally changing services. Track rollback prerequisites so a software rollback does not fail against newly changed data.
111. How would you handle cancellation when two requests share the same upstream work?
Track caller interest separately from the underlying operation. Cancel individual waits immediately, but only cancel shared work when no callers remain interested or an operation deadline applies. Prevent a canceled caller from deleting a newer cache entry.
For example, if two clients fetch the same immutable object, canceling one caller can return immediately without wasting progress for the other. But a caller arriving after cancellation should not attach to an operation already being torn down. Test cancellation and replacement interleavings explicitly.
112. How would you enforce separate DNS, connection and response budgets?
Choose a client with the required phase-level controls, and layer an overall deadline across phases and retries. Instrument actual timestamps and honor cancellation after headers as well as before them. Document which timers start at queue entry versus socket acquisition.
A connection can spend significant time awaiting a pooled slot before DNS or socket work begins. If the only timer covers response headers, queueing can already violate the user deadline. Instrument durations at each meaningful transition and prove any retry still fits the shared deadline.
113. How do you avoid leaking event listeners in timeout races?
Use a scoped owner and detach listeners on every outcome, including success, deadline and disconnect. Prefer once for one-shot events but remember it is not auto-removed if another event wins first. Repeat the race test to confirm counts and resource use return to baseline.
When racing an emitter event against a timer, merely awaiting the winning promise does not remove the losing listener or timer. Centralize teardown so both normal and failure paths unwind. Exercise many iterations with a long-lived emitter and see whether listener counts rise after each settled request.
114. How do you distinguish a recoverable request failure from a fatal process error?
Expected input or dependency errors belong within the request boundary. An uncaught error can leave invariants or process state unknown; record diagnostics, terminate under a supervisor and replace the process. Do not treat a process-wide handler as a way to keep accepting traffic indefinitely.
For example, if an unhandled error occurs during an in-memory state update, there may be no safe way to establish which invariants still hold. Prefer supervised replacement and replay-safe durable effects. Use scoped error handlers for normal failures so they do not trigger broad restarts unnecessarily.
115. How would you use diagnostic reports in a production incident?
Configure reports for selected trigger conditions and store them where access is controlled. Use their stack and runtime resource information alongside metrics to identify evidence, not as proof by themselves. Review sensitive contents and operational overhead before enabling collection broadly.
A report taken at high memory pressure can be useful for seeing native handles and runtime state, but it may contain sensitive context and isn't the same as a heap snapshot. Choose what to collect based on the incident hypothesis. Set retention, access and redaction policy before enabling automated collection.
116. How would you make a startup dependency failure diagnosable and safe?
Validate configuration first, then try required initialization with time limits and a clear redacted failure. Remain unready until essentials are healthy; fail rather than accepting work in a partially initialized state. Decide which optional dependencies can degrade without blocking startup.
If a required signing configuration is missing, fail before becoming ready and avoid printing its value. An optional recommendations API going offline may instead allow readiness with degraded behavior. Model both cases and document what clients should see so operators don't confuse a deliberate degraded state with a failed release.
117. How do you test graceful shutdown under actual concurrent traffic?
Launch the service as a child process, start in-flight requests and signal termination while also checking readiness and admission. Assert that allowed work completes, overdue work is canceled and exit occurs by deadline. Cover long-lived connections separately.
For an endpoint streaming updates, send the termination signal just after headers and check whether policy permits completion or explicitly ends the stream. Assert process exit and socket closure rather than only a log line. Use a bounded test deadline so the test itself cannot hang on leaked handles.
118. How would you compare two Node.js implementations fairly under load?
Hold runtime version, resources, payload distribution, dependency behavior and connection policy constant. Include warmup, varied concurrency and slow-client cases; report p50, p95, p99, error rates and resource use. Compare more than peak throughput to avoid hiding tail regressions.
It is possible for an implementation to improve throughput by silently accepting a growing queue. Keep arrival rate and admission policy visible, and compare resource use and timeout rate at the same successful throughput. Include the overload point so the benchmark says something about production capacity.
119. When is a Node.js core benchmark misleading for a real service?
A tight benchmark can omit JSON sizes, contention, GC, sockets, logging and downstream latency. It may also compare warm optimized code with a cold candidate. Use it to test a hypothesis, then verify using an end-to-end workload that isolates the change.
A microbenchmark of a parser can identify a promising implementation, but a route dominated by upstream latency may not benefit much at normal load. A mixed workload can still reveal improvements to the tail when the parser shares the loop. Report where an observed gain applies rather than generalizing from a synthetic result.
120. How would you establish an operational contract for a critical Node.js API?
Define latency and availability objectives, input and concurrency bounds, retry and idempotency rules, cancellation, readiness, shutdown and error semantics. Pair each policy with measurable signals and realistic failure tests. Make the expectations visible to both operators and callers.
For example, define what occurs if an accepted request outlives its client connection, how repeat writes are identified and what excess traffic receives. Include an actionable runbook for sustained lag, downstream outages and partial responses. An operational contract is only useful if operators and consuming teams can test and rely on it.
Node.js Documentation and Further Reading
Check the reference for the Node.js version you deploy, especially for module interoperability, HTTP shutdown and test-runner APIs.
Similar Posts
