Skip to content

Scenario-Based Full Stack with Node.js Interview Questions

43 questions with answers. Real-work situations — broken dashboards, flaky tests, unclear requirements — and how a strong node.js developer would handle them.

How to approach these questions

Clarify the situation, list likely causes, say how you would check each one, then give the fix and how you would stop it happening again.

Solved — scenario-basedStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Your Node.js API becomes unresponsive when one endpoint generates a large PDF report. What is happening and how do you fix it?

Save to ▾
Show answer
The PDF generation is CPU-bound and blocks the single event loop, so every other request waits. Fixes: move the work to a worker_threads pool such as Piscina, or push it to a background job queue like BullMQ with Redis and return a job ID that the client polls. Also break large loops into chunks and measure event loop lag to confirm the fix.
02

Memory usage of a Node.js service grows steadily until the pod restarts. How would you find the leak?

Save to ▾
Show answer
First confirm with metrics that heap used keeps rising under steady traffic. Take heap snapshots with --inspect and Chrome DevTools or heapdump at intervals and compare them to find objects whose count keeps growing. Common causes are global caches without limits, event listeners added per request, closures holding large objects and unclosed timers. Fix, then load test with autocannon to verify heap stabilises.
03

A teammate uses fs.readFileSync inside an Express route. What is the problem and what would you suggest?

Save to ▾
Show answer
Synchronous file calls block the event loop for the whole read, so under load every request queues behind disk I/O and latency spikes. In a route, use fs.promises.readFile with await, or stream the file with fs.createReadStream and pipe it to the response. Sync calls are acceptable only at startup, for example reading a config file once before the server listens.
04

How would you handle uncaughtException and unhandledRejection in production?

Save to ▾
Show answer
Log both with full stack traces and context, then exit the process after flushing logs, because state may be corrupted. A process manager like PM2, systemd or Kubernetes restarts it. Never use uncaughtException to keep running as if nothing happened. Since Node 15, unhandled rejections crash the process by default, so every promise chain should have proper error handling.
05

You need to choose between Node.js and Java for a new high-traffic service. How would you decide?

Save to ▾
Show answer
I would look at the workload and team. Node.js fits I/O-heavy services like API gateways, chat, notifications and BFF layers, with fast development and shared JavaScript skills. Java fits CPU-heavy processing, complex multi-threaded logic and teams with strong JVM experience. I would benchmark a prototype for the real access pattern and consider hiring, libraries and existing platform tooling before deciding.
06

A dashboard endpoint makes five independent database queries one after another and takes 1.5 seconds. How would you speed it up?

Save to ▾
Show answer
Because the queries are independent, run them concurrently with Promise.all so total time is close to the slowest query instead of the sum. Check that the database connection pool is large enough to serve them in parallel. Then add indexes for slow queries, cache rarely changing parts in Redis, and use Promise.allSettled if the page can render with some widgets missing.
07

Two simultaneous requests both read a wallet balance, deduct money and save it, causing a wrong balance. How do you fix this race condition?

Save to ▾
Show answer
Async code interleaves between awaits, so read-modify-write is unsafe. Make the update atomic in the database: use an UPDATE with balance = balance - amount WHERE balance >= amount, or MongoDB $inc with a filter. Alternatives are row-level locks with SELECT FOR UPDATE inside a transaction, optimistic locking with a version column, or a Redis distributed lock for cross-service work.
08

Your service calls three microservices and fails completely if one is down. How would you make it more resilient?

Save to ▾
Show answer
Use Promise.allSettled so one failure does not reject everything, and return partial data with clear flags. Add timeouts to every call, retries with backoff for transient errors and a circuit breaker such as opossum to stop hammering a failing service. Provide fallbacks like cached values and log failures with correlation IDs so the issue can be traced.
09

A scheduled job processes orders with setInterval every minute, but sometimes runs overlap and duplicate emails are sent. How do you fix it?

Save to ▾
Show answer
setInterval fires regardless of whether the previous async run finished. Use a recursive setTimeout that schedules the next run only after the current one completes, or keep an isRunning flag. If several instances run, use a distributed lock in Redis or a job queue like BullMQ with unique job IDs. Also make email sending idempotent by recording sent message IDs.
10

What causes the error 'Cannot set headers after they are sent to the client'?

Save to ▾
Show answer
It happens when code tries to send a second response for the same request, for example calling res.json in a callback and then again later, or forgetting return after sending an error response, or calling next() after responding. Fix it by returning immediately after each res.send or res.json, and making sure each code path sends exactly one response.
11

After adding a new middleware, all routes return 404 or hang. How do you debug it?

