Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 77 ยท Web and Frontend Interview Questions

Node.js and Backend Interview Questions

Practice Node.js and backend interview questions: event loop phases, streams and backpressure, clustering, REST design, authentication and idempotency, with runnable code.

Backend interviews test whether you can reason about a server under load: what blocks, what scales, what happens when a client retries a request, and how you keep credentials safe. Node.js questions usually start with the event loop and then drift into streams, scaling and API design.

All the examples in this lesson run on the site's Node 24 runner (single file, no npm packages). Servers listen on nothing; instead we call the handler functions directly, which is how you would unit-test them anyway. Where a real production setup is described (a cluster, a reverse proxy), the code is read-only and the runnable part is a small stand-in that shows the idea.

Backend question map

Event loop Why one thread can serve many users.
Streams Move big data in small chunks.
Scaling Use every CPU core.
Auth Hash passwords, sign tokens.

Idempotency and REST design tie these together.

1 / 2

How does Node handle many requests on one thread?

Short answer: JavaScript runs on one thread, but I/O (network, disk, DNS) is handed to the operating system or a small thread pool. While that work is pending, the event loop keeps running other callbacks. When the I/O finishes, its callback is queued. So Node is great at waiting for many things at once and poor at computing one big thing: a CPU-heavy loop blocks every other request.

The event loop cycles through phases. The ones worth naming:

  1. timers: callbacks from setTimeout and setInterval whose time has come.
  2. poll: wait for and run I/O callbacks.
  3. check: setImmediate callbacks.
  4. close callbacks: such as a socket's close event.

Between callbacks, Node drains two queues: process.nextTick first, then promise microtasks. These run to completion before the loop moves on, so a recursive nextTick can starve I/O.

