← Interview prep

Node.js interview questions

Event loop, streams, Nest-style APIs, and Node production topics.

200 questions · Page 8 of 10

Want the full pack? Interview packs · Mock interview · Mentora

Page 8 of 10

Questions 141–160 of 200 · 0 of 20 on this page marked learned

141.nodejs-0141Mediummid

How do you use PostgreSQL from Node.js with the pg library: Pool, parameterized queries, transactions and releasing clients?

Create one Pool for the whole process. Use pool.query for single statements, because it borrows a client and returns it for you. For several statements that must run together (a transaction), take a client with pool.connect(), run BEGIN, COMMIT or ROLLBACK on that same client, and always release it in finally. Pass values as parameters ($1, $2), never by string concatenation. Call pool.end() on shutdown.

Full answer

Why a pool

  • Opening a Postgres connection is slow (network, authentication, process start on the server) and the server allows a limited number of connections. A pool keeps a few open connections and lends them out.
  • Create one Pool at start up and share it. Do not create a pool per request. new Pool({ max: 10 }) is typical, and the total over all app instances must stay below the server's max_connections (or use PgBouncer).

Querying

  • pool.query(text, values) borrows a connection for one statement and returns it automatically.
  • Use parameters: pool.query('SELECT * FROM students WHERE id = $1', [id]). The values are sent separately from the SQL, which prevents SQL injection and allows plan reuse.
  • Results: result.rows (array of objects), result.rowCount, result.fields.
  • Column types: bigint and numeric come back as strings because JavaScript numbers cannot hold them exactly. Cast in SQL (count(*)::int) or set a type parser when you are sure it is safe.

Transactions

  • A transaction belongs to one connection, so pool.query cannot be used between BEGIN and COMMIT (each call may use a different connection).
  • const client = await pool.connect(); try { await client.query('BEGIN'); ...; await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); }
  • Forgetting release() leaks a connection, and the pool runs dry (see the pitfalls item).

Operations

  • Handle pool.on('error') for errors on idle clients.
  • Close with await pool.end() when the process shuts down.
  • Watch pool.totalCount, idleCount and waitingCount for metrics.
  • Use migrations for schema changes, and an ORM or query builder when you want one, but the same pooling rules apply.
javascript
const { Pool } = require('pg');

async function main() {
  // Connection settings come from PGHOST, PGPORT, PGUSER, PGDATABASE and PGPASSWORD.
  const pool = new Pool({ max: 3 });
  await pool.query('DROP TABLE IF EXISTS demo_students');
  await pool.query('CREATE TABLE demo_students (id serial PRIMARY KEY, name text NOT NULL, marks int NOT NULL)');

  // Parameterized insert with RETURNING
  const inserted = await pool.query('INSERT INTO demo_students (name, marks) VALUES ($1, $2) RETURNING id, name', ['Asha', 78]);
  console.log('inserted:', JSON.stringify(inserted.rows[0]));

  // A hostile value is just data
  await pool.query('INSERT INTO demo_students (name, marks) VALUES ($1, $2)', ["Robert'); DROP TABLE demo_students;--", 40]);
  const count = await pool.query('SELECT count(*) AS total, count(*)::int AS total_int FROM demo_students');
  console.log('count as returned:', JSON.stringify(count.rows[0]), '| typeof total:', typeof count.rows[0].total);

  // A transaction on one client: the second insert fails, so both are rolled back.
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    await client.query('INSERT INTO demo_students (name, marks) VALUES ($1, $2)', ['Ravi', 64]);
    await client.query('INSERT INTO demo_students (name, marks) VALUES ($1, $2)', [null, 50]); // violates NOT NULL
    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    console.log('transaction failed with code', err.code, '-> rolled back');
  } finally {
    client.release();
  }
  const after = await pool.query('SELECT name FROM demo_students ORDER BY id');
  console.log('rows after rollback:', after.rows.length, '| Ravi saved:', after.rows.some((r) => r.name === 'Ravi'));

  // Pool statistics
  console.log('pool total/idle/waiting:', pool.totalCount > 0, pool.idleCount === pool.totalCount, pool.waitingCount);

  await pool.query('DROP TABLE demo_students');
  await pool.end();
}
main();

The script needs a running PostgreSQL server and PG environment variables (it was run against PostgreSQL 17). It creates and drops its own table. Install first with npm install pg (run here with pg 8.23.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): inserted: {"id":1,"name":"Asha"} count as returned: {"total":"2","total_int":2} | typeof total: string transaction failed with code 23502 -> rolled back rows after rollback: 2 | Ravi saved: false pool total/idle/waiting: true true 0

Key points

  • One Pool per process, shared by all requests.
  • pool.query for one statement, pool.connect for a transaction.
  • Always release the client in finally.
  • Use $1 parameters, never string concatenation.
  • bigint and numeric arrive as strings.

Common mistakes

  • Creating a new Pool for every request.
  • Building SQL with template strings and user input.
  • Using pool.query between BEGIN and COMMIT.
  • Forgetting client.release() on an error path.
  • Assuming count(*) is a JavaScript number.

Follow-ups

  • How do you choose the pool size?
  • What does PgBouncer add?
  • How do you run a migration safely in a deployment?

Tips

  • Start with 'one pool, shared'.
  • Explain why a transaction needs one client.
  • Mention parameters as the injection defence.
142.nodejs-0142Hardsenior

What goes wrong with Postgres in production Node.js services: leaked clients, pool exhaustion, slow queries, idle client errors and type surprises?

A client taken with pool.connect() and not released stays busy forever, and when all clients are busy every request waits and then times out. Defend with release in finally, connectionTimeoutMillis, statement_timeout, idle_in_transaction_session_timeout, a pool.on('error') handler (an unhandled error on an idle client can crash the process), and awareness that bigint and numeric are strings.

Full answer

Failure modes and defences

  1. Leaked clients and pool exhaustion

    • pool.connect() without release() (an early return, a thrown error, a missing finally) keeps that connection busy. After max leaks, new requests queue. With no connectionTimeoutMillis they wait forever and the service looks frozen while the database is idle.
    • Set connectionTimeoutMillis so waiting fails fast. Always use try/finally. Prefer pool.query when you do not need a transaction.
    • Watch pool.waitingCount. A value above zero for a long time means a leak or too small a pool.
  2. Slow queries

    • A single slow query holds a connection and can block everything behind it. Set statement_timeout (in the pool options or per transaction with SET LOCAL). The server cancels the query with error 57014. Add indexes and use EXPLAIN.
    • Use query_timeout in pg for the client side as a second guard.
  3. Open transactions

    • A transaction left open (BEGIN without COMMIT) holds locks and prevents vacuum. Set idle_in_transaction_session_timeout on the server or role so Postgres ends such sessions.
  4. Errors on idle clients

    • A database restart, a failover or a proxy can kill idle connections. pg emits an 'error' event on the pool. If no listener exists, the process crashes with an unhandled error event. Add pool.on('error', log). The pool removes the broken client and creates a new one when needed.
  5. Types and data

    • bigint (int8) and numeric are returned as strings. Cast in SQL or use pg.types.setTypeParser carefully, because large values lose precision.
    • timestamp without time zone is parsed in the local time zone. Prefer timestamptz.
  6. Shutdown and capacity

    • Call pool.end() after the HTTP server stops accepting work.
    • Total connections = instances times max. Compare with max_connections, or use PgBouncer in transaction mode.
    • Retry only idempotent operations, and handle serialization failures (40001) and deadlocks (40P01) by retrying the whole transaction.
javascript
const { Pool, types } = require('pg');

async function main() {
  // 1. A leaked client exhausts a small pool, and the timeout turns a hang into an error.
  const small = new Pool({ max: 2, connectionTimeoutMillis: 200 });
  const leaked = [await small.connect(), await small.connect()];   // never released
  try {
    await small.query('SELECT 1');
  } catch (err) {
    console.log('1. leaked clients ->', err.message);
  }
  console.log('   waiting after timeout:', small.waitingCount, '| total:', small.totalCount);
  leaked.forEach((client) => client.release());
  console.log('   after release, query works:', (await small.query('SELECT 1 AS one')).rows[0].one === 1);
  await small.end();

  // 2. statement_timeout cancels slow queries on the server.
  const timed = new Pool({ max: 1, statement_timeout: 100 });
  try {
    await timed.query('SELECT pg_sleep(2)');
  } catch (err) {
    console.log('2. slow query ->', err.code, err.message);
  }
  await timed.end();

  // 3. Types
  const typed = new Pool({ max: 1 });
  const row = (await typed.query("SELECT 9007199254740993::bigint AS big, 1.10::numeric AS price, now()::timestamptz AS at")).rows[0];
  console.log('3. bigint:', typeof row.big, row.big, '| numeric:', typeof row.price, row.price, '| timestamptz:', row.at instanceof Date);
  const asNumber = Number(row.big);
  console.log('   converting the bigint to a number loses precision:', String(asNumber) !== row.big);

  // 4. The server kills an idle connection. Without a listener this would crash the process.
  const watched = new Pool({ max: 1 });
  watched.on('error', (err) => console.log('4. pool error handler got:', err.code));
  const client = await watched.connect();
  const pid = (await client.query('SELECT pg_backend_pid() AS pid')).rows[0].pid;
  client.release();                                               // now idle
  await typed.query('SELECT pg_terminate_backend($1)', [pid]);
  await new Promise((resolve) => setTimeout(resolve, 100));
  console.log('   next query after the broken idle client works:', (await watched.query('SELECT 1 AS one')).rows[0].one === 1);

  await watched.end();
  await typed.end();
}
main();

