Skip to main content
InterviewHubPRO
HomeTracksSection 21: Node.js & Libuv (60 Qs)
Section 21 of 6460 Questions (1 Per Page)

Node.js Core Internals, Libuv & Microservices Master Interview Bank

Node.js event loop phases, Libuv thread pool, Streams API, clustering, Worker Threads, memory leak diagnostics, and NestJS enterprise patterns.

Curriculum Roadmap & Learning Path

5 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.5 Connected Milestones
60 of 60 Qs

Part 1: Intro, Candid Experience & Architecture (1 - 5)

5 Questions
1
Most AskedSeniorCode#System Design

What is Node.js, and how does its single-threaded, event-driven, non-blocking I/O runtime work?

Node.js is an open-source, cross-platform JavaScript runtime environment built on Google Chrome's V8 JavaScript engine and the Libuv C library, created by Ryan Dahl in 2009. It enables JavaScript to run directly on server operating systems outside the browser.

2
SeniorCode#System Design#Microservices

Walk me through your hands-on experience building backend microservices and APIs in Node.js, and how you choose between Express, Fastify, and NestJS.

"I am a Senior Backend and Full-Stack Engineer with extensive experience building high-throughput services using Node.js, TypeScript, and modern frameworks including Express, Fastify, and NestJS.

3
SeniorCode#Forms#Performance

Describe a critical production incident or performance bottleneck you resolved in Node.js.

How to Explain in an Interview: Problem: In an Express payment gateway, service instances intermittently stopped responding, leading to Kubernetes liveness probe failures and • Root Cause: A CPU-intensive PDF invoice generation library was being invoked synchronously inside request handlers, blocking the single-threaded.

4
SeniorCode#System Design

How do you design and structure enterprise Node.js projects?

I adhere to Layered Architecture (Controller-Service-Repository) with Clean Architecture boundaries: Presentation Layer (Controllers/Routes): Handles HTTP request parsing, DTO validation using Zod, and returns HTTP responses.

5
SeniorCode#Testing#System Design

What is your strategy for automated backend testing in Node.js?

Unit Testing: Vitest or Jest for fast isolated tests of business logic and domain services with mocked repository dependencies • Integration Testing: Supertest against real Fastify/Express HTTP servers, paired with Testcontainers to spin up ephemeral PostgreSQL and Redis.

Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)

15 Questions
6
Most AskedSeniorCode#Event Loop#System Design

Node.js fundamental architecture: V8, Libuv, c-ares, llhttp.

Node.js is a C++ runtime wrapping Google's V8 engine with asynchronous libraries: V8: Google's open-source JavaScript and WebAssembly engine that compiles JS to native machine code • Libuv: High-performance C library that provides the Event Loop and asynchronous I/O abstractions (thread pool, epoll, kqueue).

7
Most AskedSeniorCode#Event Loop

Node.js Event Loop Phases in exact order.

The Event Loop continuously executes tasks in 6 distinct phases in this exact order: Timers: Executes callbacks scheduled by setTimeout() and setInterval() • Pending Callbacks: Executes I/O callbacks deferred to the next loop iteration (e.g., TCP socket errors) • Idle, Prepare: Used internally by Node.js.

8
Most AskedSeniorCode#Event Loop

`process.nextTick()` vs `setImmediate()`.

process.nextTick(): Not technically part of the Event Loop phases; it drains its queue immediately after the current operation completes, before • setImmediate(): Scheduled to execute specifically in the Check phase on the next tick of the Event Loop.

9
Most AskedSeniorCode#Event Loop

Microtasks execution relative to Macrotasks in Node.js.

Microtasks include process.nextTick() and Promise callbacks (.then(), await, queueMicrotask) • In Node.js, the microtask queue executes immediately after the currently running JavaScript operation finishes, between every phase transition.

10
Most AskedSeniorCode#Event Loop

The Libuv Thread Pool.

By default, Libuv maintains a thread pool of 4 worker threads for operations that the OS cannot handle asynchronously non-blockingly: File system operations (fs.) • DNS lookup operations (dns.lookup) • Cryptographic functions (crypto.pbkdf2, crypto.randomBytes, crypto.scrypt) • Compression (zlib.).

11
Most AskedSeniorCode#Event Loop

Scaling the thread pool with `UV_THREADPOOL_SIZE`.

You can increase the thread pool size up to 128 by setting the environment variable before Node starts.

12
Most AskedSeniorCode#Event Loop

Detecting Event Loop delay in production.

Use the perf_hooks built-in module to measure p99 Event Loop lag.

13
Most AskedSeniorCode#Event Loop#Memory Management

V8 Garbage Collection in Node.js.

