Full Stack with Node.js Interview Questions for 5 Years Experience
40 questions with answers for candidates with 5 years of experience — 30 medium, 10 hard.
What interviewers expect: 5 years experience
At five years, the focus shifts to system design, architecture and leadership. Expect questions on microservices, event-driven design with Kafka or queues, database scaling, caching strategies, observability, incident handling and zero-downtime deployments. You should discuss systems you designed, their scale in requests per second or data size, failures you handled and how you mentored juniors and improved team practices.
This set is weighted towards REST API Design (7), Deployment, Scaling and Performance (7), Authentication and Security (7), Node.js Core and Event Loop (5).
System design at scale Microservices and events Observability and incidents Mentoring
Solved at this levelStart 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?
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
How do you manage database schema migrations in a Node.js project?
Use a migration tool such as Prisma Migrate, Knex, Sequelize CLI or TypeORM migrations, and commit migration files to Git. Each migration has up and ideally down steps and runs in CI and before deployment. For zero downtime, use expand and contract: add new columns first, deploy code that writes both, backfill, switch reads, then drop old columns in a later release.
REST exposes multiple endpoints with fixed response shapes, uses HTTP caching easily and is simple to reason about. GraphQL exposes one endpoint where clients query exactly the fields they need, reducing over-fetching and multiple round trips, which helps mobile apps. GraphQL adds complexity: N+1 query risks needing DataLoader, harder caching, query cost limits and schema governance.
04
How do you design an API that needs to handle 50,000 requests per second for reading product details?
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.
05
Tell me about an API you designed that you are proud of.
Situation: our support team used spreadsheets to track refunds. Task: I designed a refund API used by the admin panel and payment service. Action: I wrote the OpenAPI spec first, reviewed it with frontend and finance, added idempotency keys, clear error codes and pagination, and wrote contract tests. Result: integration took two days instead of a week, and refund errors dropped sharply.
06
How would you test code that depends on the current time, like an expiring coupon?
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.
07
How do you design a consistent error response format for an API?
Use one structure everywhere, for example { "error": { "code": "VALIDATION_FAILED", "message": "Email is invalid", "details": [{ "field": "email" }], "requestId": "abc123" } }. Many teams follow RFC 9457 Problem Details with type, title, status and detail. Use machine-readable codes for clients, human messages for display, and never leak stack traces or SQL errors.
08
Describe how you would mentor a junior developer who writes no tests.
I would start by understanding why: lack of time, knowledge or examples. Then I pair with them on one feature, writing a test first for a real bug so they see the value. I share a small template for service and route tests, review their tests kindly in pull requests and celebrate when a test catches a regression. Over a few sprints, testing becomes a habit.
09
npm audit reports a critical vulnerability in a dependency of a dependency. What do you do?
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.
10
How do you use a message queue to process background jobs in Node.js?
Start a disposable database for the test run, using Docker Compose services in CI, Testcontainers from the test code, or mongodb-memory-server for MongoDB. Run migrations before tests, seed minimal data per test, and clean tables between tests or wrap each test in a rolled-back transaction. Use a separate DATABASE_URL so tests can never touch production data.
12
When would you use Kafka instead of a Redis-based queue like BullMQ?
BullMQ suits task queues inside one application: emails, reports, retries and scheduled jobs. Kafka is a distributed, durable event log for high-throughput streaming, where many consumer groups read the same events independently and can replay history, such as order events consumed by analytics, notifications and inventory. Kafka adds operational complexity, so use it when you need event streaming at scale.
13
How do access tokens and refresh tokens work together?
The access token is short-lived, around 5 to 15 minutes, and sent with each API request. The refresh token is long-lived, stored securely in an HttpOnly cookie, and used only at a refresh endpoint to get a new access token. Rotate refresh tokens on every use and store their hashes server-side, so a stolen or reused token can be detected and the session revoked.
14
Explain the Node.js event loop and its main phases.
The event loop lets Node.js run asynchronous callbacks on a single thread. Each iteration passes through phases: timers (setTimeout, setInterval), pending callbacks, poll (waits for and runs I/O callbacks), check (setImmediate), and close callbacks. Between phases Node drains the process.nextTick queue and the promise microtask queue. Understanding phases explains why setImmediate runs before a 0 ms timer inside an I/O callback.
15
How would you add OTP-based login for an Indian mobile app?
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.
16
How do you implement rate limiting on a login endpoint?
The OWASP Top 10 lists the most critical web application security risks. For Node APIs the most relevant are broken access control, injection, cryptographic failures, security misconfiguration, vulnerable and outdated components, authentication failures and server-side request forgery. OWASP also publishes an API Security Top 10, which highlights broken object level authorisation, where users access others' data by changing an ID.
Use multer for multipart/form-data. Configure limits for file size and count, filter allowed MIME types and extensions, and store files with generated names, not user-supplied names. For production, stream uploads directly to object storage such as S3 using presigned URLs so files do not pass through or fill the server disk. Scan files and never execute uploaded content.
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.
21
How would you migrate a monolithic Node.js app to microservices?
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.
22
Should you use serverless functions like AWS Lambda for a Node.js API?
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.
23
What is backpressure in streams and how does pipeline handle it?
Backpressure happens when a readable source produces data faster than the writable destination can consume it, causing memory to grow. write() returns false when the internal buffer exceeds highWaterMark, and the producer should pause until the drain event. stream.pipeline and pipe handle this automatically, and pipeline also forwards errors and destroys all streams on failure, which pipe does not.
24
What is contract testing and why is it useful for microservices?
Contract testing verifies that a provider API and its consumers agree on request and response formats without running the whole system. With Pact, the consumer writes expectations that become a contract, and the provider runs them in its own CI. It catches breaking changes like a renamed field before deployment, and is faster and less flaky than full end-to-end environments.
25
A security audit finds that users can see other users' orders by changing the order ID in the URL. How do you fix it?
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.
26
Tell me about a time you found a security issue in code and how you handled it.
Situation: during code review I noticed an admin export route that only hid the button in the frontend. Task: make sure no regular user could call it. Action: I reproduced it with a normal user token, reported it privately to my lead, added role middleware and tests, and checked similar routes. Result: we fixed four endpoints before release and added an authorisation checklist to pull requests.
27
Tell me about a time a database change caused an issue and what you learned.
Situation: I added a NOT NULL column with a default to a large MySQL table during business hours. Task: the migration locked the table and checkout slowed down. Action: I rolled back, rewrote it as add nullable column, backfill in batches, then add the constraint, and ran it at low traffic after testing on a production-size copy. Result: no downtime, and we added a migration review checklist.
28
Compare Prisma, Sequelize and TypeORM for SQL databases in Node.js.
Prisma uses a schema file to generate a fully typed client and has excellent TypeScript support and migrations, though complex raw SQL needs escape hatches. Sequelize is mature, promise-based and widely used in older JavaScript projects. TypeORM uses decorators and entity classes, familiar to Java and NestJS developers. Drizzle is a newer lightweight, SQL-like typed option. Pick based on TypeScript use and team familiarity.
29
How does HTTP caching with ETag and Cache-Control work for APIs?
Cache-Control tells clients and CDNs how long a response is fresh, for example public, max-age=300, or private, no-store for user data. An ETag is a hash of the response; the client sends it back in If-None-Match, and if nothing changed the server returns 304 Not Modified with no body. Express generates weak ETags automatically for res.send responses.
30
You need to choose a database for a food delivery app's orders, live rider locations and menus. What would you pick?
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.
31
How do you serve a React build and an API from the same Express server?
const path = require('path');
app.use('/api', apiRouter);
app.use(express.static(path.join(__dirname, 'client/dist'), { maxAge: '1y' }));
// SPA fallback for client-side routes
app.get(/^\/(?!api).*/, (req, res) => {
res.sendFile(path.join(__dirname, 'client/dist/index.html'));
});
// Register API routes first so they are not caught by the fallback.
32
How do you implement and secure webhooks that your API sends to customers?
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.
33
Your service calls three microservices and fails completely if one is down. How would you make it more resilient?
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.
34
How do you implement real-time features like live order tracking in Node.js?
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.
35
Is Node.js single-threaded? Explain the role of libuv.
Your JavaScript runs on a single main thread, but Node.js itself is not purely single-threaded. libuv, the C library under Node, provides the event loop and a thread pool (default 4 threads, set with UV_THREADPOOL_SIZE) used for file system work, DNS lookups, crypto and zlib. Network I/O uses OS async mechanisms like epoll or IOCP instead of threads.
I use a layered structure: routes define endpoints, controllers handle HTTP details, services hold business logic, and repositories or models talk to the database. Add middlewares, validators, config and utils folders, and group by feature, for example modules/orders, once the app grows. This keeps controllers thin, makes services unit-testable and avoids business rules leaking into routes.
37
How do you implement filtering and sorting safely from query parameters?
Inside an async function they behave the same: throw new Error() causes the returned promise to reject with that error. Outside async functions, a throw inside a plain callback such as setTimeout is not caught by promise handlers and becomes an uncaught exception. Always reject with Error objects, not strings, so you keep a stack trace.
39
How do you read a large file efficiently in Node.js?
const fs = require('fs');
const readline = require('readline');
async function countErrors(path) {
const rl = readline.createInterface({
input: fs.createReadStream(path),
crlfDelay: Infinity
});
let count = 0;
for await (const line of rl) {
if (line.includes('ERROR')) count++;
}
return count;
}
// Streams line by line, so a 5 GB log uses little memory.
40
How do you achieve zero-downtime deployments for a Node.js service?
Use rolling or blue-green deployments so new instances start and pass readiness checks before old ones are removed. Implement graceful shutdown on SIGTERM so in-flight requests finish. Keep database migrations backward compatible using expand and contract. Use feature flags for risky changes and have automated rollback on error rate spikes. Canary releases send a small share of traffic first.
Frequently asked questions
What is asked in Full Stack with Node.js interviews for 5 years of experience?
At five years, the focus shifts to system design, architecture and leadership. Expect questions on microservices, event-driven design with Kafka or queues, database scaling, caching strategies, observability, incident handling and zero-downtime deployments. You should discuss systems you designed, their scale in requests per second or data size, failures you handled and how you mentored juniors and improved team practices.
How many questions should I practise before a Full Stack with Node.js interview?
Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.
Which topics matter most for 5 years of experience?
Focus first on System design at scale, Microservices and events, Observability and incidents, Mentoring.