Save to ▾
Show answer
A hang usually means the middleware never calls next() or sends a response on some path. A 404 often means it was mounted with a wrong path or registered after routes. I check order of app.use calls, add logging at the start and end of the middleware, verify every branch calls next or responds, and check async code passes errors to next.
12

Your Express API needs to support multiple client apps with different rate limits. How would you design it?

Save to ▾
Show answer
Identify the client through an API key or OAuth client ID in authentication middleware and attach the plan to req. Then use express-rate-limit or a custom limiter with a Redis store, keyed by client ID, with limits read from the plan. Return 429 with Retry-After and RateLimit headers. Redis keeps limits consistent across multiple server instances.
13

A client reports that a large JSON POST request fails with 413 Payload Too Large. What do you do?

Save to ▾
Show answer
express.json() has a default body limit of 100 KB, so bigger payloads are rejected with 413. If the size is legitimate, raise it for that route only, for example express.json({ limit: '2mb' }), and check any proxy limit such as Nginx client_max_body_size. For very large data, switch to file upload to object storage or pagination instead of huge JSON bodies.
14

How do you design Express middleware that checks user roles for a route?

Save to ▾
Show answer
Create a factory: const authorize = (...roles) => (req, res, next) => roles.includes(req.user?.role) ? next() : res.status(403).json({ error: 'Forbidden' }). Use it after authentication, for example router.delete('/:id', authenticate, authorize('admin'), handler). Keep roles and permissions in config or the database, and for complex rules move to permission-based checks or a policy library.
15

A mobile app team complains your API returns too much data and is slow on 4G. What would you change?

Save to ▾
Show answer
Add field selection like ?fields=id,name,price, smaller list representations with details on a separate endpoint, pagination with sensible limits and gzip or Brotli compression. Support ETag and Cache-Control so unchanged data returns 304. If many screens need combined data, consider a Backend-for-Frontend layer or GraphQL tailored to the mobile app.
16

You must change a response field name used by many clients. How do you do it without breaking them?

Save to ▾
Show answer
Treat it as a breaking change. Option one: add the new field alongside the old one, mark the old field deprecated in docs and response headers, track usage through logs and remove it after clients migrate. Option two: release it in /v2 and keep /v1 for a deprecation window. Communicate timelines clearly and add contract tests for both.
17

How would you design an API for a long-running task such as exporting a 1 GB report?

Save to ▾
Show answer
Do not keep the HTTP request open. POST /exports creates a job, pushes it to a queue and returns 202 Accepted with a job ID and status URL. Clients poll GET /exports/:id or receive a webhook or WebSocket event. A worker generates the file, uploads it to object storage, and the status endpoint returns a short-lived signed download URL.
18

How do you implement and secure webhooks that your API sends to customers?

Save to ▾
Show answer
Send a POST with a JSON event, a unique event ID and timestamp. Sign the body with HMAC-SHA256 using a per-customer secret and include it in a header, so receivers verify authenticity and reject old timestamps to stop replays. Retry failures with exponential backoff, log delivery attempts and make events idempotent so receivers can safely handle duplicates.
19

A security audit finds that users can see other users' orders by changing the order ID in the URL. How do you fix it?

Save to ▾
Show answer
This is broken object level authorisation. Every query must be scoped to the authenticated user: Order.findOne({ _id: id, userId: req.user.id }), returning 404 if not found. Put this check in a shared service or middleware so no route can skip it, add tests that try other users' IDs, and consider non-guessable IDs like UUIDs as defence in depth, not as the fix.
20

Your JWT secret has leaked. What steps do you take?

Save to ▾
Show answer
Treat it as an incident. Generate a new secret and deploy it immediately, which invalidates all existing tokens and forces re-login. Revoke refresh tokens in the database, check logs for suspicious tokens or admin actions, and find how it leaked, for example a committed .env or logs. Move to a secrets manager, consider asymmetric RS256 keys with key IDs to rotate safely, and document the incident.
21

How would you add OTP-based login for an Indian mobile app?

Save to ▾
Show answer
Generate a random 6-digit OTP with crypto.randomInt, store only its hash in Redis with a 5-minute TTL and an attempt counter, and send it through an SMS provider on a DLT-registered template. Verify with a timing-safe compare, limit to about 3 to 5 attempts and rate limit sends per number and IP. On success, issue access and refresh tokens and delete the OTP.
22

npm audit reports a critical vulnerability in a dependency of a dependency. What do you do?

