Node.js Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How is the V8 heap organized for garbage collection?
Correct answer: Into a young generation and an old generation
Most objects die young, so frequent cheap scavenges reclaim them. Objects that survive are promoted to the old generation, whose collections are rarer and more expensive, though mostly concurrent and incremental.
2. A container has 2 GB of memory, but the Node.js process crashes with 'JavaScript heap out of memory' at about 1.4 GB. What should you check?
Correct answer: The V8 old-space limit:
--max-old-space-sizeRecent Node.js versions size the heap from the container's memory limit, but the heap is not all memory: Buffers, native code and thread stacks live outside it. Leave a margin.
3. Which pattern is a classic cause of a memory leak in a Node.js server?
Correct answer: A module-level
Mapcache that's never evictedAnything reachable from a module-level object lives forever. Use a bounded LRU cache with TTL, a
WeakMapkeyed by objects, or an external cache like Redis.4. How do you find what is leaking in a Node.js process?
Correct answer: Compare several heap snapshots taken over time
The comparison view shows objects allocated between snapshots, and retainer paths show what keeps them alive.
--heapsnapshot-near-heap-limitcan take a snapshot right before a crash.5. Why can a closure cause unexpected memory retention?
function handler(req) { const hugeBody = req.body; // 50 MB const id = hugeBody.id; emitter.on("done", () => console.log(id)); }Correct answer: A long-lived listener keeps its closure's scope alive
The real bug is the listener that is never removed. V8 may also keep variables of a shared context alive. Remove listeners, use
once, and don't capture large objects.6. What are hidden classes (shapes) in V8, and why do they matter?
Correct answer: Object layouts that let V8 use fast inline caches
Creating objects with the same properties in the same order keeps them on one shape. Adding properties in different orders or using
deletecan make hot code polymorphic and slower.7. What does
process.memoryUsage()report asrss?Correct answer: All of the process's memory that's held in RAM
Compare
heapUsedwithrss. Ifrssgrows while the heap stays flat, look at Buffers (arrayBuffers,external) or native modules.8. What are
WeakRefandFinalizationRegistryNOT good for?Correct answer: Releasing important resources at a predictable time
Garbage collection timing is not guaranteed, and finalizers may never run. Release resources explicitly with
close()orusing/Symbol.dispose.9. How do you find which functions use the most CPU in production-like conditions?
Correct answer: Record a CPU profile under load and read a flame graph
Profiles show where time goes, including GC and native code. Generate load with a tool like autocannon or k6, since idle profiles show nothing useful.
10. p99 latency is high but average CPU usage is low. What might be the cause?
Correct answer: Occasional event loop blocking delaying queued requests
Measure event loop delay with
monitorEventLoopDelay. Short CPU spikes don't show up in average CPU but stall all concurrent requests.11. What is a typical cause of a slow regular expression blocking a Node.js server (ReDoS)?
/^(a+)+$/.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaa!");Correct answer: Nested quantifiers cause catastrophic backtracking
Since the regex runs on the main thread, one request can freeze the whole server. Avoid nested quantifiers, limit input length, or use a linear-time engine like RE2.
12. Why can
JSON.stringifyof a large response be a bottleneck, and what helps?Correct answer: It's synchronous and CPU-heavy; schema serializers help
Fastify compiles a serializer from the response schema, which is faster and also drops fields not in the schema. For huge lists, paginate or stream.
13. When does increasing
UV_THREADPOOL_SIZEactually help?Correct answer: When
fs,dns.lookup,cryptoorzlibcalls queue upNetwork sockets don't use the pool, and JavaScript always runs on the main thread. For CPU-bound JS, use worker threads.
14. Why can
dns.lookupbe a hidden bottleneck for outgoing HTTP calls?Correct answer: It uses the thread pool, which
fsandcryptoalso needOptions include connection reuse (keep-alive), caching DNS results, or
dns.resolve*, which uses c-ares on the network instead of the pool (but ignores/etc/hosts).15. What is a good way to share large binary data between worker threads without copying?
Correct answer: Transfer an
ArrayBufferor use aSharedArrayBufferTransferring moves ownership: the sender can no longer use the buffer.
SharedArrayBufferlets both sides read and write the same memory, so useAtomicsto avoid races.16. Why should a server use a pool of worker threads instead of creating a new worker per request?
Correct answer: Starting a worker is expensive, so a pool reuses them
Libraries like Piscina manage a pool and a task queue. Size the pool close to the number of available cores.
17. Behind a load balancer (e.g., AWS ALB with a 60 s idle timeout), clients sometimes get 502 errors. What's a common cause?
Correct answer: Node's
keepAliveTimeoutis shorter than the balancer'sSet
keepAliveTimeoutabove the balancer's idle timeout (andheadersTimeoutabove that) so the balancer always closes idle connections first.18. Why might
server.close()not finish during graceful shutdown?Correct answer: It waits for open keep-alive connections to end
Typical shutdown: mark not ready, stop accepting connections, let in-flight requests finish, close idle connections, then close pools and exit, with a deadline.
19. How should a server limit the size of incoming request bodies?
Correct answer: Set a limit in the parser and reject larger ones with 413
Without limits, a client can exhaust memory with one huge request. Stream large uploads to storage instead of buffering them.
20. What does
server.requestTimeoutprotect against?Correct answer: Slow clients holding connections open on purpose
It limits how long the server waits to receive the whole request.
headersTimeoutdoes the same for headers. Handler time needs your own timeouts.21. What does HTTP/2 change for a Node.js API used by browsers?
Correct answer: Many requests share one connection, with header compression
Browsers use HTTP/2 only over TLS. In practice TLS and HTTP/2 often terminate at a proxy or CDN, which talks HTTP/1.1 to Node.js.
22. What is
undiciin Node.js?Correct answer: The HTTP client that powers the global
fetchUsing undici directly (
Pool,Agent,request) gives finer control over connection pools and timeouts thanfetch.23. What does an async generator in
pipelinegive you?await pipeline( createReadStream("in.csv"), async function* (source) { for await (const chunk of source) yield transform(chunk); }, createWriteStream("out.csv"), );Correct answer: A transform as plain async code, with backpressure handled
The generator pulls the next chunk only when the writer is ready. An error anywhere destroys all streams and rejects the promise.
24. What does
highWaterMarkcontrol?Correct answer: How much a stream buffers before signalling backpressure
It's a threshold, not a hard limit. Ignoring
write()returningfalselets the buffer grow without bound.25. How do Node.js streams interoperate with Web Streams (
ReadableStream)?Correct answer: With
Readable.toWeb()andReadable.fromWeb()Web Streams are the standard across runtimes (browsers, Deno, Bun, edge). Node streams are still common in older APIs, so conversion is often needed.
26. Processing an upload stream, you call an async function for each chunk without awaiting it. What's the risk?
Correct answer: No backpressure, so pending work and memory keep growing
Await inside
for await, or use bounded concurrency (for example,readable.map(fn, { concurrency: 4 })), so reading slows down when processing does.27. What is prototype pollution?
merge({}, JSON.parse('{"__proto__": {"isAdmin": true}}')); ({}).isAdmin; // trueCorrect answer: Input sets properties on
Object.prototypefor all objectsUnsafe deep merges and path setters are the usual cause. Block
__proto__,constructorandprototypekeys, useObject.create(null)orMap, and validate input with a schema.28. How do you safely serve a user-requested file from an
uploadsdirectory?Correct answer: Resolve the full path and check it stays in
uploadsPath traversal can use encodings or absolute paths, so a single replace isn't enough. Better still, store files by generated IDs and keep names in the database.
29. Your API fetches a URL supplied by the user (e.g. for link previews). What attack must you prevent?
Correct answer: SSRF: requests to internal services or cloud metadata
Allow only needed schemes and ports, resolve the host and block private and link-local ranges, disable or re-check redirects, and use network-level egress rules.
30. What does the Node.js permission model (
--permission) do?Correct answer: Restricts what the process can access unless allowed
For example,
--allow-fs-read=/applimits reads to/app. It's defense in depth against compromised dependencies, not a full sandbox.31. Which measure helps most against malicious package versions (supply-chain attacks)?
Correct answer: A committed lock file with
npm ciand careful updatesAttackers publish compromised versions of popular packages. Delaying updates, reviewing diffs of new versions and npm provenance reduce the risk.
32. Why is
eval(ornew Function) on user input dangerous even in a 'sandbox' likevm?Correct answer: It gives the input full code execution;
vmisn't a boundaryEscapes from
vmcontexts are well known. Run untrusted code in a separate process or container with strict limits, or avoid running it at all.33. Which HTTP-level issue should you protect a Node.js API from besides application bugs?
Correct answer: HTTP request smuggling between proxies and Node
Node's HTTP parser (llhttp) is strict by default. Flags like
--insecure-http-parserweaken that and should not be used in production.34. Why should a Node.js process run as a non-root user in a container?
Correct answer: If compromised, the attacker gets fewer privileges
The official Node.js images include a
nodeuser. Combine this with a read-only file system and minimal images for defense in depth.35. Why add random jitter to exponential backoff when retrying failed calls?
Correct answer: So clients don't all retry at the same moment
Without jitter, retries come in synchronized waves (thundering herd). Also cap the number of retries and retry only safe or idempotent operations.
36. What does a circuit breaker do?
Correct answer: After failures, it stops calling a dependency for a while
It prevents a slow dependency from tying up all resources and gives it time to recover. Combine it with timeouts and a fallback where possible.
37. What problem does the transactional outbox pattern solve?
Correct answer: Saving a change and publishing an event reliably together
The event is written to an outbox table in the same transaction as the change. A separate worker publishes outbox rows to the broker and marks them sent, so delivery is at least once.
38. A message queue delivers messages 'at least once'. What must consumers do?
Correct answer: Be idempotent, as the same message can arrive twice
Exactly-once delivery is very hard in distributed systems. Idempotent handling makes duplicates harmless.
39. What is a cache stampede, and how can you prevent it?
Correct answer: Many misses on one hot key hit the DB; coalesce requests
Coalescing inside one process means sharing one in-flight promise per key. Across instances use a short lock in Redis or stale-while-revalidate.
40. Which rate-limiting algorithm allows short bursts while keeping an average rate?
Correct answer: Token bucket
Tokens refill at a steady rate, and each request spends one; a full bucket allows a burst. Sliding windows are another common approach.
41. Why should long-running or CPU-heavy work be moved out of the HTTP request path?
Correct answer: Requests stay fast, and the work can be retried and scaled
Return
202 Acceptedwith a job ID and let clients poll or receive a webhook or event. Keep jobs idempotent.42. How do you keep a slow dependency from taking down the whole service (bulkhead pattern)?
Correct answer: Limit concurrent calls per dependency, with separate pools
Like compartments in a ship, isolated limits contain failures. Combine with timeouts and circuit breakers.
43. Why might a team choose a modular monolith over microservices for a new Node.js product?
Correct answer: It's simpler to run, and modules can be split out later
Microservices bring network failures, distributed data and complex operations. They pay off when teams and scaling needs are truly independent.
44. What does OpenTelemetry provide for Node.js services?
Correct answer: A vendor-neutral standard for traces, metrics and logs
Traces show how one request flows through services. Context propagation uses the
traceparentheader andAsyncLocalStorageinside the process.45. Which metrics form the RED method for monitoring a service?
Correct answer: Rate, Errors, Duration of requests
For Node.js also track event loop delay, heap usage, GC pauses and active handles. Use latency histograms (p95, p99), not just averages.
46. What is
diagnostics_channelfor?Correct answer: Letting libraries publish diagnostic events to tools
Node.js core (http, undici) and libraries like Fastify publish events through it, so APMs don't need to monkey-patch modules.
47. What is a diagnostic report (
--report-on-fatalerror,process.report.writeReport())?Correct answer: A JSON file with the stack, heap stats and environment
It helps investigate crashes and hangs in production without attaching a debugger. Reports can contain sensitive environment data, so handle them carefully.
48. A Node.js process doesn't exit after the main script finishes. What's the usual reason?
Correct answer: Something still holds the event loop open
Close pools and servers explicitly.
process.getActiveResourcesInfo()lists what keeps the loop alive, andunref()lets background timers not hold it.49. Why is
uncaughtException+ 'log and continue' a bad pattern?Correct answer: State may be corrupted, so log and restart safely
Use the handler only for synchronous cleanup and logging, then exit with a non-zero code and let the orchestrator restart the process.
50. What do module customization hooks (
module.register,registerHooks) allow?Correct answer: Changing how modules are resolved and loaded
Tools like tsx and test runners use them. They replace the old
--loaderapproach and the hacks onrequire.extensions.51. What is the 'dual package hazard'?
Correct answer: A package's CJS and ESM builds both load, duplicating state
Solutions: ship ESM only now that
require(esm)works, or keep state in one format and wrap it in the other.52. What is Node-API (N-API)?
Correct answer: A stable C API for native addons
Addons built on Node-API don't need recompiling for each Node.js major version. Many projects now use Rust (napi-rs) or WebAssembly instead of C++.
53. What are Single Executable Applications (SEA) in Node.js?
Correct answer: Bundling a script with Node.js into one executable
It's useful for CLIs and internal tools. The app usually needs to be bundled into one file first.
54. What does the
usingdeclaration (explicit resource management) give Node.js code?{ await using conn = await pool.connect(); await conn.query("..."); } // conn is disposed hereCorrect answer: Automatic cleanup via
Symbol.disposeon block exitIt replaces many
try/finallyblocks. Some Node.js APIs, like timers and file handles, already implement the dispose symbols.55. How does Node.js handle
enumandnamespacewhen running TypeScript with type stripping?Correct answer: They aren't erasable, so they fail without transformation
Type stripping only removes types. TypeScript's
erasableSyntaxOnlyoption lets the compiler flag such syntax in advance.56. Why does test isolation matter in
node --test, and how does it work by default?Correct answer: Each test file runs in its own process by default
--test-isolation=noneruns files in one process, which is faster but can leak state. Inside one file, tests share state and you must reset it yourself.57. What is snapshot startup (
--build-snapshot) useful for?Correct answer: Speeding up startup from a prebuilt V8 heap
It's mainly for CLIs and short-lived processes where startup time dominates, and works together with SEA.
58. Running Node.js in Kubernetes, should you use the
clustermodule inside each pod?Correct answer: Usually not: run one process per pod and scale pods
One process per container keeps metrics, memory limits and restarts simple.
clusterstill helps on a single VM without an orchestrator.59. Why should a horizontally scaled Node.js service be stateless?
Correct answer: Any instance can handle any request and be replaced freely
In-memory sessions or local uploads break when the next request goes to another instance or the pod restarts.
60. What is the main trade-off of
clusterround-robin vs. letting the OS distribute connections?Correct answer: Round-robin balances more evenly; the OS can leave some busier
With round-robin the primary accepts connections and passes them to workers. It's controlled by
cluster.schedulingPolicyorNODE_CLUSTER_SCHED_POLICY.61. How do you prevent one tenant or client from exhausting a shared Node.js API?
Correct answer: Per-tenant rate limits, quotas and payload limits
This is the 'noisy neighbor' problem. Fair queuing and per-tenant concurrency limits keep latency stable for everyone.
62. Your service must call three APIs per request and can tolerate one failing. What approach fits?
Correct answer: Call them in parallel with
Promise.allSettledand timeoutsGraceful degradation keeps the main feature working. Make it clear to clients which parts are missing.
63. How does DataLoader solve the N+1 problem in a GraphQL server?
Correct answer: It batches
load(id)calls from one tick into one queryCreate a new DataLoader per request, so caching never mixes data between users.
64. When is gRPC a good fit compared with REST/JSON?
Correct answer: For internal service calls that benefit from typed contracts
Browsers can't use plain gRPC directly (gRPC-Web or a proxy is needed). REST stays simpler for public APIs and caching.
65. How do idempotency keys make POST requests safe to retry?
Correct answer: The server stores each key's result and returns it on repeats
Store the key with the request hash and the response, and handle concurrent requests with the same key (for example, with a lock).
66. How should you evolve a public API without breaking existing clients?
Correct answer: Make additive changes, deprecate clearly, version breaks
Removing or renaming fields breaks clients. Monitor usage of deprecated fields before removing them; the
DeprecationandSunsetheaders can announce it.67. Why does a Node.js process need a strategy for
SIGINT/SIGTERMwhen it runs as PID 1 in a container?Correct answer: PID 1 has no default handling, so stop signals may be ignored
Start Node.js directly (
CMD ["node", "server.js"]), not throughnpm start, which may not forward signals, and handleSIGTERMfor graceful shutdown.68. What is a reasonable way to run scheduled tasks (cron) in a Node.js service with several instances?
Correct answer: A scheduler that runs each job once, like a queue or lock
With a timer in each of 5 instances the job runs 5 times. Jobs should still be idempotent in case a run is repeated.
69. Why can
AsyncLocalStoragelose its context inside some libraries, and what fixes it?Correct answer: Queued callbacks lose it;
AsyncResource.bindrestores itContext follows the async chain where a callback was created. A pool that runs a stored callback later continues the chain of whoever triggered it, not the original request.
70. The client disconnects while your handler runs a slow database query. How do you avoid wasting work?
Correct answer: Watch
res.on("close")and abort through anAbortSignalPass the signal to
fetch, timers and libraries that support it. For databases, use query timeouts or cancellation if the driver supports them.71. You scale to 40 instances, each with a pool of 20 connections, and PostgreSQL starts refusing connections. What helps?
Correct answer: Reduce pool sizes and put PgBouncer in front of the DB
Total connections = instances × pool size, and each PostgreSQL connection is a process with its own memory. A pooler multiplexes many client connections onto few server ones.
72. Two requests read a record, change it and save it at the same time, and one update is lost. How does optimistic locking prevent this?
Correct answer: The update checks a version column and fails on a change
Optimistic locking works well when conflicts are rare. Pessimistic locking (
SELECT ... FOR UPDATE) fits frequent conflicts but holds locks longer.73. What does load shedding mean for an overloaded Node.js service?
Correct answer: Quickly rejecting new requests with 503 when overloaded
Accepting everything makes every request slow and can crash the process. Plugins like Fastify's
under-pressureimplement this, and clients should retry with backoff.74. How do you deploy a new version of a Node.js API without dropping requests?
Correct answer: A rolling update with readiness checks and graceful drain
Database migrations must be backward compatible during the rollout, since old and new code run at the same time (expand, then contract).
75. A service does heavy image or video processing. Which approach is most sensible in a Node.js stack?
Correct answer: Use native or WASM libraries in separate workers
Libraries like sharp use native code off the main thread. Very heavy pipelines often live in separate services, scaled independently through a queue.