V8 uses a Generational Garbage Collector divided into two main spaces: Scavenge (Young Generation): Two semi-spaces (From/To) • Mark-Sweep-Compact (Old Generation): Marks surviving long-lived objects, sweeps unmarked memory, and compacts fragmented pages to optimize.

14
Most AskedSeniorCode#Event Loop#Memory Management

Common causes of Memory Leaks in Node.js.

How to Explain in an Interview: Global variables: Accidentally holding references to large objects in global scope • Uncleared event listeners: Repeatedly attaching .on('event', fn) to long-lived objects without .off() • Unbounded caches: Storing items in plain JavaScript objects/maps without LRU eviction.

15
Most AskedSeniorCode#Event Loop

Buffers: `Buffer.alloc()` vs `Buffer.allocUnsafe()`.

Buffers allocate raw binary memory outside the V8 heap in native C++ memory: Buffer.alloc(size): Initializes memory and zeroes out all bytes • Buffer.allocUnsafe(size): Allocates raw uninitialized memory without zeroing it out.

16
Most AskedSeniorCode#Event Loop

CommonJS (`require`) vs ES Modules (`import`) resolution.

CommonJS: Synchronous, dynamic (require() can be placed inside conditionals), loads and executes the script immediately, caches exports in • ES Modules: Asynchronous, static analysis at parse-time, supports top-level await, and handles cyclic dependencies via live bindings.

17
Most AskedSeniorCode#Event Loop

Operational pitfalls of mixing CJS and ESM.

ESM cannot import named exports from CJS without default import wrappers (import pkg from 'cjs-pkg'; const { fn } = pkg;) • dirname and filename are not defined in ESM; must be derived via import.meta.url.

18
Most AskedSeniorCode#Async & Promises#Event Loop

Unhandled Promise Rejections & Uncaught Exceptions.

process.on('uncaughtException', (err) => ...): Synchronous uncaught error • process.on('unhandledRejection', (reason, promise) => ...): Promise rejected without a .catch().

19
Most AskedSeniorCode#Event Loop

Graceful Shutdown implementation.

Listen for SIGTERM and SIGINT signals, stop accepting new connections, finish in-flight requests, close DB pools, and exit cleanly.

20
Most AskedSeniorCode#Performance#Event Loop

Profiling Node.js applications with Flame Graphs.

Run Node.js with --prof flag, then process generated v8.log with node --prof-process isolate.log > processed.txt. Or use Clinic.js Flame** (clinic flame -- node server.js) to generate interactive flame graphs pinpointing hot code paths.

Part 3: Streams, Buffers & Core Modules (21 - 35)

15 Questions
21
JuniorCode#nodejs#Streams

What are Node.js Streams and why are they essential?

Streams process data sequentially chunk by chunk instead of reading the entire payload into RAM at once. Enables handling multi-gigabyte files or network payloads with constant, minimal memory consumption.

22
MidCode#nodejs#Streams

4 Fundamental Stream Types.

Readable: Source of data (fs.createReadStream, HTTP request) • Writable: Destination for data (fs.createWriteStream, HTTP response) • Duplex: Both Readable and Writable (e.g., net.Socket).

23
Most AskedSeniorCode#Pipes#CI/CD & DevOps

Stream Backpressure and `pipeline()`.

Backpressure: Occurs when a Readable stream produces data faster than a Writable stream can consume and flush it to disk/network, leading to RAM • Solution: Use pipeline from stream/promises.

24
MidCode#Forms

Custom Transform Stream implementation.

Extend Transform and implement the _transform method.

25
MidCode#nodejs#Streams

The EventEmitter Class & `MaxListenersExceededWarning`.

Maintains internal arrays of listener functions per event name. Default warning threshold is 10 listeners per event. If exceeded, Node.js logs a warning to prevent memory leaks from forgotten listeners.

26
MidCode#nodejs#Streams

Unhandled 'error' events in EventEmitter.

If an EventEmitter emits an 'error' event and has no listeners registered for 'error', Node.js prints the stack trace and crashes the entire process. Always attach .on('error', handler).

27
Most AskedMidCode#Async & Promises

`fs.promises` vs callback-based vs synchronous `fs`.

Synchronous methods (fs.readFileSync) block the entire Event Loop thread until disk I/O completes. Always use fs.promises (await fs.readFile(...)) or streaming methods in web request handlers.

28
MidCode#nodejs#Streams

`fs.readFile()` vs `fs.createReadStream()`.

fs.readFile(): Loads the entire file content into a memory Buffer before calling the callback • fs.createReadStream(): Streams the file in 64KB chunks, allowing concurrent processing with minimal RAM footprint.

29
MidCode#nodejs#Streams

The `cluster` module.