Save to ▾
Show answer
First check whether the vulnerable code path is actually reachable in our usage and read the advisory. Try npm audit fix or updating the parent package to a version that pulls a patched sub-dependency. If none exists, use the overrides field in package.json to force a safe version and run tests. Track it in a ticket and enable Dependabot or Renovate for ongoing updates.
23

How would you design authentication for a system of ten microservices?

Save to ▾
Show answer
Centralise login in an identity service or provider such as Keycloak, Auth0 or Cognito that issues short-lived JWTs signed with RS256. The API gateway validates tokens, and each service verifies the signature using the public keys from a JWKS endpoint, so no shared secret is needed. Use service-to-service tokens or mTLS for internal calls and keep authorisation checks inside each service.
24

An API listing orders became slow after the table reached 50 million rows. How do you investigate?

Save to ▾
Show answer
Run EXPLAIN ANALYZE on the slow query to see whether it does a sequential scan or a costly sort. Add a composite index matching the filter and sort, for example (user_id, created_at DESC). Replace OFFSET pagination with cursor pagination, select only needed columns, and consider partitioning by date and archiving old rows. Monitor slow query logs after the change.
25

Users report seeing stale prices after an update because of caching. How do you solve it?

Save to ▾
Show answer
Invalidate or update the cache key in the same code path that updates the price, preferably after the database commit. Use reasonable TTLs as a safety net, and version keys if needed. If several services update prices, publish a price-changed event and have consumers delete the cache. For CDN-cached responses, purge the relevant URLs or use short max-age with stale-while-revalidate.
26

Your app gets 'too many connections' errors from PostgreSQL after scaling to 20 pods. What would you do?

Save to ▾
Show answer
Each pod opens its own pool, so 20 pods with max 20 connections need 400, beyond the database limit. Reduce the per-pod pool size, put PgBouncer or RDS Proxy in front of the database for transaction pooling, and make sure connections are released, for example client.release() in finally blocks. Also check for long-running idle transactions holding connections.
27

You need to choose a database for a food delivery app's orders, live rider locations and menus. What would you pick?

Save to ▾
Show answer
Orders and payments need strong consistency and transactions, so PostgreSQL or MySQL fits. Live rider locations change every few seconds and need geo queries, so Redis with geospatial commands works well for the hot data, with history stored elsewhere. Menus are read-heavy and nested, so a document store like MongoDB or Postgres JSONB plus caching suits them.
28

A Mongoose query returns large documents and the API is slow. What optimisations can you apply?

Save to ▾
Show answer
Use .select() to fetch only needed fields, and .lean() to return plain objects instead of full Mongoose documents, which cuts memory and CPU. Make sure the filter and sort use an index, checked with explain. Paginate results, avoid populating deep references, and cache frequently read data. For large exports, use a cursor with for await instead of loading everything.
29

A test passes locally but fails randomly in CI. How do you approach this flaky test?

Save to ▾
Show answer
Run it repeatedly to reproduce, then look for shared state between tests, missing awaits, reliance on test order, real timers, current date or time zones, random data and network calls. Fix by isolating data per test, using fake timers, freezing dates, mocking external calls and awaiting all promises. Quarantine the test only temporarily with a ticket, never delete it silently.
30

Production shows intermittent 502 errors from the load balancer but your app logs show nothing. How do you investigate?

Save to ▾
Show answer
A 502 means the load balancer got a bad or no response from the app. Check whether pods restarted or crashed through OOM kills, health check failures and deployment times. A common Node cause is keep-alive mismatch: set server.keepAliveTimeout higher than the load balancer idle timeout and headersTimeout above that. Also check event loop blocking and connection limits.
31

How would you test code that depends on the current time, like an expiring coupon?

Save to ▾
Show answer
Inject a clock function instead of calling Date.now directly, or use Jest fake timers: jest.useFakeTimers().setSystemTime(new Date('2026-01-01')). Then test before, exactly at and after expiry. Store dates in UTC and convert for display in IST, which avoids bugs near midnight. Reset timers after each test with jest.useRealTimers to avoid leaking into other tests.
32

A new developer pushes code that breaks the login API in staging. How would you prevent this in future?

Save to ▾
Show answer
Add automated checks before merge: unit and integration tests for login in the CI pipeline, branch protection requiring green builds and at least one review, linting and type checks. Add a smoke test that runs after each staging deploy and alerts on failure. Treat it as a blameless learning moment and pair with the developer to write the missing tests.
33

How do you load test a Node.js API before a big sale event?

Save to ▾
Show answer
Define targets from expected traffic, such as 5,000 requests per second with p95 under 300 ms. Write realistic scenarios in k6 or Artillery covering browse, cart and checkout, run them against a production-like environment, and ramp up gradually. Watch latency, error rates, CPU, memory, event loop lag and database metrics, then fix bottlenecks and rerun until targets are met with headroom.
34

