Full Stack with Node.js Interview Questions for 3 Years Experience
40 questions with answers for candidates with 3 years of experience — 4 easy, 31 medium, 5 hard.
What interviewers expect: 3 years experience
Three-year candidates face deeper rounds on event loop internals, streams, memory leaks, security, database design and scaling. Expect a low-level or basic system design round, such as designing a rate limiter, notification service or URL shortener. Interviewers look for ownership of modules, code review experience and the ability to explain decisions clearly and justify the trade-offs you made.
This set is weighted towards Authentication and Security (10), Deployment, Scaling and Performance (6), Asynchronous JavaScript (6), Node.js Core and Event Loop (4).
Node internals and profiling Security and OWASP Basic system design Code ownership
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
What is the difference between process.nextTick and setImmediate?
process.nextTick queues a callback to run immediately after the current operation, before the event loop continues to any phase, even before promise microtasks. setImmediate queues a callback for the check phase of the next loop iteration. Overusing nextTick recursively can starve I/O because the loop never moves on, so setImmediate is safer for deferring heavy work.
02
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.
03
Where should a web app store tokens: localStorage or cookies?
localStorage is readable by any JavaScript on the page, so an XSS bug can steal tokens. HttpOnly, Secure, SameSite cookies cannot be read by JavaScript, which is safer for refresh tokens and session IDs. Cookies require CSRF protection, which SameSite=Lax or Strict plus CSRF tokens provide. A common pattern keeps the access token in memory and the refresh token in an HttpOnly cookie.
04
What is the built-in node:test runner and when would you use it over Jest?
Node.js ships a stable test runner in the node:test module with describe, it, mocks, coverage and watch mode, run with node --test. It needs no extra dependency and works natively with ES modules, which Jest still handles with extra configuration. Jest or Vitest offer richer snapshot testing, mocking and ecosystem. For small libraries or ESM-first services, node:test is a lightweight choice.
05
Write a centralised error handler with a custom AppError class.
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.
07
Tell me about a time you had to balance speed of delivery with technical quality.
Situation: sales needed a partner API in one week for a client launch. Task: deliver fast without creating a mess. Action: I agreed with my manager to ship the core endpoints with validation, auth and tests, and to defer caching and admin tooling, logging them as tickets with dates. Result: the partner went live on time, and we completed the deferred work in the next sprint as planned.
08
When should you embed documents versus reference them in MongoDB?
Embed when data is read together, owned by the parent and bounded in size, such as addresses inside a user or line items inside an order. Reference when the related data is large, grows without limit, is shared across many documents or changes independently, such as products referenced by orders or comments on a viral post. Remember the 16 MB document size limit.
09
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.
10
Tell me about a time you had to debug a tricky asynchronous bug.
Situation: customers occasionally received two invoices. Task: I had to find why it happened only in production. Action: I added request IDs to logs and found a forEach with async callbacks plus a retry triggering a second save before the first finished. I replaced it with for...of, added a unique index on invoice number and made the job idempotent. Result: duplicates stopped completely.
11
What is the purpose of the util.promisify function?
util.promisify converts a function that follows the Node callback convention, where the last argument is (err, result) => {}, into one that returns a promise. This lets you use async and await with older APIs. For example, const sleep = util.promisify(setTimeout) or promisify(fs.readFile). Many core modules now offer promise versions directly, such as fs/promises and dns/promises.
12
What is the N+1 query problem and how do you fix it?
N+1 happens when you run one query to fetch a list and then one extra query per item, for example loading 100 posts and then each author separately, causing 101 queries. Fix it with joins or eager loading in SQL ORMs like include in Prisma or Sequelize, populate or $lookup in MongoDB, batching with an IN query, or DataLoader in GraphQL.
13
A regex in your validation code makes the server hang on certain inputs. What is the issue?
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.
14
What is a closure and how is it used in Node.js code?
A closure is a function that remembers variables from the scope where it was created, even after that outer function has returned. In Node it is used for middleware factories like rateLimit({ max: 100 }), private counters, memoisation and module-level state. A risk is memory leaks when closures hold large objects longer than needed, for example inside long-lived event listeners.
15
Explain the difference between Promise.all, Promise.allSettled, Promise.race and Promise.any.
Promise.all resolves with all results when every promise fulfils, and rejects as soon as one rejects. Promise.allSettled waits for all and returns each status and value or reason, useful when partial failure is fine. Promise.race settles with the first promise to settle, often used for timeouts. Promise.any resolves with the first fulfilled promise and rejects only if all reject.
An idempotent operation gives the same result when repeated. For POST /payments, the client sends a unique Idempotency-Key header. The server stores the key with the request hash and response, for example in Redis or a table with a unique index. If the same key arrives again, it returns the saved response instead of charging twice. Keys expire after about 24 hours.
18
What is the difference between authentication and authorisation?
Authentication verifies who the user is, for example by checking a password, OTP or OAuth login. Authorisation decides what that verified user is allowed to do, such as whether they can delete an order or view admin reports. In an API, authentication failures return 401 and authorisation failures return 403. Both must be enforced on the server, never only in the frontend.
19
A mobile app team complains your API returns too much data and is slow on 4G. What would you change?
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.
20
Your JWT secret has leaked. What steps do you take?
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
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.
22
Why is using async callbacks inside forEach a common bug?
Array.forEach ignores the promise returned by an async callback, so it does not wait for any iteration and errors are not caught by the outer function. Code after the loop runs before the work is done. Use for...of with await for sequential processing, or map the items to promises and await Promise.all for parallel processing.
23
What are XSS and CSRF and how do you protect a Node.js app from them?
XSS injects malicious script into pages other users view; prevent it by escaping output, using templating or React auto-escaping, sanitising rich HTML with DOMPurify and setting a strong Content-Security-Policy. CSRF tricks a logged-in browser into sending unwanted requests; prevent it with SameSite cookies, CSRF tokens for cookie-based auth and checking Origin headers on state-changing requests.
24
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.
25
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.
26
How do you explain asynchronous programming to a non-technical stakeholder or junior teammate?
I use a restaurant analogy. One waiter takes an order, gives it to the kitchen and serves other tables instead of waiting at the stove; when the dish is ready, the kitchen rings a bell. Node.js works the same: it starts a database or network task, handles other requests and resumes when the result is ready. Then I show a short code example with async and await.
27
After adding a new middleware, all routes return 404 or hang. How do you debug it?
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.
28
How would you handle uncaughtException and unhandledRejection in production?
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.
29
A Mongoose query returns large documents and the API is slow. What optimisations can you apply?
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.
30
How do you use the Node.js cluster module to use all CPU cores?
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
for (let i = 0; i < os.availableParallelism(); i++) cluster.fork();
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, restarting`);
cluster.fork();
});
} else {
require('./server'); // each worker listens on the same port
}
// In Kubernetes, prefer one process per container and more replicas.
31
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.
32
What is an API gateway and what does it do in a Node.js microservice setup?
An API gateway is a single entry point in front of services. It routes requests, terminates TLS, validates tokens, applies rate limits, handles CORS, aggregates responses and collects logs and metrics. Examples are Kong, AWS API Gateway, Nginx and Envoy-based gateways. It keeps cross-cutting concerns out of each service, but must be highly available so it does not become a single point of failure.
33
What is the OWASP Top 10 and which items matter most for Node.js APIs?
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.
34
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.
35
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.
36
What is a compound index and why does field order matter?
A compound index covers multiple fields, such as { userId: 1, createdAt: -1 }. It supports queries that use a prefix of the fields, so it helps queries on userId alone or userId plus createdAt, but not createdAt alone. A good rule in MongoDB is ESR: put equality fields first, then sort fields, then range fields, to avoid in-memory sorts.
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.
38
Explain OAuth 2.0 and the Authorization Code flow with PKCE.
OAuth 2.0 lets an app access resources on a user's behalf without seeing their password, for example social login with an existing account. In Authorization Code with PKCE, the app creates a code verifier and sends its hash to the authorisation server. The user logs in and consents, the app receives a code and exchanges it plus the verifier for tokens. PKCE stops intercepted codes being reused.
39
When would you choose NestJS or Fastify over Express?
Choose Fastify when raw performance and built-in schema validation matter; it is faster than Express thanks to optimised routing and serialisation. Choose NestJS for large teams that want structure: modules, dependency injection, decorators and first-class TypeScript, similar to Spring or Angular. Express still suits small to medium services and teams that prefer flexibility and a huge middleware ecosystem.
40
A dashboard endpoint makes five independent database queries one after another and takes 1.5 seconds. How would you speed it up?
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.
Frequently asked questions
What is asked in Full Stack with Node.js interviews for 3 years of experience?
Three-year candidates face deeper rounds on event loop internals, streams, memory leaks, security, database design and scaling. Expect a low-level or basic system design round, such as designing a rate limiter, notification service or URL shortener. Interviewers look for ownership of modules, code review experience and the ability to explain decisions clearly and justify the trade-offs you made.
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 3 years of experience?
Focus first on Node internals and profiling, Security and OWASP, Basic system design, Code ownership.