Node.js 22 • TypeScript 5 • Express • NestJS

Node.js 22, TypeScript, Express & NestJS Backend Interview Questions & Answers (2026)

Master startup & enterprise Node.js backend interviews across India — covering V8/libuv Event Loop mechanics, Streams backpressure, NestJS Dependency Injection, Prisma/PostgreSQL + MongoDB indexing, Redis BullMQ, and FinTech ledger system design.

Razorpay PhonePe Meesho Swiggy Paytm TCS Infosys Cognizant
← All Interview Question Hubs
Freshers Node.js Event Loop Q1. Explain the phases of the Node.js Event Loop and the exact difference between process.nextTick() and setImmediate().
libuv cycles through 6 phases: Timers (setTimeout/setInterval) → Pending Callbacks → Idle/Prepare → Poll (incoming I/O) → Check (setImmediate) → Close Callbacks. process.nextTick() is NOT a phase — its queue drains completely right after the current JS operation before the loop even moves to the next phase (so recursive nextTick starves I/O!). setImmediate() runs in the Check phase immediately after Poll.
Freshers libuv Threadpool Q2. Is Node.js completely single-threaded? What uses the libuv thread pool?
Your JavaScript executes on one main thread, while libuv maintains a background C++ worker threadpool (default UV_THREADPOOL_SIZE=4, tunable up to 1024). Network sockets use OS async primitives (epoll/kqueue/IOCP) without consuming pool threads, whereas fs file I/O, crypto (pbkdf2/scrypt), zlib compression, and dns.lookup() DO use the threadpool and can bottleneck if overloaded.
Freshers Streams & Backpressure Q3. Why should you use Node.js Streams with stream.pipeline() instead of fs.readFile() for large files?
fs.readFile() buffers the entire file into V8 heap RAM, crashing the process on large uploads/exports. Streams process chunks incrementally in O(1) memory (~64 KB highWaterMark). Always use stream.pipeline() instead of raw .pipe() because pipeline automatically handles Backpressure (pausing fast readers when slow writers lag) and cleans up/destroys all streams properly on errors without descriptor leaks.
Freshers Express Middleware Q4. How does Express error-handling middleware work and why must it declare 4 parameters?
Express identifies error-handling middleware strictly by function arity of 4: (err, req, res, next). Passing any argument to next(err) skips all remaining normal route handlers and jumps straight to the error middleware. In Express 4, wrap async handlers (or use Express 5 native promise rejection handling) so rejected promises never become unhandledRejection crashes.
Freshers TypeScript Backend Q5. Why does TypeScript alone NOT validate incoming HTTP request payloads at runtime?
TypeScript types are erased completely during compilation to JavaScript — at runtime req.body is untrusted JSON from the network. Always combine TypeScript with runtime schema validators like Zod or NestJS class-validator + ValidationPipe (with whitelist: true and forbidNonWhitelisted: true) to block mass-assignment and malformed input attacks.
Experienced NestJS Architecture Q6. What is the exact request lifecycle order in NestJS (Middleware, Guards, Interceptors, Pipes, Filters)?
An incoming request flows in strict order: (1) Middleware → (2) Guards (auth/RBAC authorization) → (3) Pre-controller Interceptors (logging/cache/timing) → (4) Pipes (DTO validation & transformation) → (5) Route Handler → (6) Post-controller Interceptors (response shaping) → (7) Exception Filters (if any error occurred at any step).
Experienced MongoDB Indexing Q7. Explain the MongoDB ESR (Equality, Sort, Range) index rule with an example.
When building compound B-Tree indexes in MongoDB, order fields by: (1) Equality match fields first (e.g., status: "ACTIVE"), (2) Sort fields next (createdAt: -1) so results return pre-sorted without expensive in-memory blocking sorts, and (3) Range filters last (price: { $gte: 500 }). Verify with .explain("executionStats") that totalKeysExamined ≈ nReturned and zero COLLSCAN occurs.
Experienced PostgreSQL & Prisma Q8. How do you handle concurrent wallet/inventory updates safely in Node.js + PostgreSQL + Prisma?
Wrap the balance check and debit inside an interactive prisma.$transaction() using either atomic conditional SQL updates (UPDATE wallets SET balance = balance - $1 WHERE id = $2 AND balance >= $1) or row-level locks (SELECT ... FOR UPDATE) with SERIALIZABLE/READ COMMITTED retry logic. Never compute balance in JS memory and write it back unprotected — two parallel requests will double-spend!
Experienced Scaling CPU Work Q9. Compare Node.js Cluster / PM2 vs Worker Threads for scaling production backends.
Cluster / PM2 spawns multiple independent OS processes sharing a single listening port (or Kubernetes pods behind a load balancer) — ideal for utilizing all CPU cores for HTTP I/O throughput and zero-downtime graceful reloads. Worker Threads run parallel JS V8 isolates inside ONE process sharing memory (SharedArrayBuffer) — ideal for offloading isolated CPU-heavy tasks like PDF generation, image processing, or cryptographic hashing without blocking the HTTP event loop.
Experienced Queues & Reliability Q10. Why should you use BullMQ (Redis) or Kafka instead of firing unawaited Promises inside an Express/NestJS handler?
Unawaited background promises vanish silently if a container restarts, crash the process on unhandled errors, and overwhelm downstream SMTP/payment APIs during spikes. BullMQ persists jobs in Redis with concurrency caps, exponential backoff retries, delayed scheduling, dead-letter failed queues, and graceful shutdown draining.
System Design FinTech Ledger Design Q11. How do you design a double-entry UPI/Wallet Ledger in Node.js + PostgreSQL avoiding floating-point bugs?
Store all monetary amounts strictly as 64-bit integer paise (BIGINT, never JS float/double where 0.1 + 0.2 !== 0.3!). Record immutable append-only ledger_entries (debit row + credit row summing to 0 per transaction_id) with a UNIQUE idempotency_key per transfer, and compute/update cached account balances atomically inside the same ACID DB transaction.
System Design Real-Time Socket.IO Scale Q12. How do you horizontally scale Socket.IO WebSockets across 10 Node.js server instances?
Configure sticky sessions at Nginx/ALB for initial HTTP long-polling handshake upgrade, and attach the official @socket.io/redis-adapter (or Redis Streams adapter) so room broadcasts and user-targeted events published on Node instance #1 fan out immediately across all 10 instances without in-memory state fragmentation.
System Design Graceful Shutdown Q13. How do you implement zero-downtime graceful shutdown in a Dockerized Node.js / NestJS container?
Listen for SIGTERM/SIGINT: (1) mark /healthz readiness probe unhealthy so Nginx/ALB stops routing new traffic, (2) call server.close() to finish in-flight HTTP requests within a timeout, (3) pause BullMQ/Kafka consumers and await active jobs, (4) close Prisma/PostgreSQL, MongoDB, and Redis clients cleanly, then exit(0).
System Design Memory Leak Forensics Q14. How do you diagnose a V8 heap memory leak or Event Loop Lag spike in production Node.js?
Monitor perf_hooks monitorEventLoopDelay() (P99 event loop lag) and V8 heapUsed/external metrics via OpenTelemetry/Prometheus. Capture two V8 Heap Snapshots (.heapsnapshot) spaced 10 minutes apart and inspect Retainers/Comparison view in Chrome DevTools — common leaks include unremoved EventEmitter listeners, global caches without LRU eviction, and closures capturing large req/res buffers.
System Design Microservices Communication Q15. When should Node.js microservices communicate via REST vs gRPC vs Kafka/RabbitMQ?
Use REST/JSON for public/browser/partner-facing external APIs. Use gRPC (Protobuf over HTTP/2) for low-latency, strongly-typed synchronous internal service-to-service calls. Use Kafka or RabbitMQ for asynchronous decoupled event workflows (order placed → inventory, email, analytics) so downstream failures never block the checkout API.
Freshers Node.js Event Loop Puzzle Q16. Predict the exact console output order of sync, process.nextTick, Promise.then, setTimeout(0), and setImmediate.
Synchronous code runs first, followed immediately by the nextTick queue (higher priority than Promise microtasks!), then Promise microtasks, and finally macrotasks (Timers vs Check; inside an I/O callback, setImmediate ALWAYS fires before setTimeout(0)).
Classic Node.js Event Loop Execution Order Puzzlejavascript
console.log('1: sync');
setTimeout(() => console.log('5: timeout'), 0);
Promise.resolve().then(() => console.log('3: promise'));
process.nextTick(() => console.log('2: nextTick'));
console.log('1b: sync end');
// Output: 1: sync -> 1b: sync end -> 2: nextTick -> 3: promise -> 5: timeout
Freshers Streams & Backpressure Q17. Show how stream.pipeline() safely compresses and streams a 2 GB file in Node.js with automatic error cleanup.
Using node:stream/promises pipeline() automatically manages backpressure between fast disk reads and slower gzip/socket writes and destroys every stream on error without file-descriptor leaks.
Memory-Safe Node.js 22 Stream Pipelinetypescript
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
import { pipeline } from 'node:stream/promises';