Four failures are reproduced against a local PostgreSQL server: a leaked client, a slow query, string types, and a killed idle connection. Install first with npm install pg (run here with pg 8.23.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. leaked clients -> timeout exceeded when trying to connect waiting after timeout: 0 | total: 2 after release, query works: true 2. slow query -> 57014 canceling statement due to statement timeout 3. bigint: string 9007199254740993 | numeric: string 1.10 | timestamptz: true converting the bigint to a number loses precision: true 4. pool error handler got: 57P01 next query after the broken idle client works: true

Key points

  • Leaked clients exhaust the pool and make the service look frozen.
  • connectionTimeoutMillis and statement_timeout make failures fast.
  • Always add pool.on('error') for idle client errors.
  • End idle transactions with a server timeout.
  • bigint and numeric are strings, and timestamps need care.

Common mistakes

  • Using pool.connect() without try and finally.
  • No connection timeout, so requests wait forever.
  • No pool 'error' listener, so a restart of the database crashes the app.
  • Converting a bigint column to Number.
  • Opening a transaction and returning early without rollback.

Follow-ups

  • How does PgBouncer transaction pooling change what you can do with a connection?
  • How do you retry a transaction after a deadlock?
  • How would you alert on pool exhaustion?

Tips

  • Use the 'looks frozen' symptom to open.
  • List timeouts and the error listener as the defences.
  • Mention the string types.
143.nodejs-0143Easyfresher

How do you use Redis from Node.js with ioredis: strings, expiry, counters, hashes, pipelines and connection handling?

Redis is an in-memory data store that is used for caches, counters, sessions, queues and pub/sub. With ioredis you create one client, call commands as promise-returning methods (set, get, incr, hset), give keys an expiry with EX, batch commands with pipeline or multi, handle the 'error' event, and close with quit(). Use key prefixes and always set a TTL on cache keys.

Full answer

What Redis is for

  • Very fast key-value operations in memory. Data types: strings, hashes, lists, sets, sorted sets, streams and more.
  • Typical uses: caching, rate limit counters, sessions, leaderboards, job queues (BullMQ), pub/sub and locks.
  • Data is mostly in memory, so it is not a main database unless persistence is configured and the data fits.

Using ioredis

  • const redis = new Redis(url). Create one client per process (and a separate one for subscribe mode). It reconnects automatically.
  • Commands match Redis names: redis.set('key', 'value', 'EX', 60) sets with a 60 second expiry. get returns a string or null. del removes keys.
  • incr and incrby are atomic, so they are safe for counters across many instances.
  • Hashes: hset('user:1', { name: 'Asha', plan: 'free' }), hgetall returns an object with string values.
  • ttl(key) shows the remaining seconds, -1 means no expiry, -2 means no key.
  • pipeline() sends many commands in one network round trip and returns results in order. multi() also wraps them in a transaction (all or nothing execution, but no rollback logic).
  • Everything is a string in Redis. Store JSON with JSON.stringify and parse it back.

Good habits

  • Key naming: app:entity:id, for example school:session:abc. Use SCAN, never KEYS, in production.
  • Set a TTL on cache keys so memory does not fill.
  • Listen to redis.on('error', ...), otherwise connection problems are printed as unhandled errors.
  • Close with await redis.quit() on shutdown.
  • Do not store huge values. Redis runs commands on one thread, so a slow command blocks all clients.
javascript
const Redis = require('ioredis');

async function main() {
  const redis = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
  redis.on('error', (err) => console.log('redis error:', err.message));
  const p = `demo:${process.pid}:`;                                  // unique prefix for this run

  await redis.set(p + 'greeting', 'hello', 'EX', 30);
  console.log('get:', await redis.get(p + 'greeting'), '| missing key:', await redis.get(p + 'nothing'));
  const ttl = await redis.ttl(p + 'greeting');
  console.log('ttl is between 1 and 30 seconds:', ttl > 0 && ttl <= 30);

  console.log('incr x3:', await redis.incr(p + 'visits'), await redis.incr(p + 'visits'), await redis.incr(p + 'visits'));

  await redis.hset(p + 'user:1', { name: 'Asha', plan: 'free' });
  console.log('hash:', JSON.stringify(await redis.hgetall(p + 'user:1')));

  await redis.set(p + 'json', JSON.stringify({ marks: [78, 91] }));
  console.log('json value:', JSON.parse(await redis.get(p + 'json')).marks.join(','));

  // pipeline: one round trip, results come back in order as [error, value] pairs
  const results = await redis.pipeline().incr(p + 'visits').get(p + 'greeting').exists(p + 'nothing').exec();
  console.log('pipeline:', JSON.stringify(results.map(([err, value]) => value)));

  // NX: set only if the key does not exist (the base of a lock)
  console.log('set NX first:', await redis.set(p + 'lock', 'a', 'EX', 5, 'NX'), '| second:', await redis.set(p + 'lock', 'b', 'EX', 5, 'NX'));

  const keys = await redis.keys(p + '*');          // fine in a demo, use SCAN in production
  await redis.del(...keys);
  console.log('cleaned up', keys.length, 'keys');
  await redis.quit();
}
main();

The script needs a running Redis server (REDIS_URL, default localhost:6379). It uses a unique key prefix and deletes its keys at the end. Install first with npm install ioredis (run here with ioredis 6.1.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): get: hello | missing key: null ttl is between 1 and 30 seconds: true incr x3: 1 2 3 hash: {"name":"Asha","plan":"free"} json value: 78,91 pipeline: [4,"hello",0] set NX first: OK | second: null cleaned up 5 keys

Key points

  • Redis is a fast in-memory store for caches, counters, sessions and queues.
  • ioredis commands are promise methods; one client per process.
  • set with EX gives an expiry, and incr is atomic.
  • pipeline batches commands into one round trip.
  • Prefix keys, set TTLs and handle the 'error' event.

Common mistakes

  • Using KEYS in production code.
  • Caching without a TTL.
  • Creating a client per request.
  • Reading and then writing a counter instead of using INCR.
  • No 'error' listener on the client.

Follow-ups

  • What is the difference between pipeline and multi?
  • Why is Redis single-threaded and still fast?
  • How do you persist Redis data, and when should you not rely on it?

Tips

  • Name four uses of Redis.
  • Mention atomic incr and EX.
  • Say that every value is a string.
144.nodejs-0144Mediummid

How do you build an in-memory LRU cache with a TTL in Node.js, and what are the limits of in-process caching?

A JavaScript Map keeps insertion order, so an LRU cache is a Map where each read deletes and re-inserts the key to mark it recent, and eviction removes the first key when the size limit is exceeded. Store an expiry time with each value and check it on read. In-process caches are fast but are per instance, vanish on restart, and need a size bound, so use a shared cache such as Redis when instances must agree.

Full answer

The structure

  • Map iterates in insertion order. The first key is the least recently used (LRU) when you re-insert on every read.
  • get(key): read the entry. If it is missing or expired, return undefined (and delete if expired). Otherwise delete and set the key again to move it to the end, then return the value.
  • set(key, value): delete the key if present, insert with expiry = now + ttl, then while size > max, delete map.keys().next().value.
  • Both operations are O(1) on average.
  • Inject the clock (a now function) so that tests do not need real waiting.

Decisions

  • Bound the cache by entries or by estimated bytes. An unbounded Map is a memory leak.
  • TTL protects against stale data. Choose it from how wrong the data is allowed to be, add small random jitter so many keys do not expire at once.
  • Cache promises or add request coalescing to avoid a stampede on a miss.
  • Negative caching: remember 'not found' for a short time to protect the database from repeated lookups.
  • Invalidate on write: delete the key when the source changes.

Limits of in-process caches

  • Each instance has its own copy, so instances can disagree and invalidation does not cross processes.
  • Data is lost on restart (cold start causes a burst of misses).
  • It uses the Node heap, which adds garbage collection work. Large caches belong in Redis or Memcached.
  • Libraries: lru-cache (well tested, has TTL, size accounting and stale options). Prefer it in production over your own class.
javascript
class LruCache {
  constructor({ max, ttlMs, now = Date.now }) {
    this.max = max; this.ttlMs = ttlMs; this.now = now;
    this.map = new Map();
    this.hits = 0; this.misses = 0;
  }
  get(key) {
    const entry = this.map.get(key);
    if (!entry || entry.expiresAt <= this.now()) {
      if (entry) this.map.delete(key);           // expired
      this.misses++;
      return undefined;
    }
    this.map.delete(key);                        // move to the most recent position
    this.map.set(key, entry);
    this.hits++;
    return entry.value;
  }
  set(key, value) {
    this.map.delete(key);
    this.map.set(key, { value, expiresAt: this.now() + this.ttlMs });
    while (this.map.size > this.max) this.map.delete(this.map.keys().next().value); // evict the least recently used
  }
  keys() { return [...this.map.keys()]; }
}

let time = 0;                                     // a fake clock in milliseconds
const cache = new LruCache({ max: 3, ttlMs: 1000, now: () => time });

cache.set('a', 1); cache.set('b', 2); cache.set('c', 3);
console.log('order after 3 sets      :', cache.keys().join(','));
cache.get('a');
console.log('order after reading a   :', cache.keys().join(','));
cache.set('d', 4);
console.log('after adding d (max 3)  :', cache.keys().join(','), '| b was evicted:', cache.get('b') === undefined);

time = 999; console.log('at 999 ms, a still there:', cache.get('a'));
time = 1001; console.log('at 1001 ms, a expired    :', cache.get('a'));
console.log('hits:', cache.hits, '| misses:', cache.misses);

// Without a bound, a Map used as a cache grows forever.
const unbounded = new Map();
for (let i = 0; i < 100000; i++) unbounded.set('request-' + i, i);
console.log('unbounded map size after 100000 different keys:', unbounded.size);

A fake clock makes the TTL behaviour exact. The last lines show why a bound is needed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): order after 3 sets : a,b,c order after reading a : b,c,a after adding d (max 3) : c,a,d | b was evicted: true at 999 ms, a still there: 1 at 1001 ms, a expired : undefined hits: 2 | misses: 2 unbounded map size after 100000 different keys: 100000

Key points

  • Map order gives O(1) LRU: delete and set on read, drop the first key on overflow.
  • Store an expiry and check it on read.
  • Always bound the size.
  • Add negative caching and jitter where needed.
  • In-process caches are per instance and lost on restart.

Common mistakes

  • Using a plain object or Map as an unbounded cache.
  • Not moving a key on read, which turns LRU into FIFO.
  • Using Date.now() directly and making tests slow or flaky.
  • Caching mutable objects and letting callers change them.
  • Expecting all instances to share the same cache.

Follow-ups

  • How does lru-cache handle size by bytes?
  • How do you invalidate entries across several instances?
  • What is the difference between LRU and LFU?

Tips

  • Say 'Map keeps insertion order' in the first sentence.
  • Describe get and set in two lines.
  • Name the limits of in-process caching.
145.nodejs-0145Hardsenior

How do you implement cache-aside with Redis in a Node.js service, including TTL jitter, stampede protection with a lock, negative caching and invalidation?

Cache-aside means the application reads the cache first, loads from the database on a miss, and writes the result to the cache with a TTL. To stop a stampede (many requests loading the same missing key), let one request take a short lock with SET key NX PX and load, while others wait briefly and read the cache. Add TTL jitter, cache 'not found' for a short time, and delete the key when data changes.

Full answer

Cache-aside steps

  1. GET the key from Redis. If found, return it.
  2. On a miss, load from the database.
  3. SET the key with a TTL, then return the value.
  4. On a write, update the database first and then DELETE the cache key (not update it, which avoids race conditions between writers).

Problems and fixes

  • Stampede: when a hot key expires, hundreds of requests miss at once and hit the database. Use a lock: SET lock:key token NX PX 5000. Only the winner loads. The others sleep a few milliseconds and read the cache again, or fall back to loading after a timeout. In one process, share the promise instead.
  • Safe release: delete the lock only if the stored token is yours (a short Lua script compares and deletes). The lock expiry protects against a crashed owner.
  • Synchronised expiry: many keys with the same TTL expire together. Add random jitter (for example plus or minus 10 percent).
  • Negative caching: store a marker such as null for a short TTL (30 seconds), so lookups for missing ids do not reach the database repeatedly.
  • Stale data: choose a TTL by how wrong the data may be. Stale-while-revalidate returns the old value and refreshes in the background.
  • Serialisation: JSON for plain data, and a version in the key (user:v2:42) so a deploy that changes the shape does not read old entries.
  • Failure of Redis: treat the cache as optional. On a Redis error log and go to the database, with a timeout so Redis problems do not slow requests.
  • Avoid caching per-user data under shared keys, and never cache secrets.

Metrics: hit rate, loader calls, lock waits and latency.

javascript
const Redis = require('ioredis');
const { setTimeout: sleep } = require('node:timers/promises');

const redis = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
const prefix = `cache-demo:${process.pid}:`;
let loaderCalls = 0;
const database = new Map([['1', { id: 1, name: 'Asha' }]]);

async function loadFromDatabase(id) {
  loaderCalls++;
  await sleep(50);                                       // a slow query
  return database.get(id) ?? null;
}

const jitter = (seconds) => Math.round(seconds * 1000 * (0.9 + Math.random() * 0.2)); // plus or minus 10 percent

async function getStudent(id) {
  const key = prefix + 'student:' + id;
  for (let attempt = 0; attempt < 20; attempt++) {
    const cached = await redis.get(key);
    if (cached !== null) return JSON.parse(cached);       // a stored null means "known to be missing"

    const token = Math.random().toString(36).slice(2);
    if (await redis.set(key + ':lock', token, 'PX', 2000, 'NX')) {   // winner loads
      try {
        const value = await loadFromDatabase(id);
        const ttlMs = value === null ? 1000 : jitter(60);            // short TTL for missing data
        await redis.set(key, JSON.stringify(value), 'PX', ttlMs);
        return value;
      } finally {
        await redis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0", 1, key + ':lock', token);
      }
    }
    await sleep(10);                                       // someone else is loading, check the cache again
  }
  return loadFromDatabase(id);                             // give up waiting
}

async function main() {
  // 20 requests arrive together for the same missing cache key.
  const results = await Promise.all(Array.from({ length: 20 }, () => getStudent('1')));
  console.log('20 parallel requests ->', results.every((r) => r && r.name === 'Asha'), '| database calls:', loaderCalls);

  await getStudent('1');
  console.log('a later request hits the cache, database calls:', loaderCalls);
  const ttl = await redis.pttl(prefix + 'student:1');
  console.log('TTL with jitter is within 54 to 66 seconds:', ttl > 53000 && ttl <= 66000);

  // Invalidate on write: update the database, then delete the key.
  database.set('1', { id: 1, name: 'Asha Rao' });
  await redis.del(prefix + 'student:1');
  console.log('after invalidation:', (await getStudent('1')).name, '| database calls:', loaderCalls);

  // Negative caching: a missing id is loaded once, then remembered briefly.
  await getStudent('99'); await getStudent('99'); await getStudent('99');
  console.log('three lookups of a missing id -> database calls:', loaderCalls);

  const keys = await redis.keys(prefix + '*');
  if (keys.length) await redis.del(...keys);
  await redis.quit();
}
main();

