Skip to content

Full Stack with Node.js Technical Round Questions & Answers

40 questions for the technical round stage — 3 easy, 29 medium, 8 hard.

About the technical round round

The technical round is the core of a Full Stack with Node.js interview: concept questions with follow-ups, a live hands-on task and a deep dive into one of your projects. Interviewers check depth, not just definitions.

Tips for the technical round round

  • Say your approach out loud before you start writing.
  • After a correct answer, expect 'why?' and 'what if?' follow-ups; go one level deeper than the question.
  • Pick one project you can explain end to end, including what you would do differently.
  • If you get stuck, explain what you would try next instead of going silent.
Solved — technical roundStart 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

How do you read a large file efficiently in Node.js?

Save to ▾
Show answer
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.
02

How do you use the Node.js cluster module to use all CPU cores?

Save to ▾
Show answer
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.
03

How does async/await work under the hood?

Save to ▾
Show answer
An async function always returns a promise. await pauses that function until the awaited promise settles, then resumes it with the value or throws the rejection, while the event loop keeps running other work. Internally it is built on promises and generator-like suspension. The code reads like synchronous code but is still non-blocking, and errors are handled with ordinary try/catch.
04

How do you implement role-based access control (RBAC) in an API?

Save to ▾
Show answer
Define roles such as admin, manager and customer, and map them to permissions like order:read or order:refund. Put the role or permissions in the token or load them per request, and check them in middleware before handlers. For ownership rules, also check resource data, for example a customer can view only orders where order.userId equals req.user.id. Test both allowed and denied paths.
05

Explain debounce and throttle and where they matter on the backend.

Save to ▾
Show answer
Debounce runs a function only after calls stop for a set time, merging bursts into one call. Throttle runs it at most once per interval. On the backend they help when batching cache invalidation, limiting webhook processing, writing metrics, or reacting to file watcher events. For API traffic you normally use a rate limiter instead, which is a server-side form of throttling.
06

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.
07

What are XSS and CSRF and how do you protect a Node.js app from them?

Save to ▾
Show answer
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.
08

Implement cursor-based pagination for a products endpoint.

Save to ▾
Show answer
router.get('/products', async (req, res) => { const limit = Math.min(Number(req.query.limit) || 20, 100); const cursor = req.query.cursor; const filter = cursor ? { _id: { $lt: cursor } } : {}; const items = await Product.find(filter) .sort({ _id: -1 }) .limit(limit + 1); const hasMore = items.length > limit; if (hasMore) items.pop(); res.json({ data: items, nextCursor: hasMore ? items[items.length - 1]._id : null }); });
09

What is SQL injection and how do you prevent it in Node.js?

Save to ▾
Show answer
SQL injection happens when user input is concatenated into a query, letting attackers change it, for example ' OR 1=1 --. Prevent it with parameterised queries, such as pool.query('SELECT * FROM users WHERE email = $1', [email]) in pg, or an ORM like Prisma or Sequelize that parameterises automatically. Also validate input and give the database user minimum privileges.
10

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.
11

What is the difference between PUT and PATCH?

Save to ▾
Show answer
PUT replaces the entire resource with the representation sent, so missing fields may be reset; it is idempotent. PATCH applies a partial update, sending only changed fields, such as { "phone": "..." }. PATCH is more efficient for large objects. With JSON Merge Patch, repeated identical PATCH requests are effectively idempotent, but operations like increment are not.
12

What is HATEOAS and is it used in real projects?

Save to ▾
Show answer
HATEOAS, Hypermedia as the Engine of Application State, means responses include links telling the client what it can do next, for example an order response with links to cancel or pay. It makes APIs more discoverable and decoupled. In practice most JSON APIs only partly use it, such as pagination links, because clients are usually built against documented endpoints.
13

Write a retry function with exponential backoff for a flaky API call.

Save to ▾
Show answer
async function retry(fn, retries = 3, baseMs = 200) { for (let attempt = 0; ; attempt++) { try { return await fn(); } catch (err) { if (attempt >= retries) throw err; const delay = baseMs * 2 ** attempt + Math.random() * 100; await new Promise((r) => setTimeout(r, delay)); } } } await retry(() => paymentClient.getStatus(id));
14