Spawns multiple child processes sharing the same server port. The master process receives incoming TCP connections and distributes them to worker processes using Round-Robin scheduling via IPC channels.

30
MidCode#nodejs#Streams

Worker Threads vs Child Processes vs Clustering.

Clustering: Multiple independent OS processes running identical server code; no shared memory • Child Processes (childprocess): Spawns external shell commands or programs; heavy OS overhead • Worker Threads (workerthreads): Multiple threads within the same OS process, sharing the same memory heap and using SharedArrayBuffer for.

31
MidCode#nodejs#Streams

Worker Thread communication.

Communicates via MessagePort using postMessage(data) and listening on parentPort.on('message'...). For high-throughput zero-copy access, uses SharedArrayBuffer with Atomics for thread-safe synchronization.

32
MidCode#nodejs#Streams

`child_process.exec` vs `execFile` vs `spawn` vs `fork`.

exec(): Spawns a shell and buffers full output in memory • execFile(): Invokes an executable directly without a shell • spawn(): Streams process stdout/stderr in chunks; ideal for long-running processes • fork(): Special spawn() dedicated to spawning Node.js scripts with built-in IPC communication channels.

33
MidCode#nodejs#Streams

The `crypto` module: Secure password hashing.

Use crypto.scrypt() or crypto.pbkdf2() with salt and high work factors for password hashing, or modern native algorithms like Argon2 via dedicated bindings.

34
MidCode#HTTP & REST APIs

`http.IncomingMessage` and `http.ServerResponse`.

IncomingMessage: Implements a Readable Stream, emitting 'data' chunks as HTTP body bytes arrive • ServerResponse: Implements a Writable Stream, allowing res.write() streaming chunks and res.end().

35
Most AskedSeniorCode#Async & Promises#System Design

`AsyncLocalStorage` and Distributed Request Tracing.

Provides thread-local-style storage across asynchronous operations, allowing Trace IDs and user session context to be accessible anywhere in the codebase without passing them through every function parameter.

Part 4: Express, Fastify, APIs & Middleware (36 - 50)

15 Questions
36
SeniorCode#Pipes#CI/CD & DevOps

Express Middleware Execution Pipeline.

Middleware functions form an array queue. Each function receives (req, res, next). Calling next() advances execution to the next middleware in the chain. Calling res.send() terminates the pipeline.

37
SeniorCode#Async & Promises#HTTP & REST APIs

`next(err)` vs throwing asynchronous errors in Express.

In Express 4, throwing an error inside an asynchronous Promise handler unhandled will crash the process or hang the request unless passed via next(err). (Express 5 natively catches rejected promises from async handlers).

38
SeniorCode#HTTP & REST APIs

Centralized Global Error Handler in Express.

Must accept exactly 4 parameters (err, req, res, next) so Express's reflection inspects fn.length === 4 to recognize it as an error-handling middleware.

39
SeniorCode#HTTP & REST APIs

Why Fastify achieves significantly higher throughput.

Radix Tree Routing: Uses find-my-way for O(K) route matching where K is route length • Pre-Compiled JSON Serializer: Uses fast-json-stringify which compiles JSON schemas into optimized C-like string concatenators, bypassing slow • Optimized Object Allocations: Minimizes garbage collection pressure per request.

40
SeniorCode#Forms#HTTP & REST APIs

Fastify JSON Schema Validation (Ajv).

Schemas validate request parameters, query, and body at compile-time.

41
Most AskedSeniorCode#Security & Auth#HTTP & REST APIs

Authentication layer with JWT and Refresh Tokens.

Authenticate credentials -> Issue Access Token (short-lived, 15m) and Refresh Token (long-lived, 7d) • Store Refresh Token in HttpOnly, Secure, SameSite=Strict Cookie • Middleware verifies Access Token signature and extracts claims on incoming requests.

42
Most AskedSeniorCode#HTTP & REST APIs

Rate Limiting Middleware with Redis.

Tracks IP or API key hit count in Redis with a 60-second sliding expiration window. If count exceeds limit, returns HTTP 429 with Retry-After header.

43
Most AskedSeniorCode#Security & Auth#HTTP & REST APIs

CORS and Preflight OPTIONS requests.

Preflight OPTIONS requests are sent by browsers for requests with non-simple methods (PUT, DELETE, PATCH) or custom headers (Authorization, Content-Type: application/json). Safe configuration specifies explicit origin whitelist instead of wildcard *.

44
SeniorCode#HTTP & REST APIs

File Uploads in Express: `multer` vs direct streaming.

multer: Parses multipart/form-data and buffers files to disk or RAM • Direct S3 Streaming (busboy): Streams chunks directly from the incoming HTTP stream into AWS S3 via @aws-sdk/lib-storage Upload, eliminating.