Twenty parallel requests for the same key cause one database call because of the lock. The script needs a running Redis server. Install first with npm install ioredis (run here with ioredis 6.1.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 20 parallel requests -> true | database calls: 1 a later request hits the cache, database calls: 1 TTL with jitter is within 54 to 66 seconds: true after invalidation: Asha Rao | database calls: 2 three lookups of a missing id -> database calls: 3

Key points

  • Read cache, load on miss, set with TTL, delete on write.
  • A NX lock lets one request load while others wait.
  • Add TTL jitter and short negative caching.
  • Delete the key on write instead of updating it.
  • Treat the cache as optional when Redis fails.

Common mistakes

  • Letting every request reload a hot key after it expires.
  • Deleting a lock that belongs to another owner.
  • Updating the cache and the database in different orders from different writers.
  • Using the same TTL for every key.
  • Failing requests because Redis is down.

Follow-ups

  • Why delete the key on write instead of setting the new value?
  • How does stale-while-revalidate work?
  • What are the weaknesses of a single-instance Redis lock?

Tips

  • Say the four steps first.
  • Explain the stampede with numbers: one load, many waiters.
  • Mention token-checked release.
146.nodejs-0146Mediummid

What is a job queue, and how do producers, workers, retries, delayed jobs and concurrency work in BullMQ?

A job queue moves slow or unreliable work out of the request path. A producer adds a job (a name and JSON data) to a queue stored in Redis. One or more workers, often in separate processes, take jobs, run a processor function and mark them completed or failed. BullMQ adds retries with backoff, delayed and repeatable jobs, priorities, rate limits, concurrency and events.

Full answer

Why queues

  • Respond fast: accept the request, queue the email, report or image resize, and return 202 or 201.
  • Reliability: a job survives restarts and can be retried.
  • Smoothing: workers process at their own speed, so spikes do not overload the database or an external API.
  • Scaling: add worker processes without changing the web service.

BullMQ concepts (it stores state in Redis)

  • Queue: producer side. queue.add('send-email', { to }, options).
  • Worker: new Worker('emails', async (job) => { ... return result }, { connection, concurrency: 5 }). If the function throws, the job fails. If it returns, the job completes and the return value is stored.
  • Job options: attempts and backoff (type fixed or exponential, delay), delay (run later), priority, removeOnComplete and removeOnFail (limit how much history stays in Redis), jobId (use for de-duplication).
  • QueueEvents: listens to completed, failed and progress for any job in the queue.
  • Repeatable jobs and schedulers run on a cron pattern.
  • Flows for parent and child jobs, and rate limiting per queue.

Operational notes

  • Redis configuration: workers need maxmemory-policy noeviction, otherwise Redis may evict queue data.
  • Run workers as separate processes from the web server and handle graceful shutdown with worker.close().
  • Jobs are delivered at least once. A job may run twice (after a crash or stalled lock), so the processor must be idempotent.
  • Keep job data small (ids, not whole records), and JSON serialisable.
  • Monitor with Bull Board or metrics: waiting, active, failed counts and age of the oldest job.
javascript
const { Queue, Worker, QueueEvents } = require('bullmq');

const url = new URL(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
const connection = { host: url.hostname, port: Number(url.port) };
const name = `demo-emails-${process.pid}`;

async function main() {
  const queue = new Queue(name, { connection });
  const events = new QueueEvents(name, { connection });
  await events.waitUntilReady();

  const attemptsSeen = {};
  const worker = new Worker(name, async (job) => {
    attemptsSeen[job.data.to] = (attemptsSeen[job.data.to] || 0) + 1;
    if (job.data.to === 'flaky@example.com' && job.attemptsMade < 1) throw new Error('temporary SMTP failure');
    return { sent: job.data.to };
  }, { connection, concurrency: 2 });

  // Producers add jobs. The flaky one fails once and is retried after 20 ms.
  const jobs = await Promise.all([
    queue.add('send-email', { to: 'asha@example.com' }),
    queue.add('send-email', { to: 'flaky@example.com' }, { attempts: 3, backoff: { type: 'fixed', delay: 20 } }),
    queue.add('send-email', { to: 'later@example.com' }, { delay: 100 }),
  ]);

  for (const job of jobs) {
    const result = await job.waitUntilFinished(events);
    console.log(job.data.to.padEnd(18), 'result:', JSON.stringify(result), '| attempts run:', attemptsSeen[job.data.to]);
  }
  const counts = await queue.getJobCounts('waiting', 'active', 'delayed', 'completed', 'failed');
  console.log('counts:', JSON.stringify(counts));

  await worker.close();
  await events.close();
  await queue.obliterate({ force: true });
  await queue.close();
}
main();

Three jobs are queued: a normal one, one that fails once and is retried, and a delayed one. The script needs a running Redis server. Install first with npm install bullmq (run here with bullmq 6.7.12). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): asha@example.com result: {"sent":"asha@example.com"} | attempts run: 1 flaky@example.com result: {"sent":"flaky@example.com"} | attempts run: 2 later@example.com result: {"sent":"later@example.com"} | attempts run: 1 counts: {"waiting":0,"active":0,"delayed":0,"completed":3,"failed":0}

Key points

  • A queue moves slow work out of the request path.
  • Producers add jobs and workers process them from Redis.
  • attempts and backoff handle retries; delay schedules a later run.
  • Delivery is at least once, so processors must be idempotent.
  • Run workers separately and close them gracefully.

Common mistakes

  • Doing slow work inside the HTTP request.
  • Assuming a job runs exactly once.
  • Storing large payloads in the job data.
  • Never removing completed jobs, so Redis memory grows.
  • Running workers inside the web process with no graceful shutdown.

Follow-ups

  • What happens to a job when a worker crashes while processing it?
  • How do you add a job that must run every day at 02:00?
  • How do you prioritise jobs or limit the rate to an external API?

Tips

  • Explain producer, queue, worker in one sentence.
  • Say 'at least once'.
  • Mention retries and removeOnComplete.
147.nodejs-0147Hardsenior

How do you design reliable background jobs: idempotency, retries, dead letters and graceful worker shutdown?

Queues give at-least-once delivery, so a job can run twice. Make each job idempotent (a job id or an idempotency record), retry transient errors with exponential backoff and jitter, stop retrying permanent errors, move jobs that run out of attempts to a dead letter queue for inspection, and shut workers down gracefully by letting the active job finish before the process exits.

Full answer

Delivery guarantees

  • Exactly-once processing across a network is not realistic. Queues choose at-least-once: a job is retried if a worker crashes or its lock expires (stalled job). So side effects (send an email, charge a card) must be safe to repeat.

Idempotency patterns

  • Deterministic job id: queue.add(name, data, { jobId: 'invoice-42' }). Adding the same id again is ignored while the job exists, which de-duplicates producers.
  • Processor side: record completed work in the database with a unique key (job id or business id) and skip if present. Use the same key as the idempotency key for payment APIs.
  • Make the effect itself idempotent: UPSERT, set state rather than increment.

Retries

  • Retry transient failures (timeouts, 429, 503) with exponential backoff and jitter, and a limited number of attempts.
  • Do not retry permanent failures (validation error, 404 for the target). In BullMQ throw UnrecoverableError to fail at once.
  • Respect external rate limits with queue rate limiting, and use timeouts inside the processor so a job cannot hang forever.

Dead letters

  • A job that has used all attempts goes to the failed set. Copy it (with the error and data) to a dead letter queue or an alert, so people can inspect, fix and replay it. Do not drop failures silently.

Graceful shutdown

  • On SIGTERM: stop taking new jobs and wait for active ones (worker.close() waits unless forced), then close the queue and Redis connections. Set the container's stop timeout longer than your longest job, or split long jobs into steps.
  • If a worker is killed, the lock expires and another worker picks the job up, which is why idempotency is needed.

Observability: log job id, attempt number and duration, and alert on failed counts, queue age and retry rates.

javascript
const { Queue, Worker, QueueEvents, UnrecoverableError } = require('bullmq');
const { setTimeout: sleep } = require('node:timers/promises');

const url = new URL(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
const connection = { host: url.hostname, port: Number(url.port) };
const suffix = process.pid;

async function main() {
  const queue = new Queue(`work-${suffix}`, { connection });
  const dead = new Queue(`dead-${suffix}`, { connection });
  const events = new QueueEvents(`work-${suffix}`, { connection });
  await events.waitUntilReady();

  const charged = new Set();                       // our idempotency record
  let sideEffects = 0;
  const processor = async (job) => {
    if (job.name === 'charge') {
      if (charged.has(job.data.invoice)) return 'skipped (already charged)';
      sideEffects++;
      charged.add(job.data.invoice);
      await sleep(150);                            // a slow job, still running during shutdown
      return 'charged';
    }
    if (job.name === 'always-fails') throw new Error('upstream is down');
    if (job.name === 'bad-input') throw new UnrecoverableError('invalid card number');
  };
  const worker = new Worker(`work-${suffix}`, processor, { connection });

  // Jobs that used all their attempts, or failed with a permanent error, are copied to the dead letter queue.
  const toDeadLetter = async (job, err) => {
    const finished = err.name === 'UnrecoverableError' || job.attemptsMade >= (job.opts.attempts || 1);
    if (job && finished) await dead.add('dead', { original: job.name, error: err.message, attempts: job.attemptsMade });
  };
  worker.on('failed', toDeadLetter);

  // 1. Same jobId twice: only one job exists, so the invoice is charged once.
  const first = await queue.add('charge', { invoice: 'inv-42' }, { jobId: 'invoice-42' });
  await queue.add('charge', { invoice: 'inv-42' }, { jobId: 'invoice-42' });
  const counts = await queue.getJobCounts('waiting', 'active');
  console.log('1. jobs for jobId invoice-42 (queued twice):', counts.waiting + counts.active);

  // 2. Graceful shutdown while the job is active: close() waits for it.
  await sleep(50);
  console.log('2. state before close:', await first.getState());
  await worker.close();
  console.log('   state after close  :', await first.getState(), '| charges made:', sideEffects);

  // 3. A second worker: retries then dead letter, and an unrecoverable error.
  const worker2 = new Worker(`work-${suffix}`, processor, { connection });
  worker2.on('failed', toDeadLetter);
  const retry = await queue.add('always-fails', {}, { attempts: 3, backoff: { type: 'fixed', delay: 10 } });
  const bad = await queue.add('bad-input', {}, { attempts: 5 });
  await Promise.all([retry.waitUntilFinished(events).catch(() => {}), bad.waitUntilFinished(events).catch(() => {})]);
  await sleep(100);
  const deadJobs = (await dead.getJobs(['waiting'])).map((j) => `${j.data.original}: ${j.data.attempts} attempt(s), "${j.data.error}"`).sort();
  console.log('3. dead letter queue:', deadJobs.join(' | '));

  await worker2.close(); await events.close();
  await queue.obliterate({ force: true }); await dead.obliterate({ force: true });
  await queue.close(); await dead.close();
}
main();

The script shows de-duplication by jobId, a worker that finishes its active job during close(), and two kinds of failure that end in a dead letter queue: retries that run out, and an error that is not retried. It needs a running Redis server. Install first with npm install bullmq (run here with bullmq 6.7.12). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. jobs for jobId invoice-42 (queued twice): 1 2. state before close: active state after close : completed | charges made: 1 3. dead letter queue: always-fails: 3 attempt(s), "upstream is down" | bad-input: 1 attempt(s), "invalid card number"

Key points

  • Delivery is at least once, so side effects must be idempotent.
  • A deterministic jobId de-duplicates producers.
  • Retry transient errors with backoff; fail permanent ones at once.
  • Send exhausted jobs to a dead letter queue, not the void.
  • On shutdown let the active job finish before exiting.

Common mistakes

  • Assuming a job runs exactly once and charging twice.
  • Retrying permanent errors until attempts run out.
  • Dropping failed jobs with no record.
  • Stopping the process while a job is running, with no graceful close.
  • Using the same retry delay for all clients, which causes retry storms.

Follow-ups

  • How do you replay jobs from a dead letter queue safely?
  • What is a stalled job in BullMQ?
  • How does an idempotency key work with a payment provider?

Tips

  • Say 'at least once, so idempotent'.
  • Describe retries, dead letters and shutdown in that order.
  • Mention a deterministic job id.
148.nodejs-0148Mediummid

What are Web Streams in Node.js (ReadableStream, TransformStream, CompressionStream), and how do they convert to and from Node streams?

Web Streams are the standard streaming API of browsers and fetch. Node has them as globals (ReadableStream, WritableStream, TransformStream, CompressionStream, TextDecoderStream). fetch response bodies are ReadableStreams. Convert with Readable.fromWeb, Readable.toWeb and the Writable and Duplex equivalents. Use Web Streams for code shared with browsers and Node streams for fs, net and most existing Node APIs.

Full answer

Two stream families

  • Node streams (node:stream): older, event-based, used by fs, net, http, zlib. Backpressure through write() returning false and 'drain', or through pipeline.
  • Web Streams (WHATWG): promise-based readers and writers, pipeTo and pipeThrough, used by fetch, Response, Blob.stream(), Deno and browsers. Backpressure through the desiredSize and the pull model.

In Node

  • Globals: ReadableStream, WritableStream, TransformStream, TextEncoderStream, TextDecoderStream, CompressionStream and DecompressionStream.
  • fetch(url).then(r => r.body) is a ReadableStream. It is async iterable in Node, so for await works.
  • Conversions: Readable.fromWeb(webReadable), Readable.toWeb(nodeReadable), Writable.fromWeb, Writable.toWeb, Duplex.fromWeb and Duplex.toWeb. stream.pipeline accepts Web Streams as well.
  • new Response(readableStream) can send a stream as a response body in frameworks that use the fetch Response model (and undici).

Which to use

  • Shared code between browser and server, or code built around fetch and Response: Web Streams.
  • fs.createReadStream, sockets, process.stdin, existing libraries: Node streams. They are mature and often faster in Node.
  • Mixed: convert at the boundary, once.

Details

  • A TransformStream is simple: new TransformStream({ transform(chunk, controller) { controller.enqueue(...) } }).
  • A reader can be locked: a stream can have only one reader at a time. Use tee() to split.
  • CompressionStream('gzip') and 'deflate' are available (and 'brotli' in newer versions). They work on Uint8Array chunks.
  • Errors: cancel() and abort() propagate, and pipeTo rejects if a stage fails.
javascript
const { Readable, Writable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
const zlib = require('node:zlib');

async function collect(webStream) {
  const chunks = [];
  for await (const chunk of webStream) chunks.push(chunk);
  return Buffer.concat(chunks);
}

async function main() {
  // 1. A web ReadableStream built by hand, with a TransformStream in between.
  const source = new ReadableStream({
    start(controller) { ['node', 'web', 'streams'].forEach((w) => controller.enqueue(w)); controller.close(); },
  });
  const upper = new TransformStream({ transform(chunk, controller) { controller.enqueue(chunk.toUpperCase()); } });
  const words = [];
  for await (const word of source.pipeThrough(upper)) words.push(word);
  console.log('1. pipeThrough:', words.join(' '));

  // 2. Node Readable to Web ReadableStream and back
  const nodeReadable = Readable.from(['a', 'b', 'c']);
  const web = Readable.toWeb(nodeReadable);
  console.log('2. toWeb gives a ReadableStream:', web instanceof ReadableStream);
  const back = Readable.fromWeb(new ReadableStream({ start(c) { c.enqueue('x'); c.enqueue('y'); c.close(); } }), { objectMode: true });
  const pieces = [];
  await pipeline(back, new Writable({ objectMode: true, write(chunk, enc, cb) { pieces.push(chunk); cb(); } }));
  console.log('   fromWeb pieces:', pieces.join(','));

  // 3. CompressionStream and DecompressionStream, compared with zlib
  const text = 'hello hello hello hello';
  const gz = await collect(new Blob([text]).stream().pipeThrough(new CompressionStream('gzip')));
  console.log('3. zlib can read what CompressionStream wrote:', zlib.gunzipSync(gz).toString() === text);
  const unzipped = await collect(new Blob([zlib.gzipSync(text)]).stream().pipeThrough(new DecompressionStream('gzip')));
  console.log('   DecompressionStream can read what zlib wrote:', unzipped.toString() === text);

  // 4. A Response body is a web stream, and tee() makes two readers
  const response = new Response('shared body');
  const [one, two] = response.body.tee();
  console.log('4. tee gives both readers the same data:', (await collect(one)).toString() === (await collect(two)).toString());

  // 5. Only one reader at a time
  const locked = new ReadableStream({ start(c) { c.close(); } });
  locked.getReader();
  console.log('5. second reader ->', (() => { try { locked.getReader(); } catch (err) { return err.name; } })());
}
main();

The script builds web streams, converts between Web and Node streams, and checks that CompressionStream and zlib read each other's output. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. pipeThrough: NODE WEB STREAMS 2. toWeb gives a ReadableStream: true fromWeb pieces: x,y 3. zlib can read what CompressionStream wrote: true DecompressionStream can read what zlib wrote: true 4. tee gives both readers the same data: true 5. second reader -> TypeError

Key points

  • Web Streams are the standard API behind fetch and Response.
  • Node has the globals and async iteration over them.
  • Readable.fromWeb and toWeb convert between the two families.
  • Use Web Streams for shared browser and server code.
  • A web stream has one reader at a time; tee() splits it.

Common mistakes

  • Mixing both APIs in one pipeline without converting at the boundary.
  • Trying to read a web stream twice without tee().
  • Assuming chunks are always Buffers (they can be strings or Uint8Arrays).
  • Forgetting that a locked stream cannot get a second reader.
  • Using Web Streams for fs-heavy code without measuring.

Follow-ups

  • How does backpressure work in a ReadableStream?
  • How do you stream a fetch response to a file?
  • What is the difference between pipeTo and pipeThrough?

Tips

  • Say that fetch uses Web Streams.
  • Name fromWeb and toWeb.
  • Give a rule for which family to choose.
149.nodejs-0149Easyfresher

What are the common JSON.parse and JSON.stringify pitfalls in Node.js: errors, dates, big numbers, undefined, circular data and custom serialisation?

JSON.parse throws a SyntaxError on bad input, so wrap it in try/catch. JSON has no Date, undefined, function, NaN or BigInt types: dates become strings, undefined and functions are dropped from objects, NaN becomes null, and BigInt throws a TypeError. Numbers above 2^53 lose precision. Circular structures throw. Use toJSON, replacer and reviver functions, or string ids, to control the format.

Full answer

Parsing

  • JSON.parse(text) throws SyntaxError for invalid JSON (trailing commas, single quotes, comments, undefined). Parse untrusted text inside try/catch and validate the result (zod, ajv).
  • The reviver function (key, value) lets you convert values, for example ISO date strings back to Date objects.
  • JSON.parse does not cause prototype pollution on its own: a 'proto' key becomes an own property. Danger appears when you merge the result into other objects recursively.
  • Large JSON blocks the event loop, because parsing is synchronous. Use streaming or NDJSON for very large data.

Stringifying

  • Date objects use toJSON and become ISO strings. They come back as strings.
  • undefined, functions and symbols are omitted in objects and become null in arrays.
  • NaN and Infinity become null.
  • BigInt throws TypeError: Do not know how to serialize a BigInt. Convert to string (a replacer or BigInt.prototype.toJSON).
  • Map, Set and class instances become {} or plain data. Convert them first.
  • Circular references throw TypeError. Remove the cycle or use a replacer with a WeakSet. structuredClone copes with cycles but is not a JSON tool.
  • toJSON() on your class controls the output. The replacer (array or function) filters or changes fields. The third argument adds indentation.

Numbers

  • JSON numbers are parsed as IEEE double. An id like 9007199254740993 becomes 9007199254740992. Send large ids as strings.
  • For money, use integers (cents) or strings, not floats.

Practical rules: never build JSON by string concatenation, set Content-Type: application/json, and limit the request body size.

javascript
// 1. Parse errors
for (const text of ["{'a': 1}", '{"a": 1,}', '', 'undefined']) {
  try { JSON.parse(text); } catch (err) { console.log('1. parse', JSON.stringify(text).padEnd(11), '->', err.name); }
}

// 2. What stringify does to special values
const data = { date: new Date(Date.UTC(2026, 11, 4)), missing: undefined, run() {}, nan: NaN, inf: Infinity, list: [undefined, () => {}], set: new Set([1]), map: new Map([['a', 1]]) };
console.log('2.', JSON.stringify(data));

// 3. Dates come back as strings, unless a reviver converts them
const roundTrip = JSON.parse(JSON.stringify({ at: new Date(Date.UTC(2026, 11, 4)) }));
console.log('3. typeof after round trip:', typeof roundTrip.at);
const revived = JSON.parse(JSON.stringify({ at: new Date(Date.UTC(2026, 11, 4)) }), (key, value) => (key === 'at' ? new Date(value) : value));
console.log('   with a reviver:', revived.at instanceof Date);

// 4. BigInt and big numbers
try { JSON.stringify({ id: 12n }); } catch (err) { console.log('4. BigInt ->', err.name); }
console.log('   BigInt as string:', JSON.stringify({ id: 12n }, (key, value) => (typeof value === 'bigint' ? value.toString() : value)));
console.log('   9007199254740993 parsed as', JSON.parse('{"id":9007199254740993}').id);

// 5. Circular data
const a = { name: 'a' }; a.self = a;
try { JSON.stringify(a); } catch (err) { console.log('5. circular ->', err.name); }

// 6. toJSON and a replacer that hides a secret
class User {
  constructor() { this.name = 'Asha'; this.password = 'secret'; }
  toJSON() { return { name: this.name }; }
}
console.log('6. toJSON:', JSON.stringify(new User()), '| replacer:', JSON.stringify({ a: 1, token: 'x' }, (k, v) => (k === 'token' ? undefined : v)));

// 7. __proto__ in parsed JSON is just data
const parsed = JSON.parse('{"__proto__": {"admin": true}}');
console.log('7. polluted a fresh object:', ({}).admin === true, '| own key:', Object.keys(parsed).join(','));

Each numbered line shows one pitfall with real output. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. parse "{'a': 1}" -> SyntaxError 1. parse "{\"a\": 1,}" -> SyntaxError 1. parse "" -> SyntaxError 1. parse "undefined" -> SyntaxError 2. {"date":"2026-12-04T00:00:00.000Z","nan":null,"inf":null,"list":[null,null],"set":{},"map":{}} 3. typeof after round trip: string with a reviver: true 4. BigInt -> TypeError BigInt as string: {"id":"12"} 9007199254740993 parsed as 9007199254740992 5. circular -> TypeError 6. toJSON: {"name":"Asha"} | replacer: {"a":1} 7. polluted a fresh object: false | own key: __proto__

Key points

  • JSON.parse throws, so use try/catch and validate.
  • Dates become strings, undefined is dropped, NaN becomes null.
  • BigInt throws, and integers above 2^53 lose precision.
  • Circular structures throw.
  • toJSON, replacer and reviver control the format.

Common mistakes

  • Passing user text to JSON.parse without try/catch.
  • Sending 64-bit ids as JSON numbers.
  • Expecting Date objects after a round trip.
  • Logging objects with passwords through JSON.stringify without a filter.
  • Building JSON strings by hand.

Follow-ups

  • How would you serialise a Map or a Set?
  • How does structuredClone differ from JSON for copying?
  • How do you protect an API from huge JSON bodies?

Tips

  • List what stringify drops or changes.
  • Mention the 2^53 limit.
  • Say 'try/catch and validate'.
150.nodejs-0150Hardsenior

How do you propagate request cancellation and deadlines in a Node.js service so that work stops when the client leaves or time runs out?

Create an AbortController per request. Abort it when the client connection closes before the response finished, and combine it with AbortSignal.timeout(deadline) using AbortSignal.any. Pass the signal to fetch, database drivers that support it, timers and streams. Return 504 when the deadline passes, and pass the remaining time to downstream calls, so work that nobody waits for stops.

Full answer

The problem

  • A client closes the tab, a mobile network drops, or a gateway times out after 30 seconds. Without cancellation, the server keeps doing the work: database queries, calls to other services, expensive computation. Under load, this wasted work makes the overload worse.
  • Slow downstream calls without a timeout hold the request open and use sockets and memory.

The approach

  1. Create one AbortController per incoming request.
  2. Abort it when the response is closed before it finished: res.on('close', () => { if (!res.writableFinished) controller.abort() }). (The 'close' event of res fires on finish too, so check writableFinished.)
  3. Add a deadline: AbortSignal.timeout(ms). Combine with AbortSignal.any([closeSignal, timeoutSignal]) so either one cancels the work.
  4. Pass the signal to everything that can use it: fetch(url, { signal }), timers/promises (setTimeout with signal), streams and pipeline, fs.promises functions, and database drivers with cancellation support (pg does not cancel a running query through a signal, so use statement_timeout and query_timeout there).
  5. When the signal aborts, stop early and return quickly. Send 504 Gateway Timeout for a deadline, and do not try to write to a closed connection.
  6. Propagate the deadline: send the remaining time to downstream services in a header (for example X-Request-Timeout or gRPC deadlines), and subtract a margin. Each hop should wait less than its caller.

Design points

  • Choose timeouts per dependency, smaller than the user-facing timeout.
  • Retries must respect the overall deadline.
  • Cancellation is cooperative. Code that ignores the signal keeps running. CPU loops need to check signal.aborted.
  • Log cancelled requests at a low level, because client aborts are normal.
  • Combine with load shedding and circuit breakers for a service that degrades gracefully.
javascript
const http = require('node:http');
const express = require('express');
const { setTimeout: sleep } = require('node:timers/promises');

// A slow downstream service that notices when its caller goes away.
let downstreamAborted = 0;
const downstream = http.createServer((req, res) => {
  const timer = setTimeout(() => res.end('downstream result'), 500);
  res.on('close', () => { if (!res.writableFinished) { clearTimeout(timer); downstreamAborted++; } });
});

function deadline(ms) {
  return (req, res, next) => {
    const closed = new AbortController();
    res.on('close', () => { if (!res.writableFinished) closed.abort(new Error('client went away')); });
    const started = Date.now();
    res.locals.signal = AbortSignal.any([closed.signal, AbortSignal.timeout(ms)]);
    res.locals.remainingMs = () => Math.max(0, ms - (Date.now() - started));
    next();
  };
}

downstream.listen(0, '127.0.0.1', () => {
  const downstreamUrl = 'http://127.0.0.1:' + downstream.address().port;
  const app = express();
  app.get('/report', deadline(200), async (req, res) => {
    try {
      const response = await fetch(downstreamUrl + (req.query.fast ? '/fast' : ''), { signal: res.locals.signal });
      res.send(await response.text());
    } catch (err) {
      if (res.writableEnded || res.destroyed) return;                        // the client already left
      res.status(err.name === 'TimeoutError' ? 504 : 500).json({ error: err.name });
    }
  });
  app.get('/quick', deadline(200), async (req, res) => {
    await sleep(20, null, { signal: res.locals.signal });
    res.json({ ok: true, deadlineRemainingIsLessThan200: res.locals.remainingMs() < 200 });
  });

  const server = app.listen(0, '127.0.0.1', async () => {
    const base = 'http://127.0.0.1:' + server.address().port;

    // 1. The deadline (200 ms) passes before the downstream answers (500 ms).
    const slow = await fetch(base + '/report');
    console.log('1. deadline exceeded ->', slow.status, JSON.stringify(await slow.json()));
    await sleep(50);
    console.log('   downstream request was cancelled:', downstreamAborted === 1);

    // 2. The client gives up after 50 ms.
    downstreamAborted = 0;
    const clientAbort = new AbortController();
    setTimeout(() => clientAbort.abort(), 50);
    await fetch(base + '/report', { signal: clientAbort.signal }).catch((err) => console.log('2. client aborted ->', err.name));
    await sleep(100);
    console.log('   downstream request was cancelled:', downstreamAborted === 1);

    // 3. A quick request is unaffected.
    console.log('3. quick request ->', JSON.stringify(await (await fetch(base + '/quick')).json()));

    server.close(); downstream.close();
  });
});

A slow downstream service sees its request cancelled both when the deadline expires and when the client disconnects. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. deadline exceeded -> 504 {"error":"TimeoutError"} downstream request was cancelled: true 2. client aborted -> AbortError downstream request was cancelled: true 3. quick request -> {"ok":true,"deadlineRemainingIsLessThan200":true}

Key points

  • Abort work when the client leaves or the deadline passes.
  • Use AbortSignal.any to combine close and timeout signals.
  • Pass the signal to fetch, timers, streams and fs calls.
  • Cancellation is cooperative; CPU loops must check the signal.
  • Propagate the remaining time to downstream services.

Common mistakes

  • Letting work continue after the client has gone.
  • Calling downstream services with no timeout.
  • Checking the 'close' event of res without checking writableFinished.
  • Retrying until success and ignoring the overall deadline.
  • Assuming a signal stops CPU-bound code by itself.

Follow-ups

  • How does a circuit breaker work together with deadlines?
  • How do you pass the deadline to another service?
  • Why do pg queries need statement_timeout when an AbortSignal exists?

Tips

  • Describe the wasted-work problem first.
  • Name AbortSignal.any.
  • Say that cancellation is cooperative.
151.nodejs-0151Hardsenior

How would you design and implement a URL shortener API in Node.js: id generation, redirects, validation and scaling?

Store a mapping from a short code to a long URL. Generate codes by encoding a unique counter in base62 (no collisions, short), or random codes with a retry on conflict. Validate that the target is an http or https URL, redirect with 301 or 302, and make reads fast with a cache because reads far outnumber writes. Scale with a shared id generator, a replicated store, a cache and rate limits on creation.

Full answer

Requirements to confirm first: how many links per day, how long they live, custom aliases, analytics, and the read to write ratio (often 100 to 1 or more).

API

  • POST /links with { url, alias? } returns 201, { code, shortUrl }. Creating the same URL twice may return the same code (idempotent) or a new one.
  • GET /:code answers with a redirect: 301 is cached by browsers (fast, but you lose click counts and cannot change the target), 302 or 307 is not cached (better for analytics and edits).
  • 404 for unknown codes, 409 for an alias that exists, 400 for bad input.

Code generation

  • Counter plus base62 (0-9, a-z, A-Z): 7 characters give about 3.5 trillion values. No collisions, but codes are guessable in order. Add an offset or shuffle bits if guessing matters.
  • Random codes (for example 7 random base62 characters): not guessable, but need a unique-constraint check and a retry when a collision happens.
  • A distributed counter: a database sequence, or each app instance takes a block of ids (for example 1000) from a central counter.

Safety

  • Accept only http and https schemes, limit length, and block internal addresses (see the SSRF item) if you fetch titles.
  • Rate limit creation per user or IP, and check abuse (phishing) with a block list.

Scaling reads

  • Cache code to URL in Redis or in memory with a TTL, put a CDN in front for 301 responses, and keep the database as the source of truth with an index on the code.
  • Count clicks asynchronously (queue or batch) so redirects stay fast.
javascript
const http = require('node:http');

const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function toBase62(n) {
  let out = '';
  do { out = ALPHABET[n % 62] + out; n = Math.floor(n / 62); } while (n > 0);
  return out;
}

const byCode = new Map();      // code -> { url, clicks }
const byUrl = new Map();       // url -> code (same URL gives the same code)
let counter = 1_000_000;       // start at one million so the first codes are not one character

function create(url, alias) {
  let parsed;
  try { parsed = new URL(url); } catch { return { status: 400, error: 'invalid url' }; }
  if (!['http:', 'https:'].includes(parsed.protocol)) return { status: 400, error: 'only http and https are allowed' };
  if (alias) {
    if (!/^[A-Za-z0-9_-]{3,30}$/.test(alias)) return { status: 400, error: 'bad alias' };
    if (byCode.has(alias)) return { status: 409, error: 'alias taken' };
    byCode.set(alias, { url: parsed.href, clicks: 0 });
    return { status: 201, code: alias };
  }
  if (byUrl.has(parsed.href)) return { status: 200, code: byUrl.get(parsed.href) };
  const code = toBase62(counter++);
  byCode.set(code, { url: parsed.href, clicks: 0 }); byUrl.set(parsed.href, code);
  return { status: 201, code };
}

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/links') {
    let body = '';
    req.on('data', (c) => { body += c; if (body.length > 2048) req.destroy(); });
    req.on('end', () => {
      let input = {};
      try { input = JSON.parse(body); } catch {}
      const result = create(input.url, input.alias);
      res.writeHead(result.status, { 'content-type': 'application/json' }).end(JSON.stringify(result));
    });
    return;
  }
  const entry = byCode.get(req.url.slice(1));
  if (!entry) return res.writeHead(404).end();
  entry.clicks++;                                   // a real service would count asynchronously
  res.writeHead(302, { Location: entry.url }).end();
});