await pipeline(
  createReadStream('/tmp/export.csv'),
  createGzip(),
  createWriteStream('/tmp/export.csv.gz')
);
Freshers Node.js Observability Q18. How does AsyncLocalStorage propagate Request Correlation IDs cleanly across async calls in Express/NestJS?
AsyncLocalStorage (from node:async_hooks) attaches an isolated request context store (traceId, userId, tenantId) to the async execution tree so loggers and DB helpers automatically log the correlation ID without threading req through every service parameter.
Experienced PostgreSQL & Prisma Q19. Show an atomic double-spend-proof wallet transfer inside Prisma + PostgreSQL.
Use an atomic conditional UPDATE inside prisma.$transaction() with integer paise so two concurrent debits can never drive a balance negative.
Race-Free Atomic Wallet Debit in Prismatypescript
await prisma.$transaction(async (tx) => {
  const debited = await tx.$executeRaw`
    UPDATE wallets SET balance_paise = balance_paise - ${amountPaise}
    WHERE id = ${walletId} AND balance_paise >= ${amountPaise}
  `;
  if (debited !== 1) throw new ConflictException('Insufficient wallet balance');
  await tx.ledgerEntry.create({ data: { walletId, amountPaise: -amountPaise, idempotencyKey } });
});
Experienced NestJS Architecture Q20. Show a reusable NestJS ValidationPipe + DTO setup that blocks mass-assignment attacks.
Enabling whitelist: true and forbidNonWhitelisted: true strips or rejects unexpected fields (like role: "admin") before payloads ever reach your service or Prisma create call.
Hardened Global NestJS ValidationPipetypescript
app.useGlobalPipes(new ValidationPipe({
  whitelist: true,
  forbidNonWhitelisted: true,
  transform: true,
}));
Experienced MongoDB Aggregation Q21. How do you optimize a slow MongoDB Aggregation Pipeline using $match, $project, and $lookup?
Always place $match and $sort at the very beginning of the pipeline so MongoDB uses B-Tree indexes before documents enter memory, project only required fields early to cut BSON payload size, index foreign fields used in $lookup, and avoid $unwind on huge unbounded arrays.
Experienced GraphQL N+1 & DataLoader Q22. How does the DataLoader pattern eliminate N+1 database queries in a Node.js / NestJS GraphQL API?
A per-request DataLoader collects all individual load(userId) calls triggered within the same event-loop tick and batches them into a single SELECT * FROM users WHERE id IN (...) query, caching results strictly for the lifetime of that single HTTP request to prevent cross-user leakage.
System Design Redis Atomicity Q23. Show an atomic Redis Sliding-Window / Fixed-Window Rate Limiter Lua script invoked from Node.js.
Running INCR + EXPIRE inside a single Redis Lua script eliminates the race condition where a process crashes between INCR and EXPIRE leaving a permanent key without TTL.
Atomic Redis Lua Rate-Limit Scriptlua
local current = redis.call('INCR', KEYS[1])
if current == 1 then
  redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
end
return current
System Design Graceful Shutdown Q24. Show a zero-downtime SIGTERM shutdown handler for an Express/Node.js Kubernetes pod.
Flip readiness false first, stop accepting new sockets via server.close(), drain queues and DB pools, and enforce a bounded hard-exit timer so pods never hang indefinitely.
Zero-Downtime Node.js SIGTERM Handlertypescript
process.on('SIGTERM', async () => {
  isReady = false;
  server.close(async () => {
    await Promise.allSettled([bullWorker.close(), prisma.$disconnect(), redis.quit()]);
    process.exit(0);
  });
  setTimeout(() => process.exit(1), 15_000).unref();
});
System Design Prisma vs Connection Pools Q25. Why can deploying 30 serverless/containerized Node.js instances with Prisma exhaust PostgreSQL max_connections?
Every Node.js container opens its own Prisma connection pool (e.g., 10–20 connections × 30 pods = 600 connections). Tune connection_limit conservatively per container and place PgBouncer (Transaction mode, ?pgbouncer=true) in front of PostgreSQL to multiplex connections cleanly.