Node.js Ordering: nextTick, promises, timers, setImmediate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This example runs as CommonJS (the first line // cjs tells the runner so). In an ES module, the whole file runs inside a promise job, so promise callbacks run before nextTick callbacks; in CommonJS, nextTick goes first. That difference is itself a favorite trick question. Read the numbers I put in the strings: they show the order. Interviewers love the question "timeout 0 or setImmediate first?". The honest answer is: from the main module it is not guaranteed (it depends on process timing); inside an I/O callback setImmediate always wins. The lines marked 6 and 7 can swap places on a busy machine, which is why you should never rely on it.

What blocks the loop?

Synchronous CPU work: a huge JSON.parse, a tight loop, crypto.pbkdf2Sync, a catastrophic regular expression, fs.readFileSync on a request path. The fixes are to move the work to a worker thread, to a separate process or service, to chunk it with setImmediate, or to use the async version of the API.

What are streams, and what is backpressure?

A stream processes data piece by piece instead of loading it all into memory. A 10 GB file can be copied with a few kilobytes of RAM. There are four kinds: readable, writable, duplex and transform.

Backpressure is what happens when the consumer is slower than the producer. If a readable keeps pushing into a slow writable, the data piles up in memory. A writable signals "slow down" by returning false from write() and emitting drain later. Calling stream.pipeline() handles this for you, forwards errors and cleans up every stream if one fails, which is why interviewers expect you to prefer it over bare .pipe().

JavaScript
// Read-only: a typical production copy with compression
import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";

await pipeline(
  createReadStream("access.log"),
  createGzip(),
  createWriteStream("access.log.gz"),
);

The runnable version below needs no files. It chains a generator source, a transform that upper-cases lines, and a slow writable, and counts how many chunks are waiting in memory:

Node.js A pipeline with a slow consumer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If an interviewer asks "why not read the file with readFile and send it?", the answer is memory: readFile holds the whole file per request, so ten concurrent downloads of a 1 GB file need 10 GB.

Clustering and scaling

One Node process uses one core for JavaScript. To use more cores you run several processes. The built-in cluster module forks workers that share the same listening port; in containers the more common answer is "run several instances behind a load balancer" (or let the orchestrator do it). Worker threads share memory with the main process and suit CPU-bound jobs; processes are isolated and suit scaling request handling.

JavaScript
// Read-only: the shape of a cluster setup
import cluster from "node:cluster";
import { availableParallelism } from "node:os";
import http from "node:http";

if (cluster.isPrimary) {
  for (let i = 0; i < availableParallelism(); i++) cluster.fork();
  cluster.on("exit", () => cluster.fork());   // replace crashed workers
} else {
  http.createServer((req, res) => res.end(`pid ${process.pid}\n`)).listen(3000);
}

Say the catch: workers do not share memory, so in-process caches, sessions and rate-limit counters must move to a shared store such as Redis, or every worker will behave differently.

REST design questions

Common prompts: "design the endpoints for a blog", "PUT versus PATCH", "which status codes?". A good compact answer:

  • Resources are nouns, plural: GET /posts, POST /posts, GET /posts/42, PATCH /posts/42, DELETE /posts/42.
  • Methods carry the meaning. GET is safe (no side effects) and idempotent. PUT replaces a resource and is idempotent. PATCH changes part of it. POST creates or triggers an action and is not idempotent by default. DELETE is idempotent.
  • Status codes: 200 OK, 201 Created (with a Location header), 204 No Content, 400 bad input, 401 not authenticated, 403 not allowed, 404 not found, 409 conflict, 422 validation failed, 429 too many requests, 500 server error.
  • Lists need pagination (cursor-based pages scale better than offset on large tables), filtering and a stable sort order.

Authentication: store passwords, sign tokens

Two facts are asked in almost every backend interview:

  1. Never store passwords in plain text, or with a fast hash. Use a slow, salted, purpose-built algorithm such as argon2id, bcrypt or scrypt. Node ships crypto.scrypt. The salt is random per user and stored next to the hash; it defeats precomputed tables and makes equal passwords look different.
  2. Compare secrets in constant time (crypto.timingSafeEqual) so response time does not leak how many characters matched.

A session cookie holds a random ID that points to server-side data. A signed token (like a JWT) carries its data and a signature; the server verifies the signature instead of looking anything up, which is convenient but makes revocation harder. The stand-in below hashes a password with scrypt and signs and verifies a small token with HMAC. It is a teaching model of the idea, not a replacement for a vetted library.

Node.js Password hashing and a signed token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Idempotency: surviving retries

A client sends POST /payments, the connection drops, and it does not know whether the charge happened. If it retries and the server charges twice, you have a serious bug. The standard fix is an idempotency key: the client generates a unique key per logical operation and sends it in a header. The server stores the response for that key; a repeat with the same key returns the stored response instead of repeating the work.

Details that interviewers like: store the key before doing the work (or lock on it) so two simultaneous retries do not both proceed; reject a reused key with a different body; expire keys after a day or so.

Node.js An idempotent payment handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A Map in memory is only a demo. With several processes or servers, the key store must be shared and must be written atomically (for example a unique database constraint or Redis SET NX). Otherwise two retries landing on different servers can both charge.

JSON questions: parse, stringify, circular references, validation and JWT

Node interviews return to JSON constantly, because every API speaks it. The event loop, streams and authentication basics are covered above. This section adds the JSON-specific questions and a more precise look at JSON Web Tokens. All blocks run on Node 24.

What does JSON.stringify silently change?

JSON is a text format with six value types: object, array, string, number, boolean and null. JavaScript has more, so JSON.stringify makes quiet decisions:

  • undefined, functions and symbols are dropped from objects and become null inside arrays.
  • NaN and Infinity become null.
  • Date objects become ISO strings (through toJSON), and do not come back as Date after JSON.parse.
  • Map, Set and typed arrays become {} or an object of indexes (they are not serialized as you expect).
  • BigInt throws a TypeError.
  • Keys are always strings; property order follows insertion order (integer-like keys first).

Your tools: a replacer function or array (JSON.stringify(value, replacer, space)) to transform or filter on the way out, toJSON() on a class to control its own serialization, a reviver (JSON.parse(text, reviver)) to rebuild types on the way in, and the third argument for pretty-printing. structuredClone is the right tool for a deep copy; the JSON round trip is a lossy hack for it.

Node.js What survives a JSON round trip, and replacer/reviver fixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Why does JSON.parse throw, and how do you handle bad input?

JSON.parse throws a SyntaxError on anything that is not strictly valid JSON: single quotes, trailing commas, comments, unquoted keys, and an empty string. It must run inside try/catch whenever the text comes from outside. On a server, a malformed body should produce a 400 Bad Request, not a crash. Other gotchas: parsing a huge document blocks the event loop (stream it with a parser such as stream-json, or limit the body size), __proto__ keys in untrusted JSON can lead to prototype pollution if you merge the result recursively into another object, and numbers above 2^53 - 1 lose precision because JSON numbers become doubles.

Node.js Bad JSON, big numbers and a safe parse helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

How do you serialize an object with a circular reference?

JSON.stringify throws TypeError: Converting circular structure to JSON when an object (directly or indirectly) contains itself, for example parent.children[0].parent === parent. Fixes, from best to worst: change the data model (store IDs instead of object references, or drop the back-pointer), implement toJSON to omit the cycle, use a replacer with a WeakSet to skip objects you have already seen, or use a library (flatted, superjson) when you need to round-trip the cycle. structuredClone copes with cycles but cannot clone functions.

Node.js Detect a cycle and serialize safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

How do you validate JSON, and what is JSON Schema?

Valid JSON (it parses) is not the same as valid data (it has the fields and types your code expects). Never trust the shape of a request body. Use JSON Schema, a standard vocabulary (type, required, properties, minimum, pattern, enum, additionalProperties) that describes the allowed shape; libraries such as Ajv, or Zod/Valibot (schemas written in code) validate it and return error paths. Validate at the edge (the controller or a middleware), return a 400/422 with the list of problems, and strip unknown fields. A schema also doubles as documentation (OpenAPI uses it). The real packages are not available on the site, so this is a tiny validator for the core keywords:

JavaScript
// Read-only: what the Ajv version would look like
const schema = {
  type: "object",
  required: ["email", "age"],
  properties: {
    email: { type: "string", pattern: "^[^@]+@[^@]+$" },
    age: { type: "integer", minimum: 18 },
  },
  additionalProperties: false,
};
const validate = ajv.compile(schema);
if (!validate(body)) res.status(422).json({ errors: validate.errors });
Node.js A tiny JSON Schema validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What is a JWT, exactly, and how is it verified?

A JSON Web Token is three Base64URL-encoded parts joined by dots: header.payload.signature. The header names the algorithm ({"alg":"HS256","typ":"JWT"}), the payload holds claims (sub subject, iat issued at, exp expiry, nbf not before, iss issuer, aud audience, plus your own), and the signature covers header.payload. The payload is encoded, not encrypted: anyone can read it. Never put secrets in it. Signing proves that the token was issued by the holder of the key and was not altered.

Algorithms: HS256 uses one shared secret (HMAC) for both signing and verifying; RS256/ES256 use a private key to sign and a public key to verify, so many services can verify without being able to issue tokens.

What a correct verifier does: fix the allowed algorithm on the server (never trust the alg in the token: the classic attacks are alg: "none" and switching RS256 to HS256 so the public key is used as an HMAC secret), compare signatures with a constant-time function (crypto.timingSafeEqual), check exp/nbf/iss/aud, and use short lifetimes with refresh tokens. A JWT cannot be revoked before it expires unless you keep a deny-list, which brings state back; that is the real trade-off against server-side sessions. Store web tokens in HttpOnly cookies rather than localStorage to keep them away from injected scripts.

Node.js A real HS256 JWT: sign, verify, and reject tampering and alg none

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Interview summary for the auth question: sessions (server state, easy revocation) versus JWT (stateless, harder to revoke); passwords stored with scrypt, bcrypt or argon2; short-lived access tokens plus rotating refresh tokens; HttpOnly; Secure; SameSite cookies; and rate limiting on login. Real projects use a maintained library (jose, jsonwebtoken) instead of the hand-written code above, which exists to show what the library checks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which runs first after the current synchronous code finishes?

    The nextTick queue is drained first, then promise microtasks, and only then does the loop continue to its phases.
  2. 2. What is backpressure?

    write() returning false and the drain event implement it; stream.pipeline manages it for you.
  3. 3. Why is a per-process in-memory session store a problem in a cluster?

    Workers are separate processes with separate heaps. Share state through Redis or a database.
  4. 4. A client retries POST /payments after a timeout. What prevents a double charge?

    POST is not idempotent by itself. The key lets the server recognize the retry and replay the earlier result.
  5. 5. Which is the right way to store passwords?

    Fast hashes can be brute-forced quickly. Slow, salted hashes make each guess expensive, and encryption is reversible, which you do not want.

Summary

  • Node runs JavaScript on one thread and relies on the event loop plus OS/thread-pool I/O; CPU-bound work blocks everyone.
  • Order of work: synchronous code, nextTick, promise microtasks, then loop phases (timers, poll, check).
  • Streams move data in chunks and pipeline handles backpressure and cleanup.
  • Scale with processes or instances; keep shared state outside the process.
  • REST: nouns, correct methods and status codes, pagination.
  • Hash passwords with a slow salted algorithm, compare in constant time, sign tokens.
  • Use idempotency keys so retries are safe.
  • JSON.stringify drops undefined and functions, turns NaN and dates into null or strings and throws on BigInt and circular references; use replacers, toJSON and revivers.
  • Validate request bodies with JSON Schema or Zod at the edge, and keep large ids as strings because JSON numbers lose precision above 2^53.
  • A JWT is a signed, not encrypted, header.payload.signature; fix the algorithm on the server, compare signatures in constant time and check exp, iss and aud.

Next: TypeScript Interview Questions.