server.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const post = async (body) => { const r = await fetch(base + '/links', { method: 'POST', body: JSON.stringify(body) }); return [r.status, await r.json()]; };

  const [s1, a] = await post({ url: 'https://example.com/a/very/long/path?x=1' });
  console.log('create ->', s1, JSON.stringify(a), '| code length:', a.code.length);
  const [s2, b] = await post({ url: 'https://example.com/a/very/long/path?x=1' });
  console.log('same URL again ->', s2, 'same code:', b.code === a.code);
  console.log('alias ->', (await post({ url: 'https://example.org', alias: 'school' }))[0], '| alias again ->', (await post({ url: 'https://example.net', alias: 'school' }))[0]);
  console.log('javascript: URL ->', (await post({ url: 'javascript:alert(1)' }))[0], '| not a URL ->', (await post({ url: 'hello' }))[0]);

  const redirect = await fetch(base + '/' + a.code, { redirect: 'manual' });
  console.log('redirect ->', redirect.status, redirect.headers.get('location'));
  console.log('unknown code ->', (await fetch(base + '/nope', { redirect: 'manual' })).status, '| clicks counted:', byCode.get(a.code).clicks);
  console.log('base62 of 3844 (62 squared):', toBase62(3844));
  server.close();
});

A small in-memory service handles creation, aliases, bad schemes and redirects. A real service replaces the Maps with a database and a cache. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): create -> 201 {"status":201,"code":"4c92"} | code length: 4 same URL again -> 200 same code: true alias -> 201 | alias again -> 409 javascript: URL -> 400 | not a URL -> 400 redirect -> 302 https://example.com/a/very/long/path?x=1 unknown code -> 404 | clicks counted: 1 base62 of 3844 (62 squared): 100