Write a simple Docker Compose file to run a Node API with MongoDB and Redis locally.

Save to ▾
Show answer
services: api: build: . ports: ['3000:3000'] environment: MONGO_URL: mongodb://mongo:27017/app REDIS_URL: redis://redis:6379 depends_on: [mongo, redis] mongo: image: mongo:7 volumes: ['mongo-data:/data/db'] redis: image: redis:7-alpine volumes: mongo-data:
15

How would you structure a large Express project?

Save to ▾
Show answer
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.
16

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.
17

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.
18

How do you enable compression and why should you be careful with it?

Save to ▾
Show answer
Use the compression middleware or, better, let Nginx or the CDN compress responses with gzip or Brotli, which reduces JSON payload size by 70 percent or more. Be careful: compressing in Node uses CPU on the event loop, small responses gain little, and already compressed files like images should be skipped. Never compress responses mixing secrets with user input over HTTPS because of BREACH-style attacks.
19

How do you find which function is using the most CPU in a Node.js service?

Save to ▾
Show answer
Reproduce the load with autocannon or k6, then profile with node --cpu-prof to generate a .cpuprofile file and open it in Chrome DevTools, or use clinic flame to get a flame graph. Wide bars show hot functions. Common culprits are JSON.stringify on huge objects, synchronous crypto, regex backtracking and heavy loops. Fix and re-measure under the same load.
20

How do you use a message queue to process background jobs in Node.js?

Save to ▾
Show answer
const { Queue, Worker } = require('bullmq'); const connection = { host: 'redis', port: 6379 }; const emailQueue = new Queue('email', { connection }); await emailQueue.add('welcome', { userId }, { attempts: 5, backoff: { type: 'exponential', delay: 1000 }, jobId: `welcome:${userId}` }); new Worker('email', async (job) => { await sendWelcomeEmail(job.data.userId); }, { connection, concurrency: 10 });
21

What is a compound index and why does field order matter?

Save to ▾
Show answer
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.
22

Write a Dockerfile for a production Node.js API.

Save to ▾
Show answer
FROM node:22-alpine AS deps WORKDIR /app COPY package*.json ./ RUN npm ci --omit=dev FROM node:22-alpine ENV NODE_ENV=production WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . USER node EXPOSE 3000 HEALTHCHECK CMD wget -qO- http://localhost:3000/health || exit 1 CMD ["node", "src/server.js"]
23

How do you add a correlation ID to every log line for a request?

Save to ▾
Show answer
const { AsyncLocalStorage } = require('async_hooks'); const { randomUUID } = require('crypto'); const als = new AsyncLocalStorage(); app.use((req, res, next) => { const id = req.get('X-Request-Id') || randomUUID(); res.set('X-Request-Id', id); als.run({ requestId: id }, next); }); const log = (msg, extra = {}) => logger.info({ ...extra, requestId: als.getStore()?.requestId }, msg); // Pass the ID to downstream services in headers.
24

Compare Prisma, Sequelize and TypeORM for SQL databases in Node.js.

Save to ▾
Show answer
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.
25

What is the difference between throwing an error and rejecting a promise inside an async function?

Save to ▾
Show answer
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.
26

How do you limit concurrency when calling an external API for 10,000 records?

Save to ▾
Show answer
async function runLimited(items, limit, worker) { const results = []; let i = 0; async function next() { while (i < items.length) { const idx = i++; results[idx] = await worker(items[idx]); } } await Promise.all(Array.from({ length: limit }, next)); return results; } await runLimited(records, 10, callPartnerApi); // Or use the p-limit package.
27

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.
28

What is database normalisation and when would you denormalise?

Save to ▾
Show answer
Normalisation organises tables to remove duplicate data and update anomalies, typically up to third normal form, for example keeping customers and orders in separate tables linked by foreign keys. You denormalise for read performance, such as storing a product name on an order line or a precomputed order count on a user, when joins become expensive. Denormalised data must be kept in sync.
29

What are health check endpoints and what is the difference between liveness and readiness?