45
SeniorCode#HTTP & REST APIs

Input Sanitization with Zod.

Validate request body data with Zod schemas to guarantee type safety and block malformed payloads before they reach business logic.

46
SeniorCode#HTTP & REST APIs

Server-Sent Events (SSE) in Node.js.

Stream real-time server events over HTTP with text/event-stream.

47
SeniorCode#HTTP & REST APIs

Scaling WebSockets across multiple Node.js instances.

Use the Redis Pub/Sub Adapter (or Redis Streams). When a client on Instance A sends a message to a room, Instance A publishes the event to Redis, which broadcasts it to all other Node instances holding active WebSocket clients in that room.

48
Most AskedSeniorCode#Prototypes#Security & Auth

Security vulnerabilities: Prototype Pollution and ReDoS.

Prototype Pollution: Merging untrusted user objects directly into existing objects mutating proto • ReDoS (Regular Expression Denial of Service): Evil regexes with catastrophic backtracking freeze the Event Loop.

49
SeniorCode#Kubernetes#HTTP & REST APIs

The role of `helmet` middleware.

Sets critical HTTP security headers automatically: Content-Security-Policy, Strict-Transport-Security (HSTS), X-Frame-Options, X-Content-Type-Options, and removes X-Powered-By: Express.

50
Most AskedSeniorCode#Async & Promises#HTTP & REST APIs

Correlation IDs with `AsyncLocalStorage`.

Inject an X-Correlation-ID header into every outgoing HTTP request or log message, reading from AsyncLocalStorage to enable distributed tracing across microservice boundaries.

Part 5: Production Scale, Deployment & Observability (51 - 60)

10 Questions
51
Most AskedSeniorCode#Docker & Containers#Kubernetes

Containerized Docker Best Practices for Node.js.

Use multi-stage builds • Run on slim Alpine or distroless images • Run as non-root user (USER node) • Use tini as init process (ENTRYPOINT ["tini", "--"]) to properly reap zombie child processes and handle signal forwarding (PID 1 problem).

52
Most AskedSeniorCode#Kubernetes

Process Management: PM2 vs Kubernetes.

PM2: Excellent for standalone virtual machines (EC2) • Kubernetes: Standard for cloud-native enterprise deployments.

53
SeniorCode#Kubernetes

Managing DB Connection Pools during surges.

Set maximum pool size based on PostgreSQL capacity (maxconnections = (cores * 2) + diskspindles). Deploy a proxy pooler (PgBouncer) between Node instances and the database to prevent overwhelming the DB during autoscaling bursts.

54
SeniorCode#Kubernetes

The Outbox Pattern in Node.js.

Write business state mutations and domain event payloads into an outbox database table within the same atomic database transaction. A separate background worker tails the outbox table and publishes events to RabbitMQ or Kafka.

55
Most AskedSeniorCode#Kubernetes#System Design

Cache-Aside pattern with Redis in Node.js.

App checks Redis first; if key is found, returns cached JSON immediately; otherwise fetches from DB, caches in Redis with TTL, and returns.

56
SeniorCode#Kubernetes#HTTP & REST APIs

Health Check Endpoints: Liveness vs Readiness.

/healthz/liveness: Checks if the Node.js process is alive and its Event Loop is unblocked • /healthz/readiness: Checks if the application can accept user traffic (verifies database and Redis connectivity).

57
SeniorCode#Kubernetes

Structured Logging with Pino & OpenTelemetry.

Use Pino for fast JSON logging (asynchronously writes logs to stdout without blocking main thread). Export OpenTelemetry metrics and distributed spans to collectors like Jaeger or Datadog.

58
SeniorCode#Kubernetes

Zero-Downtime Deployments (Rolling vs Blue-Green).

Rolling Update: Kubernetes updates pods incrementally, waiting for readiness probes before terminating older pods • Blue-Green: Provisions an entirely new green environment, verifies health, and switches traffic instantly at the load balancer level.

59
SeniorCode#Kubernetes

Node.js Event-Driven I/O vs Multi-Threaded Runtimes (Java/Go).

Node.js uses a single event loop thread with non-blocking I/O, consuming ~30MB RAM for 10,000 idle connections. Java traditionally allocates 1MB stack per thread, consuming gigabytes of RAM. Go uses lightweight user-space goroutines (~2KB stack) for multi-threaded concurrency.

60
SeniorCode#Kubernetes

Modern Alternative Runtimes: Deno and Bun.

Bun: Built in Zig with JavaScriptCore engine • Deno: Built in Rust with V8. Emphasizes secure-by-default sandbox permissions, Web standard APIs, built-in tooling, and native TypeScript compilation.