Key points

  • Counter plus base62 gives short collision-free codes.
  • 301 is cached by browsers, 302 keeps control and analytics.
  • Validate the scheme and rate limit creation.
  • Reads dominate, so cache them.
  • Count clicks asynchronously.

Common mistakes

  • Using 301 and then being unable to change or count a link.
  • Accepting javascript: or file: URLs.
  • Random codes with no unique constraint or retry.
  • Hashing the URL and truncating it, which causes collisions.
  • No rate limit on link creation.

Follow-ups

  • How do you generate ids across several app instances?
  • How would you expire links or let owners delete them?
  • How would you store click analytics at high volume?

Tips

  • Ask about read to write ratio first.
  • Compare counter and random codes.
  • Mention 301 versus 302.
152.nodejs-0152Hardsenior

How do you build a rate limiter for a public API that works across several Node.js instances, and how do you report limits to clients?

An in-memory limiter is per instance, so the real limit grows with the number of instances. Keep the counters in Redis and make the check-and-update atomic with a Lua script (a token bucket or a window counter). Key by API key or user first and IP second, answer 429 with Retry-After and rate limit headers, and decide what to do when Redis is down (usually fail open with an alert).

Full answer

Why Redis

  • With three instances and an in-memory limit of 100 per minute, a client can send up to 300. A shared store gives one counter.
  • A read followed by a write from several instances is a race. A Lua script runs atomically inside Redis, so check and update happen as one step.

Algorithms

  • Fixed window: INCR a key per window and set EXPIRE. Simple, but allows a burst of 2x the limit across a window boundary.
  • Sliding window log or counter: smoother, more memory or math.
  • Token bucket: a bucket of N tokens refills at a steady rate. It allows short bursts and limits the average. Store tokens and the last refill time; compute the refill on each request using Redis TIME so instance clocks do not matter.

API behaviour

  • Respond 429 Too Many Requests with Retry-After (seconds). Add RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers (the standard is still a work in progress at the IETF, so some APIs use X-RateLimit-*).
  • Identify callers by API key or user id. Use IP as a fallback, and remember that many users can share one IP (NAT) and that X-Forwarded-For can be faked unless your proxy sets it.
  • Different limits per plan and per route (login attempts need much stricter limits than reads).
  • Expire keys so memory is bounded.

Failure policy

  • If Redis is unavailable: fail open (allow, log, alert) for normal routes, fail closed for dangerous ones (login, payment). Use a short timeout so Redis problems do not slow all requests.
  • Add a small local limiter as a second layer for abuse spikes.

Test: parallel requests from several clients, clock changes, and expiry of idle keys.

javascript
const Redis = require('ioredis');

const redis = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
const prefix = `rl-demo:${process.pid}:`;

// Token bucket in Lua: KEYS[1] = bucket, ARGV = capacity, refill tokens per second, cost
redis.defineCommand('takeToken', {
  numberOfKeys: 1,
  lua: `
    local capacity = tonumber(ARGV[1])
    local rate = tonumber(ARGV[2])
    local now = redis.call('TIME')
    local nowMs = now[1] * 1000 + math.floor(now[2] / 1000)
    local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
    local tokens = tonumber(state[1]) or capacity
    local ts = tonumber(state[2]) or nowMs
    tokens = math.min(capacity, tokens + (nowMs - ts) * rate / 1000)
    local allowed = 0
    local retryMs = 0
    if tokens >= 1 then
      tokens = tokens - 1
      allowed = 1
    else
      retryMs = math.ceil((1 - tokens) * 1000 / rate)
    end
    redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', nowMs)
    redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
    return { allowed, math.floor(tokens), retryMs }
  `,
});

async function limit(apiKey) {
  const [allowed, remaining, retryMs] = await redis.takeToken(prefix + apiKey, 5, 1);   // burst 5, refill 1 per second
  return { allowed: allowed === 1, remaining, retryAfterSeconds: Math.ceil(retryMs / 1000) };
}

async function main() {
  const results = [];
  for (let i = 0; i < 8; i++) results.push(await limit('key-A'));
  console.log('key-A:', results.map((r) => (r.allowed ? 'ok(' + r.remaining + ')' : 'DENIED')).join(' '));
  console.log('Retry-After for the denied requests:', [...new Set(results.filter((r) => !r.allowed).map((r) => r.retryAfterSeconds))].join(','), 'second(s)');
  console.log('key-B has its own bucket:', (await limit('key-B')).allowed);

  // Parallel requests share the same atomic bucket (as if they came from different instances).
  const parallel = await Promise.all(Array.from({ length: 20 }, () => limit('key-C')));
  console.log('20 parallel requests, allowed:', parallel.filter((r) => r.allowed).length, '(capacity is 5)');

  const keys = await redis.keys(prefix + '*');
  const ttl = await redis.pttl(keys[0]);
  console.log('buckets expire by themselves:', ttl > 0);
  await redis.del(...keys);
  await redis.quit();
}
main();

The Lua script runs inside Redis. The script needs a running Redis server and shows a burst of 5, the denial after it, and 20 parallel requests sharing one bucket. Install first with npm install ioredis (run here with ioredis 6.1.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): key-A: ok(4) ok(3) ok(2) ok(1) ok(0) DENIED DENIED DENIED Retry-After for the denied requests: 1 second(s) key-B has its own bucket: true 20 parallel requests, allowed: 5 (capacity is 5) buckets expire by themselves: true

Key points

  • An in-memory limiter multiplies the limit by the instance count.
  • A Lua script makes check and update atomic.
  • Token bucket allows bursts and limits the average rate.
  • Return 429 with Retry-After and rate limit headers.
  • Choose fail open or fail closed per route.

Common mistakes

  • Using an in-memory limiter on several instances.
  • Reading the count and writing it back in two separate commands.
  • Trusting X-Forwarded-For from any client.
  • No Retry-After, so clients retry immediately.
  • Using the same limit for login and for read endpoints.

Follow-ups

  • Why is a fixed window limiter allowed to burst to twice the limit?
  • How would you rate limit by user and by IP at the same time?
  • What happens to your service if Redis is slow?

Tips

  • Start with 'in-memory limits multiply by instance count'.
  • Say that Lua makes the step atomic.
  • State the fail-open decision.
153.nodejs-0153Hardsenior

How would you design a file processing pipeline (parse, transform, store) in Node.js with bounded concurrency per stage, ordered output and backpressure?

Chain async generator stages. Each stage keeps at most N items in flight, yields results in the original order, and pulls from the previous stage only when it has room, so a slow stage slows the source instead of growing a queue. Size each stage by its resource (CPU, network, disk), and at the system level add a durable queue, retries, idempotent writes and a dead letter store.