Save to ▾
Show answer
Health endpoints let orchestrators check the app. Liveness answers whether the process is alive; if it fails, the container is restarted, so keep it simple. Readiness answers whether the instance can serve traffic, checking database and cache connections; if it fails, the load balancer stops sending requests but does not restart it. During shutdown, fail readiness first.
30

How do you run integration tests against a real database in CI?

Save to ▾
Show answer
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.
31

How can you cancel an in-flight HTTP request in Node.js?

Save to ▾
Show answer
Use AbortController. Create a controller, pass controller.signal to fetch or to libraries that support it such as axios, and call controller.abort() when the request is no longer needed, for example when the client disconnects. AbortSignal.timeout(ms) gives a ready-made timeout signal. Aborting rejects the promise with an AbortError, which you should handle separately from real failures.
32

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.
33

What are microtasks and macrotasks?

Save to ▾
Show answer
Macrotasks are scheduled work like setTimeout, setInterval, setImmediate and I/O callbacks, handled phase by phase by the event loop. Microtasks are promise reactions and queueMicrotask callbacks; they run right after the current synchronous code finishes and before the next macrotask. In Node, process.nextTick callbacks run even before promise microtasks. A long microtask chain can delay timers and I/O.
34

Compare offset pagination and cursor pagination.

Save to ▾
Show answer
Offset pagination uses page and limit, translated to LIMIT and OFFSET. It is simple and allows jumping to a page, but gets slow on large tables and can skip or repeat rows when data changes. Cursor pagination uses the last seen value, such as id or created_at, to fetch the next set with a WHERE clause. It is fast and stable, ideal for feeds and infinite scroll.
35

When should you embed documents versus reference them in MongoDB?

Save to ▾
Show answer
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.
36

How do you implement graceful shutdown in a Node.js server?

Save to ▾
Show answer
const server = app.listen(3000); async function shutdown(signal) { console.log(signal, 'received, closing'); server.close(async () => { await db.close(); await redis.quit(); process.exit(0); }); setTimeout(() => process.exit(1), 10000).unref(); } process.on('SIGTERM', shutdown); process.on('SIGINT', shutdown); // Stops new connections, finishes in-flight requests, closes pools.
37

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.
38

How do you implement rate limiting on a login endpoint?

Save to ▾
Show answer
const rateLimit = require('express-rate-limit'); const { RedisStore } = require('rate-limit-redis'); const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 5, standardHeaders: 'draft-7', legacyHeaders: false, keyGenerator: (req) => `${req.ip}:${req.body.email}`, store: new RedisStore({ sendCommand: (...a) => redis.sendCommand(a) }) }); app.post('/auth/login', loginLimiter, login); // Add account lockout or CAPTCHA after repeated failures.
39

Write a basic GitHub Actions workflow that tests and builds a Node.js app.

Save to ▾
Show answer
name: ci on: [push, pull_request] jobs: test: runs-on: ubuntu-latest services: mongo: image: mongo:7 ports: ['27017:27017'] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm - run: npm ci - run: npm run lint - run: npm test -- --coverage env: MONGO_URL: mongodb://localhost:27017/test
40

Write a centralised error handler with a custom AppError class.

Save to ▾
Show answer
class AppError extends Error { constructor(message, status = 500) { super(message); this.status = status; } } app.use((err, req, res, next) => { const status = err.status || 500; logger.error({ err, path: req.path }); res.status(status).json({ error: status === 500 ? 'Internal server error' : err.message }); }); // In a route: throw new AppError('User not found', 404);

Frequently asked questions

What happens in the Full Stack with Node.js technical round round?

The technical round is the core of a Full Stack with Node.js interview: concept questions with follow-ups, a live hands-on task and a deep dive into one of your projects. Interviewers check depth, not just definitions.

How do I clear the technical round round?

Say your approach out loud before you start writing. After a correct answer, expect 'why?' and 'what if?' follow-ups; go one level deeper than the question. Pick one project you can explain end to end, including what you would do differently.

Which round comes next?

A typical order is online assessment, telephonic screening, one or two technical rounds, a managerial round and HR. Use the other round pages to practise each stage.