A regex in your validation code makes the server hang on certain inputs. What is the issue?

Save to ▾
Show answer
This is likely ReDoS, regular expression denial of service. Patterns with nested quantifiers such as (a+)+ can backtrack exponentially on crafted input, blocking the event loop. Fix by simplifying the regex, limiting input length before matching, using well-tested validators like validator.js, or a linear-time engine such as re2. Add tests with long malicious strings.
35

How do you implement real-time features like live order tracking in Node.js?

Save to ▾
Show answer
Use WebSockets through Socket.IO or ws, or Server-Sent Events for one-way updates. Clients join a room per order, and when the rider location or status changes, the server emits to that room. With multiple instances, use the Socket.IO Redis adapter so events reach clients on any server, authenticate the socket on connect, and throttle location updates to save bandwidth.
36

Your API's p99 latency is high during peak hours even though CPU is only 40 percent. What could be wrong?

Save to ▾
Show answer
Low CPU with high latency suggests waiting, not computing. Check database query times and connection pool wait, slow downstream APIs, Redis latency, DNS lookups without keep-alive agents, garbage collection pauses and event loop lag from occasional heavy requests. Use distributed tracing with OpenTelemetry to see where time goes, then add indexes, caching, timeouts or more pool connections.
37

Your service is expected to get ten times normal traffic during a festive sale. How do you prepare?

Save to ▾
Show answer
Load test at above the expected peak, then fix bottlenecks. Pre-scale instances and database capacity instead of relying only on autoscaling, warm caches, and put static and catalogue responses on a CDN. Add rate limits, queue non-critical work, set timeouts and circuit breakers, prepare feature flags to switch off heavy features, and have dashboards, alerts and an on-call plan ready.
38

How would you migrate a monolithic Node.js app to microservices?

Save to ▾
Show answer
Do it gradually with the strangler fig pattern. Identify bounded contexts like auth, catalogue and payments, pick one with clear boundaries and high change rate, extract it behind an API gateway and route traffic to it. Give each service its own data, communicate through APIs and events, and invest in logging, tracing and CI first. Do not split before the monolith causes real pain.
39

How do you design an API that needs to handle 50,000 requests per second for reading product details?

Save to ▾
Show answer
Make the read path cache-heavy: CDN caching for public product pages, Redis cache for product details with high hit ratio, and database read replicas behind it. Run many stateless Node instances with autoscaling, keep responses small and compressed, and use keep-alive connections. Avoid cache stampedes with request coalescing or locks, and precompute data that is expensive to build.
40

How do you prevent a cache stampede when a popular key expires?

Save to ▾
Show answer
When a hot key expires, thousands of requests may hit the database at once. Solutions: allow only one request to rebuild the cache using a short Redis lock while others wait or serve stale data, refresh hot keys in the background before expiry, add random jitter to TTLs so keys do not expire together, and use stale-while-revalidate where slightly old data is acceptable.
41

Should you use serverless functions like AWS Lambda for a Node.js API?

Save to ▾
Show answer
Serverless suits spiky or low-traffic workloads, event processing and quick prototypes, since you pay per invocation and need no server management. Downsides are cold starts, execution time limits, connection handling with relational databases and harder local debugging. For steady high traffic or long-lived WebSocket connections, containers are usually cheaper and simpler. Many teams mix both.
42

A partner integration retries POST requests on timeouts and creates duplicate orders in your API. How would you redesign the endpoint?

Save to ▾
Show answer
Require an Idempotency-Key header on order creation and store it with a unique index alongside the created order ID and response. On a repeated key with the same payload, return the original response; with a different payload, return 409 or 422. Also add a unique business constraint such as partner order reference, respond quickly by queueing slow work, and document retry behaviour for partners.
43

After a Node.js version upgrade, a few integration tests fail with date and crypto differences. How do you handle the upgrade safely?

Save to ▾
Show answer
Read the release notes and changelog for breaking changes, such as deprecated APIs, OpenSSL updates or changed default behaviour. Run the full test suite on the new version in a CI matrix alongside the old one, fix failures one by one and check native modules rebuild correctly. Roll out to staging, then to a canary in production while watching error rates before upgrading all services.

Frequently asked questions

Why are scenario-based questions important?

They show how you think on real problems. Interviewers use them to separate people who memorised definitions from people who have done the work.

How should I answer them?

Clarify the situation, list likely causes, say how you would check each one, then give the fix and how you would stop it happening again.