Full answer

Pipeline thinking

  • Break the work into stages with different limits. For example parse (CPU, small), resize (CPU heavy, 2 at a time), upload (network, 3 at a time).
  • Every stage needs a bound. Without it a fast source loads thousands of files into memory while the slow stage works.
  • Backpressure comes from the pull model. An async generator stage calls next() on its source only when it has capacity, so pressure flows back to the beginning.
  • Ordering: if the output must keep input order, wait for results in order while later items run in parallel. If order does not matter, take results as they finish (higher throughput).

Inside one process

  • A helper mapOrdered(source, fn, limit) keeps a small array of in-flight promises. It fills the array, awaits the first one, yields it, and refills.
  • Use worker threads for CPU stages and a limit near the core count.
  • Streams (Transform) work too. Object mode streams have highWaterMark in objects.

At system level (design interview)

  • A durable queue between stages (SQS, BullMQ, Kafka) so a crash does not lose work. Workers are separate processes that scale independently.
  • Store the state of every file (pending, processing, done, failed) in a database, with an idempotency key so retries do not duplicate results.
  • Retry with backoff, then a dead letter queue. Keep poison files from blocking the line.
  • Big files go to object storage first, and the queue carries only the key.
  • Metrics: queue length, age of the oldest item, time per stage, failure rate.
javascript
const { setTimeout: sleep } = require('node:timers/promises');

// Runs fn on up to `limit` items at once, but yields the results in input order.
async function* mapOrdered(source, fn, limit) {
  const iterator = source[Symbol.asyncIterator]();
  const inFlight = [];
  let finished = false;
  async function fill() {
    while (!finished && inFlight.length < limit) {
      const next = await iterator.next();
      if (next.done) { finished = true; break; }
      const promise = fn(next.value);
      promise.catch(() => {});               // the error is reported when the result is awaited
      inFlight.push(promise);
    }
  }
  await fill();
  while (inFlight.length) {
    yield await inFlight.shift();
    await fill();
  }
}

const stats = {};
function stage(name, limit, delayFor) {
  stats[name] = { running: 0, max: 0, limit };
  return (source) => mapOrdered(source, async (file) => {
    const s = stats[name];
    s.max = Math.max(s.max, ++s.running);
    await sleep(delayFor(file.id));               // pretend work
    s.running--;
    return { ...file, [name]: true };
  }, limit);
}

let produced = 0, consumed = 0, maxAhead = 0;
async function* files() {
  for (let id = 1; id <= 12; id++) {
    produced++;
    maxAhead = Math.max(maxAhead, produced - consumed);
    yield { id };
  }
}

async function main() {
  const parse = stage('parse', 4, (id) => 5 + (id % 3) * 4);
  const resize = stage('resize', 2, (id) => 30 - (id % 4) * 6);    // the slow stage
  const store = stage('store', 3, (id) => 5 + (id % 2) * 8);

  const order = [];
  for await (const file of store(resize(parse(files())))) { consumed++; order.push(file.id); }

  console.log('output order:', order.join(','));
  console.log('in input order:', order.every((id, i) => id === i + 1));
  for (const [name, s] of Object.entries(stats)) console.log(name.padEnd(7), 'limit', s.limit, '| never above the limit:', s.max <= s.limit, '| reached it:', s.max === s.limit);
  console.log('source was read at most', maxAhead, 'items ahead of the final consumer (12 files in total)');
}
main();

Twelve files pass through three stages with limits 4, 2 and 3. The output stays in order, no stage goes above its limit, and the source never runs far ahead of the slowest stage. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): output order: 1,2,3,4,5,6,7,8,9,10,11,12 in input order: true parse limit 4 | never above the limit: true | reached it: true resize limit 2 | never above the limit: true | reached it: true store limit 3 | never above the limit: true | reached it: true source was read at most 7 items ahead of the final consumer (12 files in total)

Key points

  • Each stage needs its own concurrency bound.
  • Pulling from the source only when there is room gives backpressure.
  • Keeping order means awaiting results in order while work runs in parallel.
  • Use workers for CPU stages.
  • A durable queue and idempotent writes make it survive crashes.

Common mistakes

  • No limit on a stage, so memory grows with the input.
  • Using Promise.all on the whole input list.
  • Losing order when the output must match the input.
  • Retrying inside the stage without an idempotent write.
  • Running CPU-heavy stages on the main thread.

Follow-ups

  • How would you handle one file that always fails?
  • How do you choose the limit for each stage?
  • How would the design change if the files are 10 GB each?

Tips

  • Draw the stages with their limits.
  • Say 'pull model gives backpressure'.
  • Finish with the durable queue and idempotency.
154.nodejs-0154Hardsenior

How would you design a notification service (email, SMS, push) with user preferences, deduplication, retries and provider fallback?

Callers publish an event, not a message. The service looks up the user's preferences and quiet hours, renders a template per channel, writes a record with an idempotency key (so duplicates are dropped), and sends through a queue so each channel scales and retries on its own. Providers are wrapped behind one interface with timeouts, retries with backoff and a fallback provider, and delivery status flows back by webhook.

Full answer

Flow

  1. Producer calls POST /notifications with { userId, type, data, idempotencyKey }. Return 202 Accepted quickly.
  2. The service checks the idempotency key (unique constraint), loads preferences (channels per notification type, language, quiet hours, opt-outs), and creates one delivery record per channel.
  3. Each delivery goes to a channel queue (email, sms, push). Separate queues stop a slow SMS provider from delaying email.
  4. A channel worker renders the template, calls the provider, and updates the record (queued, sent, delivered, failed).
  5. Providers send delivery receipts and bounces by webhook, which update the status and the suppression list.

Reliability

  • At-least-once delivery means duplicates are possible, so use provider idempotency keys where they exist and a unique key on (notificationId, channel).
  • Retry transient errors with backoff and jitter, give up after N attempts, and move to a dead letter queue. Do not retry permanent errors (invalid number, hard bounce).
  • Provider fallback: when provider A fails or times out, try provider B. Use a circuit breaker so you stop calling a provider that is down.
  • Rate limits per provider and per user (do not send 50 pushes in a minute). Batch low priority messages into a digest.

Compliance and quality

  • Respect opt-out and legal rules (unsubscribe links, consent, quiet hours in the user's time zone). Critical alerts (security, payment) bypass marketing preferences but not legal blocks.
  • Store minimal personal data, mask it in logs, and keep an audit trail.
  • Templates with versioning and tests, and a sandbox mode for staging.

Metrics: queue age per channel, send success rate per provider, time to deliver, bounce and complaint rates.

javascript
// Teaching sketch: the decision logic of a notification service, with fake providers and a fake clock.
const preferences = {
  asha: { channels: { security: ['push', 'email'], marketing: ['email'] }, quietHours: [22, 7], timezoneOffsetHours: 0 },
  ravi: { channels: { security: ['sms'], marketing: [] }, quietHours: [22, 7], timezoneOffsetHours: 0 },
};
const seen = new Set();                         // idempotency keys
const log = [];

const providers = {
  push: async () => { throw Object.assign(new Error('push provider down'), { transient: true }); },
  email: async (to) => `email sent to ${to}`,
  sms: async (to) => `sms sent to ${to}`,
};
const fallbackFor = { push: 'email' };           // if push fails, try email

function inQuietHours(user, hour) {
  const [from, to] = user.quietHours;
  return from > to ? (hour >= from || hour < to) : (hour >= from && hour < to);
}

async function notify({ userId, type, key, hour }) {
  if (seen.has(key)) return log.push(`${key}: duplicate ignored`);
  seen.add(key);
  const user = preferences[userId];
  const channels = user.channels[type];
  if (!channels.length) return log.push(`${key}: user opted out of ${type}`);
  if (type === 'marketing' && inQuietHours(user, hour)) return log.push(`${key}: held until quiet hours end`);

  for (const channel of channels) {
    let used = channel;
    try {
      log.push(`${key}: ${await providers[channel](userId)}`);
    } catch (err) {
      const fallback = fallbackFor[channel];
      if (err.transient && fallback) {
        used = fallback;
        log.push(`${key}: ${channel} failed, fallback -> ${await providers[fallback](userId)}`);
      } else log.push(`${key}: ${channel} failed for good`);
    }
  }
}

(async () => {
  await notify({ userId: 'asha', type: 'security', key: 'n1', hour: 12 });
  await notify({ userId: 'asha', type: 'security', key: 'n1', hour: 12 });       // same key again
  await notify({ userId: 'asha', type: 'marketing', key: 'n2', hour: 23 });      // quiet hours
  await notify({ userId: 'asha', type: 'marketing', key: 'n3', hour: 10 });
  await notify({ userId: 'ravi', type: 'marketing', key: 'n4', hour: 10 });      // opted out
  await notify({ userId: 'ravi', type: 'security', key: 'n5', hour: 3 });        // security ignores quiet hours
  console.log(log.join('\n'));
})();

This is a teaching sketch of the decisions (idempotency, opt-out, quiet hours, fallback). Queues, templates and real providers are not included. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): n1: push failed, fallback -> email sent to asha n1: email sent to asha n1: duplicate ignored n2: held until quiet hours end n3: email sent to asha n4: user opted out of marketing n5: sms sent to ravi

Key points

  • Publish events, then resolve preferences and channels in the service.
  • An idempotency key and unique records stop duplicates.
  • One queue per channel isolates slow providers.
  • Retry transient errors, fall back to another provider, dead letter the rest.
  • Respect opt-outs and quiet hours.

Common mistakes

  • Sending synchronously inside the request that triggered the event.
  • No idempotency key, so a retry sends the message twice.
  • One shared queue for all channels.
  • Ignoring unsubscribes and time zones.
  • Retrying permanent failures such as an invalid number.

Follow-ups

  • How would you send a daily digest instead of many messages?
  • How do delivery receipts update the status?
  • How do you prevent a notification storm after an outage?

Tips

  • Walk through the flow in five steps.
  • Name idempotency and fallback.
  • Mention quiet hours and opt-outs.
155.nodejs-0155Easyfresher

What is the difference between server-side sessions and JWTs for authentication, and which is easier to revoke?

A session keeps the user's state on the server and gives the browser an opaque id in a cookie. A JWT is a signed token that carries the claims itself, so the server stores nothing. Sessions are easy to revoke (delete the record). A JWT stays valid until it expires unless you add a block list, so use short lifetimes. Sessions suit browser apps, JWTs suit APIs across services.

Full answer

Sessions

  • Login creates a record in a store (memory for demos, Redis or a database in production) and sends Set-Cookie with a random session id (HttpOnly, Secure, SameSite).
  • Each request carries the cookie, the server looks up the record. Logout, password change or admin action deletes the record, and access ends immediately.
  • Cost: a store lookup per request, and a shared store when you run several instances.

JWT (JSON Web Token)

  • Three base64url parts: header, payload (claims such as sub and exp), signature. The server verifies the signature and the expiry, no lookup needed.
  • Good for stateless APIs, service to service calls and short-lived access tokens.
  • Problems: you cannot revoke a token before exp without extra state (a deny list or a token version number), the payload is readable by anyone (do not store secrets), tokens in localStorage are exposed to XSS, and a leaked token works anywhere until it expires.

How to choose

  • Traditional web app with a browser: server sessions in an HttpOnly cookie are simpler and safer.
  • Mobile or third-party API clients, microservices: short-lived JWT access token (5 to 15 minutes) plus a refresh token that the server can revoke.
  • Avoid using JWT only because it feels modern. Stateless tokens trade revocation for scalability.

In both cases: use HTTPS, rotate secrets, set short lifetimes, and protect cookies against CSRF.

javascript
const express = require('express');
const session = require('express-session');
const jwt = require('jsonwebtoken');

const SECRET = 'demo-secret-change-me';
const app = express();
app.use(express.json());
app.use(session({ secret: SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax' } }));

// Session login and a protected route
app.post('/session/login', (req, res) => { req.session.user = 'asha'; res.json({ ok: true }); });
app.get('/session/me', (req, res) => (req.session.user ? res.json({ user: req.session.user }) : res.status(401).json({ error: 'not logged in' })));
app.post('/session/logout', (req, res) => req.session.destroy(() => res.json({ ok: true })));

// JWT login and a protected route
app.post('/jwt/login', (req, res) => res.json({ token: jwt.sign({ sub: 'asha' }, SECRET, { expiresIn: '15m' }) }));
app.get('/jwt/me', (req, res) => {
  try { res.json({ user: jwt.verify((req.get('authorization') || '').replace('Bearer ', ''), SECRET).sub }); }
  catch { res.status(401).json({ error: 'invalid token' }); }
});
app.post('/jwt/logout', (req, res) => res.json({ ok: true, note: 'the server has nothing to delete' }));

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const call = async (path, headers = {}, method = 'GET') => { const r = await fetch(base + path, { method, headers }); return r; };

  const login = await call('/session/login', {}, 'POST');
  const cookie = login.headers.get('set-cookie').split(';')[0];
  console.log('session cookie flags:', /HttpOnly/i.test(login.headers.get('set-cookie')), /SameSite=Lax/i.test(login.headers.get('set-cookie')));
  console.log('session /me before logout:', (await call('/session/me', { cookie })).status);
  await call('/session/logout', { cookie }, 'POST');
  console.log('session /me after logout :', (await call('/session/me', { cookie })).status, '(revoked at once)');

  const { token } = await (await call('/jwt/login', {}, 'POST')).json();
  console.log('jwt payload is readable by anyone:', JSON.parse(Buffer.from(token.split('.')[1], 'base64url')).sub);
  console.log('jwt /me before logout    :', (await call('/jwt/me', { authorization: 'Bearer ' + token })).status);
  await call('/jwt/logout', {}, 'POST');
  console.log('jwt /me after logout     :', (await call('/jwt/me', { authorization: 'Bearer ' + token })).status, '(still valid until it expires)');
  server.close();
});

The same user logs in with a session and with a JWT and then logs out. The session stops working at once, the JWT keeps working. Install first with npm install express express-session jsonwebtoken (run here with express 5.3.0, express-session 1.19.0, jsonwebtoken 9.0.3). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): session cookie flags: true true session /me before logout: 200 session /me after logout : 401 (revoked at once) jwt payload is readable by anyone: asha jwt /me before logout : 200 jwt /me after logout : 200 (still valid until it expires)

Key points

  • A session stores state on the server; a JWT carries signed claims.
  • Deleting the session revokes access at once.
  • A JWT is valid until it expires unless extra state is kept.
  • Use HttpOnly, Secure, SameSite cookies for browser sessions.
  • Short access tokens plus revocable refresh tokens suit APIs.

Common mistakes

  • Choosing JWT for a simple browser app and then needing revocation.
  • Storing a JWT in localStorage where XSS can read it.
  • Putting secrets in the JWT payload.
  • Long-lived access tokens with no refresh strategy.
  • Using MemoryStore for sessions in production.

Follow-ups

  • How do you revoke a JWT before it expires?
  • Where should a browser app keep a token?
  • Why do sessions need a shared store when you scale out?

Tips

  • Define both in one sentence each.
  • Say 'revocation' as the key difference.
  • Give a rule of thumb for choosing.
156.nodejs-0156Easyfresher

How do you verify a JWT correctly in Node.js: algorithm allowlist, expiry, issuer and audience, and what is the 'alg none' attack?

jwt.verify checks the signature and the standard claims, but you must pass the algorithms you accept, plus the issuer and audience you expect. Without an allowlist, an attacker can forge a token with alg none or switch a public key algorithm to HMAC. jwt.decode only reads the payload and verifies nothing. Keep access tokens short, use strong secrets or key pairs, and handle TokenExpiredError separately.

Full answer

Verify, do not decode

  • jwt.decode(token) returns the payload without checking anything. Never use it to make a security decision.
  • jwt.verify(token, secretOrKey, options) checks the signature, exp (expiry), nbf (not before), and the options you pass.

Options that matter

  • algorithms: ['HS256'] (or ['RS256'] for public key setups). If you leave it out, the library decides from the header, which the attacker controls. The old attacks: alg none (a token with no signature) and algorithm confusion (a token signed with HMAC using the public key as the secret).
  • issuer and audience: check that the token was made by your auth service for your API. Tokens from another system with the same secret should not work.
  • clockTolerance of a few seconds helps with small clock differences.
  • maxAge as an extra limit on token age.

Good practice

  • Use a long random secret for HS256 (32 bytes or more) from the environment, or an asymmetric key pair (RS256, ES256, EdDSA) so that other services can verify without being able to sign. Publish public keys through a JWKS endpoint and use a kid header for rotation.
  • Short expiry (5 to 15 minutes).
  • Return the same 401 for all verification failures. Log the specific error internally (TokenExpiredError, JsonWebTokenError, NotBeforeError).
  • Do not put sensitive data in the payload; it is only encoded.
  • Libraries: jsonwebtoken, jose (also supports Web Crypto and JWKS helpers).
javascript
const jwt = require('jsonwebtoken');
const crypto = require('node:crypto');

const secret = crypto.randomBytes(32).toString('hex');
const options = { algorithms: ['HS256'], issuer: 'school-auth', audience: 'school-api' };
const check = (label, token, opts = options, key = secret) => {
  try { console.log(label.padEnd(24), 'OK', JSON.stringify(jwt.verify(token, key, opts).sub)); }
  catch (err) { console.log(label.padEnd(24), 'rejected:', err.name + ' (' + err.message + ')'); }
};

const good = jwt.sign({ sub: 'asha' }, secret, { algorithm: 'HS256', issuer: 'school-auth', audience: 'school-api', expiresIn: '10m' });
check('valid token', good);

check('expired token', jwt.sign({ sub: 'asha', exp: Math.floor(Date.now() / 1000) - 60 }, secret, { issuer: 'school-auth', audience: 'school-api' }));
check('wrong audience', jwt.sign({ sub: 'asha' }, secret, { issuer: 'school-auth', audience: 'other-api' }));
check('wrong secret', jwt.sign({ sub: 'asha' }, 'another-secret', { issuer: 'school-auth', audience: 'school-api' }));

// Tampered payload: change the subject and keep the old signature.
const [h, , s] = good.split('.');
const forgedPayload = Buffer.from(JSON.stringify({ sub: 'admin', iss: 'school-auth', aud: 'school-api' })).toString('base64url');
check('tampered payload', `${h}.${forgedPayload}.${s}`);

// The alg none attack: a token without a signature.
const none = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url') + '.' + forgedPayload + '.';
check('alg none token', none);
check('alg none, no allowlist', none, { issuer: 'school-auth', audience: 'school-api' });

console.log('decode reads a forged token without complaint:', jwt.decode(none).sub);

A good token passes. Expired, wrong audience, wrong secret, tampered and unsigned tokens are all rejected. Install first with npm install jsonwebtoken (run here with jsonwebtoken 9.0.3). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): valid token OK "asha" expired token rejected: TokenExpiredError (jwt expired) wrong audience rejected: JsonWebTokenError (jwt audience invalid. expected: school-api) wrong secret rejected: JsonWebTokenError (invalid signature) tampered payload rejected: JsonWebTokenError (invalid signature) alg none token rejected: JsonWebTokenError (jwt signature is required) alg none, no allowlist rejected: JsonWebTokenError (jwt signature is required) decode reads a forged token without complaint: admin

Key points

  • verify checks the signature and claims; decode checks nothing.
  • Always pass an algorithms allowlist.
  • Check issuer and audience.
  • Use strong secrets or key pairs, with short expiry.
  • Return one generic 401 and log the detail.

Common mistakes

  • Using jwt.decode to decide who the user is.
  • Calling verify without an algorithms list.
  • Not checking audience and issuer.
  • Hard-coded or short secrets.
  • Returning different errors that help an attacker.

Follow-ups

  • What is algorithm confusion between RS256 and HS256?
  • How does a JWKS endpoint support key rotation?
  • Why use an asymmetric algorithm for microservices?

Tips

  • Say 'verify, never decode'.
  • Name alg none.
  • List issuer, audience, expiry.
157.nodejs-0157Mediummid

How do you choose argon2 parameters, and how do you upgrade stored password hashes over time with needsRehash?

Argon2id is a memory-hard password hash that is recommended for new systems. The hash string stores the algorithm, version, parameters and salt, so verify works with old settings. Choose memory and time cost as high as your login latency allows (about 100 to 500 ms), and when you raise the settings, call needsRehash after a successful login and store the new hash, so users upgrade without a reset.

Full answer

Why a slow, memory-hard hash

  • Password databases leak. Attackers then try billions of guesses. A fast hash (SHA-256) allows billions per second on a GPU. Password hashes are slow on purpose and have a unique salt per password.
  • Argon2id uses a lot of memory, which makes GPU and ASIC attacks expensive. bcrypt (cost factor, 72 byte limit) and scrypt (built into node:crypto) are acceptable alternatives. PBKDF2 is the compatible choice for rules that demand it.

Parameters (argon2 npm package)

  • memoryCost in KiB (65536 means 64 MiB), timeCost (iterations), parallelism (lanes). Defaults are reasonable. OWASP lists values such as 19 MiB with 2 iterations or 46 MiB with 1 iteration as minimum levels, and higher is better.
  • Measure on your production hardware. Aim for roughly 100 to 500 ms per hash. Remember that login bursts run many hashes at once and use memory (threads in the libuv pool run them, default 4 at a time).

Storing and verifying

  • argon2.hash(password) returns a PHC string such as $argon2id$v=19$m=65536,t=3,p=4$salt$hash. Store the whole string in one column.
  • argon2.verify(hash, password) reads the parameters from the string and compares in constant time.
  • argon2.needsRehash(hash, options) tells whether the stored hash uses weaker parameters than your current policy.

Upgrade flow

  1. User logs in, verify succeeds.
  2. If needsRehash is true, hash the password again with the new options and update the row. You only have the plain password at this moment.
  3. Over time active users move to the new settings. Inactive users keep old hashes until they return.

Also: never log passwords, limit login attempts, compare reset tokens with timingSafeEqual, and consider a pepper kept outside the database.

javascript
const argon2 = require('argon2');

const oldPolicy = { type: argon2.argon2id, memoryCost: 4096, timeCost: 2, parallelism: 1 };      // small values keep the demo fast
const newPolicy = { type: argon2.argon2id, memoryCost: 16384, timeCost: 3, parallelism: 1 };

// A tiny user table with a pretend login flow.
const users = new Map();

async function register(name, password) { users.set(name, await argon2.hash(password, oldPolicy)); }

async function login(name, password) {
  const stored = users.get(name);
  if (!(await argon2.verify(stored, password))) return 'wrong password';
  if (argon2.needsRehash(stored, newPolicy)) {
    users.set(name, await argon2.hash(password, newPolicy));          // upgrade while we have the password
    return 'ok (hash upgraded)';
  }
  return 'ok';
}

(async () => {
  await register('asha', 'correct horse battery');
  const before = users.get('asha');
  console.log('stored hash parameters:', before.split('$')[3]);
  console.log('same password hashed twice differs (salt):', before !== await argon2.hash('correct horse battery', oldPolicy));

  console.log('wrong password ->', await login('asha', 'guess'));
  console.log('right password ->', await login('asha', 'correct horse battery'));
  console.log('hash parameters after login:', users.get('asha').split('$')[3]);
  console.log('second login ->', await login('asha', 'correct horse battery'));
  console.log('needsRehash with the new policy now:', argon2.needsRehash(users.get('asha'), newPolicy));
})();

The first login after a policy change replaces the stored hash with one made with stronger parameters. The parameters used here are small so that the demo runs fast, so do not copy them into production. Install first with npm install argon2 (run here with argon2 0.45.2). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): stored hash parameters: m=4096,t=2,p=1 same password hashed twice differs (salt): true wrong password -> wrong password right password -> ok (hash upgraded) hash parameters after login: m=16384,t=3,p=1 second login -> ok needsRehash with the new policy now: false

Key points

  • Slow, salted, memory-hard hashes limit offline guessing.
  • The hash string stores algorithm, parameters and salt.
  • Tune cost to about 100 to 500 ms on your hardware.
  • needsRehash plus a successful login upgrades hashes in place.
  • Rate limit logins and never log passwords.

Common mistakes

  • Using SHA-256 or MD5 for passwords.
  • Copying the demo parameters into production.
  • Never upgrading old hashes.
  • Running hashing on a tiny server with no memory headroom.
  • Truncating long passwords (bcrypt's 72 bytes) without noticing.

Follow-ups

  • How do you choose between argon2id, bcrypt and scrypt?
  • What is a pepper, and where do you keep it?
  • How do you protect the login endpoint from guessing?

Tips

  • Explain why slow hashing helps.
  • Mention the PHC string format.
  • Describe the upgrade flow in three steps.
158.nodejs-0158Hardsenior

How do refresh tokens work, and how does rotation with reuse detection protect against token theft?

A short-lived access token is used on every request, and a long-lived refresh token only to get new access tokens. With rotation, each refresh returns a new refresh token and invalidates the old one. If an old token is used again, someone has a copy, so the server revokes the whole token family and forces a new login. Store only hashes of refresh tokens and bind them to a family and device.

Full answer

Why two tokens

  • Access token: 5 to 15 minutes, sent with every API call. If stolen, the damage window is short.
  • Refresh token: days or weeks, kept safer (HttpOnly cookie or secure storage), sent only to the refresh endpoint.

Rotation

  • POST /refresh with the current refresh token. The server checks it, marks it used, creates a new refresh token in the same family and returns a new access token and the new refresh token.
  • The old refresh token never works again.

Reuse detection

  • If an attacker steals a refresh token and uses it, the real user's next refresh presents an already used token (or the attacker's later one does). Either way a used token arrives again.
  • The server treats this as theft and revokes the entire family. Both people lose access, and the user must log in again. This limits damage for the price of one extra login.
  • Allow a short grace window (a few seconds) for legitimate races, such as two tabs refreshing together, or answer both with the same new token.

Storage and design

  • Store a hash of the refresh token (SHA-256 is fine because the token is random and long), not the token itself. Record user, family id, expiry, used flag, device and creation time.
  • Use cryptographically random tokens (crypto.randomBytes(32)), not JWTs, so the server controls state.
  • Absolute lifetime for the family (for example 30 days) plus idle expiry.
  • Logout revokes the family. Password change revokes all families of the user.
  • For browsers use cookies with HttpOnly, Secure and SameSite, and protect the refresh endpoint from CSRF.
javascript
const crypto = require('node:crypto');

const sha256 = (text) => crypto.createHash('sha256').update(text).digest('hex');
const tokens = new Map();                 // hash -> { user, family, used, revoked }
const families = new Map();               // family -> { revoked }
let counter = 0;

function issue(user, family = 'fam-' + ++counter) {
  const token = crypto.randomBytes(24).toString('base64url');
  tokens.set(sha256(token), { user, family, used: false });
  if (!families.has(family)) families.set(family, { revoked: false });
  return token;
}

function refresh(token) {
  const record = tokens.get(sha256(token));
  if (!record) return { error: 'unknown token' };
  if (families.get(record.family).revoked) return { error: 'family revoked, log in again' };
  if (record.used) {                                           // a used token came back: someone has a copy
    families.get(record.family).revoked = true;
    return { error: 'reuse detected, family revoked' };
  }
  record.used = true;
  return { accessToken: 'access-for-' + record.user, refreshToken: issue(record.user, record.family) };
}

const first = issue('asha');                                    // issued at login
const step1 = refresh(first);
console.log('1. refresh with token 1 ->', step1.accessToken ? 'new access + new refresh token' : step1.error);

const step2 = refresh(step1.refreshToken);
console.log('2. refresh with token 2 ->', step2.accessToken ? 'new access + new refresh token' : step2.error);

// An attacker who copied token 1 earlier now tries it.
console.log('3. attacker replays token 1 ->', refresh(first).error);
console.log('4. the real user uses token 3 ->', refresh(step2.refreshToken).error);

console.log('stored values are hashes, not tokens:', ![...tokens.keys()].includes(first));
console.log('tokens kept for this family:', tokens.size);

The attacker replays the first refresh token after the user has already rotated it. The server detects the reuse and revokes the family, so even the newest token stops working. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. refresh with token 1 -> new access + new refresh token 2. refresh with token 2 -> new access + new refresh token 3. attacker replays token 1 -> reuse detected, family revoked 4. the real user uses token 3 -> family revoked, log in again stored values are hashes, not tokens: true tokens kept for this family: 3

Key points

  • Short access tokens limit the damage of theft.
  • Rotation gives a new refresh token on every use.
  • Reuse of a used token revokes the whole family.
  • Store hashes of random tokens, not the tokens.
  • Logout and password change revoke families.

Common mistakes

  • Reusing the same refresh token forever.
  • Storing refresh tokens in plain text in the database.
  • No family concept, so a theft cannot be detected.
  • Treating a double refresh from two browser tabs as theft with no grace window.
  • Making the refresh token a long-lived JWT that cannot be revoked.

Follow-ups

  • How do you handle two tabs refreshing at the same time?
  • Where should a single page app keep the refresh token?
  • What do you do on password change?

Tips

  • Explain access versus refresh first.
  • Say 'family' and 'reuse'.
  • Mention hashing the stored token.
159.nodejs-0159Mediummid

What is CSRF, and how do SameSite cookies, CSRF tokens and Origin checks protect a Node.js app?

CSRF makes a victim's browser send a state-changing request to your site, and the browser attaches the victim's cookies. Defend with SameSite=Lax or Strict cookies, a CSRF token that the attacker's page cannot read (synchroniser or double-submit token), a check of the Origin or Referer header, and never changing state with GET. APIs that use an Authorization header instead of cookies are not exposed to classic CSRF.

Full answer

The attack

  • You are logged in to bank.example (cookie session). You visit evil.example, which contains a hidden form that posts to bank.example/transfer. The browser sends the bank cookie with that request, so the bank thinks you made it.
  • CORS does not stop this. A cross-site form post is a simple request, and the server still runs it. CORS only controls who can read responses.

Defences (use several)

  1. SameSite cookies: SameSite=Lax (the default in modern browsers) stops cookies on cross-site POST requests. Strict stops them on all cross-site requests. This is the first line, but not enough alone (older browsers, subdomain issues, same-site attacks).
  2. CSRF token: a random value tied to the session, sent in a hidden form field or custom header and checked on every unsafe method (POST, PUT, PATCH, DELETE). The attacker cannot read it, because the same-origin policy blocks reading your pages. Two styles: synchroniser (stored in the session) and double submit (a cookie value must equal the header value, ideally signed).
  3. Origin check: for unsafe methods, require that Origin (or Referer) matches your site. Requests without both may be rejected.
  4. Custom header requirement (such as X-Requested-With) forces a CORS preflight for cross-site calls.
  5. Do not change state with GET. Re-authenticate for critical actions.

Notes

  • Token-based APIs that send Authorization: Bearer manually from JavaScript are not affected, since the browser does not attach that header automatically. If the token is in a cookie, CSRF applies again.
  • XSS defeats CSRF protection, because injected script can read tokens. Fix XSS too.
  • Libraries: csrf-csrf, csrf-sync (the old csurf package is deprecated).
javascript
const express = require('express');
const crypto = require('node:crypto');

const app = express();
app.use(express.json());
const sessions = new Map();          // session id -> { user, csrf }

function csrfGuard(req, res, next) {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
  const origin = req.get('origin');
  if (origin && origin !== 'http://bank.example') return res.status(403).json({ error: 'bad origin' });
  const session = sessions.get(req.get('cookie')?.match(/sid=([^;]+)/)?.[1]);
  const token = req.get('x-csrf-token');
  if (!session || !token || token.length !== session.csrf.length || !crypto.timingSafeEqual(Buffer.from(token), Buffer.from(session.csrf))) {
    return res.status(403).json({ error: 'missing or wrong csrf token' });
  }
  req.session = session;
  next();
}

app.post('/login', (req, res) => {
  const sid = crypto.randomBytes(8).toString('hex');
  const csrf = crypto.randomBytes(16).toString('hex');
  sessions.set(sid, { user: 'asha', csrf });
  res.set('Set-Cookie', `sid=${sid}; HttpOnly; SameSite=Lax; Path=/`).json({ csrfToken: csrf });
});
app.post('/transfer', csrfGuard, (req, res) => res.json({ ok: true, user: req.session.user, amount: req.body.amount }));

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const login = await fetch(base + '/login', { method: 'POST' });
  const cookie = login.headers.get('set-cookie').split(';')[0];
  const { csrfToken } = await login.json();
  console.log('cookie attributes:', login.headers.get('set-cookie').split('; ').slice(1).join(' | '));

  const transfer = async (label, headers) => {
    const res = await fetch(base + '/transfer', { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify({ amount: 50 }) });
    console.log(label.padEnd(36), res.status, JSON.stringify(await res.json()));
  };
  await transfer('legitimate (cookie + token)', { cookie, 'x-csrf-token': csrfToken });
  await transfer('forged: cookie only, no token', { cookie });
  await transfer('forged: cookie + wrong token', { cookie, 'x-csrf-token': 'a'.repeat(32) });
  await transfer('forged: token but evil origin', { cookie, 'x-csrf-token': csrfToken, origin: 'http://evil.example' });
  server.close();
});

The server accepts a request only when the cookie, the token and the origin all agree. Forged requests carry the cookie but fail the other checks. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): cookie attributes: HttpOnly | SameSite=Lax | Path=/ legitimate (cookie + token) 200 {"ok":true,"user":"asha","amount":50} forged: cookie only, no token 403 {"error":"missing or wrong csrf token"} forged: cookie + wrong token 403 {"error":"missing or wrong csrf token"} forged: token but evil origin 403 {"error":"bad origin"}

Key points

  • CSRF abuses cookies that the browser sends automatically.
  • CORS does not prevent CSRF.
  • SameSite=Lax or Strict is the first defence.
  • A token the attacker cannot read, plus an Origin check, is the second.
  • Never change state with GET.

Common mistakes

  • Believing that CORS settings stop CSRF.
  • Changing state with GET requests.
  • Using SameSite alone and skipping tokens for sensitive actions.
  • Comparing tokens with === instead of a constant-time comparison.
  • Forgetting XSS, which can read the token.

Follow-ups

  • What is the difference between synchroniser and double-submit tokens?
  • Why are Bearer-header APIs not vulnerable to classic CSRF?
  • How does SameSite=Lax treat top-level GET navigation?

Tips

  • Describe the attack in one sentence.
  • Say 'CORS does not prevent it'.
  • Name three defences.
160.nodejs-0160Easyfresher

How does CORS work in Express: simple requests, preflight, credentials and a safe origin allowlist?

CORS is a browser rule that lets a page read a response from another origin only if the server allows it with Access-Control-Allow-Origin. Some requests (JSON bodies, custom headers, PUT or DELETE) first send an OPTIONS preflight. With cookies you must name the exact origin (not *) and send Access-Control-Allow-Credentials: true. Use an allowlist, add Vary: Origin, and remember that CORS is not authentication.

Full answer

What CORS is

  • Browsers block JavaScript on one origin (scheme, host, port) from reading responses from another origin, unless the server opts in. The server still receives and runs the request, so CORS does not replace authentication or CSRF protection.
  • Non-browser clients such as curl, mobile apps and servers ignore CORS completely.

Request types

  • Simple requests (GET, HEAD, POST with form content types and no custom headers) go straight through. The browser checks the response header Access-Control-Allow-Origin.
  • Preflighted requests (JSON content type, Authorization header, PUT, PATCH, DELETE): the browser first sends OPTIONS with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The server answers 204 with Access-Control-Allow-Methods and Access-Control-Allow-Headers, and Access-Control-Max-Age to cache the answer.

Credentials

  • To send cookies or HTTP auth, the client sets credentials: 'include' and the server must answer with Access-Control-Allow-Credentials: true and a specific origin. The wildcard * is not allowed with credentials.

Allowlist

  • Compare the request Origin with a list you control and echo it back when it matches. Never reflect any origin blindly, and do not trust a pattern such as endsWith('example.com') (evilexample.com matches).
  • Add Vary: Origin so caches do not serve one origin's headers to another.
  • The cors package does this: cors({ origin: (origin, cb) => ..., credentials: true }).

Common errors: forgetting that the error response also needs the CORS headers, mixing up CORS errors with server errors (the browser hides the response), and 'fixing' CORS with * in production for private APIs.

javascript
const express = require('express');
const cors = require('cors');

const allowed = new Set(['https://app.school.example']);
const app = express();
app.use(cors({
  origin: (origin, callback) => callback(null, !origin || allowed.has(origin)),   // requests without Origin (curl, servers) pass
  credentials: true,
  methods: ['GET', 'POST', 'PUT'],
  allowedHeaders: ['content-type', 'authorization'],
  maxAge: 600,
}));
app.get('/data', (req, res) => res.json({ ok: true }));

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const show = async (label, path, init) => {
    const res = await fetch(base + path, init);
    const h = (name) => res.headers.get(name) ?? '-';
    console.log(label.padEnd(26), res.status, '| allow-origin:', h('access-control-allow-origin'), '| credentials:', h('access-control-allow-credentials'), '| vary:', h('vary'));
  };
  await show('allowed origin', '/data', { headers: { origin: 'https://app.school.example' } });
  await show('other origin', '/data', { headers: { origin: 'https://evil.example' } });
  await show('look-alike origin', '/data', { headers: { origin: 'https://app.school.example.evil.example' } });
  await show('no Origin (curl)', '/data');

  const pre = await fetch(base + '/data', { method: 'OPTIONS', headers: { origin: 'https://app.school.example', 'access-control-request-method': 'PUT', 'access-control-request-headers': 'content-type' } });
  console.log('preflight:', pre.status, '| methods:', pre.headers.get('access-control-allow-methods'), '| headers:', pre.headers.get('access-control-allow-headers'), '| max-age:', pre.headers.get('access-control-max-age'));
  server.close();
});

The server is called with a fixed Origin header, as a browser would do. The look-alike origin does not get the allow header. Real browsers enforce the result, and Node's fetch does not. Install first with npm install express cors (run here with express 5.3.0, cors 2.8.6). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): allowed origin 200 | allow-origin: https://app.school.example | credentials: true | vary: Origin other origin 200 | allow-origin: - | credentials: - | vary: - look-alike origin 200 | allow-origin: - | credentials: - | vary: - no Origin (curl) 200 | allow-origin: - | credentials: true | vary: Origin preflight: 204 | methods: GET,POST,PUT | headers: content-type,authorization | max-age: 600

Key points

  • CORS controls who can read cross-origin responses in browsers.
  • JSON, custom headers and PUT or DELETE trigger a preflight.
  • Credentials need an exact origin, never *.
  • Use an allowlist and Vary: Origin.
  • CORS is not authentication and does not stop CSRF.

Common mistakes

  • Reflecting any Origin back with credentials enabled.
  • Using a wildcard with cookies.
  • Matching origins with endsWith or includes.
  • Thinking CORS protects the API from other clients.
  • Forgetting that error responses also need the headers.

Follow-ups

  • Why does the browser send a preflight request?
  • What does Vary: Origin do?
  • How is CORS different from CSRF protection?

Tips

  • Define it as a browser rule.
  • Explain simple versus preflight.
  • Say 'exact origin with credentials'.