← Interview prep

Backend interview questions

APIs, services, reliability, and backend design trade-offs.

50 questions · Page 1 of 3

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

Page 1 of 3

Questions 1–20 of 50 · 0 of 20 on this page marked learned

1.backend-0001Easyfresher

How do you design REST resources and URLs, and what do safe and idempotent mean for GET, POST, PUT, PATCH and DELETE?

REST models your data as resources (nouns such as /students/42) and uses HTTP methods as the verbs. GET and HEAD are safe (they do not change state). GET, PUT and DELETE are idempotent (doing them twice leaves the same state as doing them once). POST is neither: it usually creates a new resource each time. PATCH is not guaranteed to be idempotent.

Full answer

Resources and URLs

  • Use plural nouns for collections (/students) and an id for one item (/students/42). Nest only when the child cannot exist without the parent (/students/42/enrollments). Keep URLs shallow.
  • Put the action in the method, not the path. Avoid /createStudent. When an action is not CRUD (for example "cancel an order"), model it as a sub-resource or state change (POST /orders/7/cancellation).

Method semantics

  • GET: read. Safe and idempotent. Cacheable.
  • POST: create a child in a collection, or run a non-idempotent action. Success is 201 with a Location header.
  • PUT: replace the whole resource at a known URL. Idempotent: sending the same body twice gives the same state.
  • PATCH: change part of a resource. Can be idempotent, but is not required to be (for example "add 1 to the counter").
  • DELETE: remove. Idempotent in state: the second call finds nothing, so the status may be 404, but the server state is the same.

Why it matters: clients, proxies and retry libraries use these rules. A network client may safely retry GET, PUT and DELETE after a timeout, but a blind retry of POST can create duplicates (idempotency keys fix that, see the idempotency items).

javascript
const http = require('node:http');

const students = new Map();
let nextId = 1;
const readJson = (req) => new Promise((resolve) => { let t = ''; req.on('data', (c) => (t += c)); req.on('end', () => resolve(t ? JSON.parse(t) : {})); });

const server = http.createServer(async (req, res) => {
  const send = (status, body, headers = {}) => { res.writeHead(status, { 'content-type': 'application/json', ...headers }); res.end(body === undefined ? '' : JSON.stringify(body)); };
  const [, collection, id] = req.url.split('/');
  if (collection !== 'students') return send(404, { error: 'not found' });
  if (req.method === 'POST' && !id) { const s = { id: nextId++, ...(await readJson(req)) }; students.set(s.id, s); return send(201, s, { location: `/students/${s.id}` }); }
  if (req.method === 'GET' && id) return students.has(+id) ? send(200, students.get(+id)) : send(404, { error: 'not found' });
  if (req.method === 'PUT' && id) { students.set(+id, { id: +id, ...(await readJson(req)) }); return send(200, students.get(+id)); }
  if (req.method === 'DELETE' && id) return students.delete(+id) ? send(204) : send(404, { error: 'not found' });
  send(405, { error: 'method not allowed' }, { allow: 'GET, POST, PUT, DELETE' });
});

server.listen(0, '127.0.0.1', async () => {
  const base = `http://127.0.0.1:${server.address().port}`;
  const call = async (method, path, body) => {
    const r = await fetch(base + path, { method, body: body && JSON.stringify(body), headers: { 'content-type': 'application/json' } });
    return `${method} ${path} -> ${r.status}${r.headers.get('location') ? ' Location ' + r.headers.get('location') : ''}`;
  };
  console.log(await call('POST', '/students', { name: 'Asha' }));
  console.log(await call('POST', '/students', { name: 'Asha' }), '(a second POST made a second resource)');
  console.log(await call('PUT', '/students/1', { name: 'Asha Rao' }));
  console.log(await call('PUT', '/students/1', { name: 'Asha Rao' }), '(same body again, same state)');
  console.log('students stored:', JSON.stringify([...students.values()]));
  console.log(await call('DELETE', '/students/2'));
  console.log(await call('DELETE', '/students/2'), '(state is the same, status differs)');
  console.log(await call('PATCH', '/students/1', { name: 'x' }));
  server.close();
});

A tiny in-memory server on a random port and fetch calls show the method rules directly. The numbers of resources and statuses are the point, not the storage. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): POST /students -> 201 Location /students/1 POST /students -> 201 Location /students/2 (a second POST made a second resource) PUT /students/1 -> 200 PUT /students/1 -> 200 (same body again, same state) students stored: [{"id":1,"name":"Asha Rao"},{"id":2,"name":"Asha"}] DELETE /students/2 -> 204 DELETE /students/2 -> 404 (state is the same, status differs) PATCH /students/1 -> 405

Key points

  • Resources are nouns; methods are the verbs.
  • GET is safe and idempotent; PUT and DELETE are idempotent; POST is not.
  • POST to a collection creates a resource and returns 201 with Location.
  • PUT replaces the whole resource; PATCH changes part of it.
  • Retry rules depend on idempotency.

Common mistakes

  • Using verbs in URLs (/getStudent).
  • Using POST for everything.
  • Using GET for actions that change state (crawlers and prefetchers will trigger them).
  • Nesting URLs five levels deep.
  • Retrying POST after a timeout without an idempotency key.

Follow-ups

  • What is the difference between safe and idempotent?
  • Why can DELETE return 404 on the second call and still be idempotent?
  • When is a sub-resource better than a custom verb?

Tips

  • Say 'nouns in the URL, verbs in the method'.
  • Give the safe and idempotent table from memory.
  • Mention retries as the reason it matters.
2.backend-0002Easyfresher

Which HTTP status codes should a REST API return for success, client errors and server errors, and how do you choose between similar ones such as 400 vs 422 and 401 vs 403?

Use the class of the code to say who is at fault: 2xx success, 3xx redirect or cached, 4xx the client must change the request, 5xx the server failed (retry may help). Pick the most specific code: 201 for created, 204 for no body, 400 for malformed input, 422 for valid syntax but failed validation, 401 when authentication is missing or wrong, 403 when the user is known but not allowed, 404 for missing, 409 for a state conflict, 429 for rate limits, 503 for temporary unavailability.

Full answer

Success

  • 200 OK with a body. 201 Created with a Location header. 202 Accepted when the work is queued. 204 No Content for success with no body (DELETE, some PUT).

Client errors (do not retry unchanged)

  • 400 Bad Request: the request cannot be parsed (broken JSON, wrong type).
  • 401 Unauthorized: no valid credentials. (The name is historic. It means "unauthenticated".) Send WWW-Authenticate.
  • 403 Forbidden: credentials are valid but the action is not allowed.
  • 404 Not Found: no such resource. Some APIs return 404 instead of 403 to hide that a resource exists.
  • 409 Conflict: the request clashes with the current state (duplicate email, version mismatch). 412 Precondition Failed for failed If-Match.
  • 422 Unprocessable Content: the syntax is fine but the values break business or validation rules.
  • 429 Too Many Requests, with Retry-After.

Server errors (the client may retry)

  • 500 unexpected failure, 502 or 504 bad or slow upstream, 503 temporarily unavailable (with Retry-After).

Also return a consistent error body (a machine code, a human message, field details, a request id). RFC 9457 (problem details) is a standard shape. Never put stack traces in responses.

javascript
const http = require('node:http');

// Each scenario returns the status that a well designed API would use.
const scenarios = {
  created:     (res) => res.writeHead(201, { location: '/students/7' }).end('{"id":7}'),
  deleted:     (res) => res.writeHead(204).end(),
  brokenJson:  (res) => res.writeHead(400).end('{"code":"invalid_json"}'),
  badEmail:    (res) => res.writeHead(422).end('{"code":"validation_failed","fields":{"email":"must be an email"}}'),
  noToken:     (res) => res.writeHead(401, { 'www-authenticate': 'Bearer' }).end('{"code":"unauthenticated"}'),
  wrongRole:   (res) => res.writeHead(403).end('{"code":"forbidden"}'),
  missing:     (res) => res.writeHead(404).end('{"code":"not_found"}'),
  duplicate:   (res) => res.writeHead(409).end('{"code":"email_taken"}'),
  tooMany:     (res) => res.writeHead(429, { 'retry-after': '30' }).end('{"code":"rate_limited"}'),
  maintenance: (res) => res.writeHead(503, { 'retry-after': '120' }).end('{"code":"unavailable"}'),
};
const retryable = (status) => status === 429 || status === 503 || status === 502 || status === 504;

const server = http.createServer((req, res) => (scenarios[req.url.slice(1)] || ((r) => r.writeHead(404).end()))(res));
server.listen(0, '127.0.0.1', async () => {
  for (const name of Object.keys(scenarios)) {
    const r = await fetch(`http://127.0.0.1:${server.address().port}/${name}`);
    const extra = ['location', 'www-authenticate', 'retry-after'].filter((h) => r.headers.has(h)).map((h) => `${h}: ${r.headers.get(h)}`).join(', ');
    console.log(name.padEnd(12), r.status, ('client may retry: ' + retryable(r.status)).padEnd(24), extra);
  }
  server.close();
});

The server answers each scenario with the status an API should use. The client prints the status, the headers that matter and whether a retry makes sense. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): created 201 client may retry: false location: /students/7 deleted 204 client may retry: false brokenJson 400 client may retry: false badEmail 422 client may retry: false noToken 401 client may retry: false www-authenticate: Bearer wrongRole 403 client may retry: false missing 404 client may retry: false duplicate 409 client may retry: false tooMany 429 client may retry: true retry-after: 30 maintenance 503 client may retry: true retry-after: 120

Key points

  • The first digit says whose fault it is.
  • 401 means unauthenticated; 403 means not allowed.
  • 400 is a bad request format; 422 is a failed validation.
  • 409 and 412 describe state conflicts; 429 describes rate limits.
  • Use one error body shape everywhere.

Common mistakes

  • Returning 200 with an error message in the body.
  • Using 500 for validation errors.
  • Mixing up 401 and 403.
  • Returning 404 for an empty list (use 200 and []).
  • Leaking stack traces in error bodies.

Follow-ups

  • When would you return 202 instead of 201?
  • What is a problem details (RFC 9457) response?
  • Why do some APIs return 404 for forbidden resources?

Tips

  • Group by who is at fault.
  • Contrast 401 with 403 in one sentence.
  • Name Retry-After.
3.backend-0003Mediummid

How do you paginate a REST API, and why does offset pagination break or slow down on large or changing data compared with keyset (cursor) pagination?

Offset pagination (LIMIT n OFFSET k) is simple but the database still reads and skips k rows, so deep pages are slow, and inserts or deletes between requests shift the rows so items repeat or vanish. Keyset (cursor) pagination asks for rows after the last seen sort key (WHERE id < last ORDER BY id DESC LIMIT n), which is fast with an index and stable under changes. The cost: no jump to page 50, and the sort key must be unique and indexed.

Full answer

Offset pagination

  • GET /items?limit=20&offset=40. Easy to build, supports page numbers and totals.
  • Problems: the engine produces and discards offset rows, so cost grows with the page number. If a row is inserted before the current position, the next page repeats a row. If a row is deleted, one row is skipped.

Keyset (cursor) pagination

  • The client sends the sort key of the last row it saw: GET /items?limit=20&after=eyJpZCI6OH0. The server runs WHERE (sort_key) < (:last) ORDER BY sort_key DESC LIMIT 20. With an index the engine jumps straight to the position.
  • The cursor is opaque to clients (often base64 of the last key). This lets you change its content later.
  • The sort key must be unique and stable. For a non-unique column such as created_at, add the id as a tie breaker and use a row comparison: WHERE (created_at, id) < (:t, :id).
  • Return a next cursor, or nothing at the end. A total count is expensive, so offer it only when needed (or an estimate).

Choosing: use keyset for feeds, logs and large tables, and offset for small admin tables where page numbers matter. Always cap limit (for example 100).

javascript
const { Client } = require('pg');

(async () => {
  const db = new Client(); await db.connect();
  await db.query('DROP TABLE IF EXISTS page_items; CREATE TABLE page_items (id serial PRIMARY KEY, title text)');
  await db.query("INSERT INTO page_items (title) SELECT 'item ' || g FROM generate_series(1, 10) g");
  const ids = (r) => r.rows.map((x) => x.id).join(', ');

  const offsetPage = (limit, offset) => db.query('SELECT id FROM page_items ORDER BY id DESC LIMIT $1 OFFSET $2', [limit, offset]);
  const keysetPage = (limit, after) => db.query('SELECT id FROM page_items WHERE ($2::int IS NULL OR id < $2) ORDER BY id DESC LIMIT $1', [limit, after]);
  const encode = (id) => Buffer.from(JSON.stringify({ id })).toString('base64url');
  const decode = (cursor) => JSON.parse(Buffer.from(cursor, 'base64url').toString()).id;

  const o1 = await offsetPage(3, 0);
  const k1 = await keysetPage(3, null);
  const cursor = encode(k1.rows.at(-1).id);
  console.log('page 1 (both)        :', ids(o1), '| cursor =', cursor);

  await db.query("INSERT INTO page_items (title) VALUES ('new item')");     // a new row arrives between the requests

  console.log('page 2 with offset   :', ids(await offsetPage(3, 3)), '(8 appears again)');
  console.log('page 2 with keyset   :', ids(await keysetPage(3, decode(cursor))), '(continues from 7)');

  const plan = await db.query('EXPLAIN (COSTS OFF) SELECT id FROM page_items WHERE id < 8 ORDER BY id DESC LIMIT 3');
  console.log('keyset plan uses the primary key index:', plan.rows.some((r) => /Index/.test(r['QUERY PLAN'])));

  await db.query('DROP TABLE page_items');
  await db.end();
})();

Run against the local PostgreSQL. A new row is inserted between page 1 and page 2 to show the difference. Timing of deep offsets was not measured here. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): page 1 (both) : 10, 9, 8 | cursor = eyJpZCI6OH0 page 2 with offset : 8, 7, 6 (8 appears again) page 2 with keyset : 7, 6, 5 (continues from 7) keyset plan uses the primary key index: true

Key points

  • Offset skips rows by reading them, so deep pages are slow.
  • Changes between requests make offset pages repeat or miss rows.
  • Keyset uses the last seen key and an index.
  • The sort key must be unique; add the id as a tie breaker.
  • Cursors should be opaque and limits capped.

Common mistakes

  • Using OFFSET on a table with millions of rows and deep pages.
  • Sorting by a non-unique column with no tie breaker.
  • Exposing raw ids in a cursor that clients start to parse.
  • Returning an exact total count on every request.
  • No maximum limit.

Follow-ups

  • How do you paginate by (created_at, id) in SQL?
  • How do you go backwards with a keyset cursor?
  • What do you return for 'total pages'?

Tips

  • Say 'the database still reads the skipped rows'.
  • Show the WHERE form of keyset.
  • Mention the trade-off: no random page jump.
4.backend-0004Mediummid

What is the difference between PUT and PATCH, how does JSON Merge Patch work, and how do ETag and If-Match protect against lost updates?

PUT sends a full replacement, so missing fields are removed, and it is idempotent. PATCH sends only the changes. JSON Merge Patch (RFC 7396) is a simple format: send a partial object, fields set to null are deleted, objects merge recursively, arrays are replaced. To avoid lost updates the server returns an ETag (a version of the representation) and the client sends If-Match with it on the write. If it no longer matches, the server answers 412 Precondition Failed.

Full answer

PUT versus PATCH

  • PUT /students/1 with a body means: make the resource exactly this. A field you leave out is gone. Same input, same state: idempotent.
  • PATCH /students/1 with a partial body means: apply these changes. Smaller requests, and clients do not need to know the whole resource.

Patch formats

  • JSON Merge Patch (application/merge-patch+json): easy. The body looks like the resource. null removes a field. Arrays are replaced as a whole, and you cannot set a value to null on purpose.
  • JSON Patch (application/json-patch+json, RFC 6902): a list of operations such as { op: "replace", path: "/name", value: "x" }. More precise (array items, test operations) but more complex.

Lost updates

  • Two clients read version A. Client 1 writes, then client 2 writes from stale data and silently overwrites the first change.
  • Fix: the server sends ETag: "v7" on GET. The client sends If-Match: "v7" on PUT or PATCH. If the current ETag differs, answer 412 and let the client re-read and merge. Use If-None-Match: * to create only if absent. A missing If-Match on a write can be answered with 428 Precondition Required.
javascript
const crypto = require('node:crypto');

// RFC 7396 JSON Merge Patch
function mergePatch(target, patch) {
  if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) return patch;
  const result = (target && typeof target === 'object' && !Array.isArray(target)) ? { ...target } : {};
  for (const [key, value] of Object.entries(patch)) {
    if (value === null) delete result[key];
    else result[key] = mergePatch(result[key], value);
  }
  return result;
}
const etag = (resource) => '"' + crypto.createHash('sha1').update(JSON.stringify(resource)).digest('hex').slice(0, 8) + '"';

let student = { id: 1, name: 'Asha', city: 'Pune', tags: ['a', 'b'], address: { street: 'MG Road', zip: '411001' } };
console.log('original      :', JSON.stringify(student));
console.log('PUT body      :', JSON.stringify({ id: 1, name: 'Asha Rao' }), '-> everything else is gone');
console.log('PATCH changes :', JSON.stringify(mergePatch(student, { name: 'Asha Rao', city: null, tags: ['c'], address: { zip: '411002' } })));

// A write with If-Match
function update(current, ifMatch, patch) {
  if (ifMatch !== etag(current)) return { status: 412 };
  return { status: 200, resource: mergePatch(current, patch) };
}
const tagSeenByBoth = etag(student);
const first = update(student, tagSeenByBoth, { name: 'First writer' });
student = first.resource;
const second = update(student, tagSeenByBoth, { name: 'Second writer' });
console.log('first write   :', first.status, '| second write with a stale ETag:', second.status);
console.log('ETag changed  :', tagSeenByBoth !== etag(student));

The Merge Patch function and the ETag check are written in plain Node with no server, so the logic is easy to read. In a real API they sit behind the PATCH route and the If-Match header. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): original : {"id":1,"name":"Asha","city":"Pune","tags":["a","b"],"address":{"street":"MG Road","zip":"411001"}} PUT body : {"id":1,"name":"Asha Rao"} -> everything else is gone PATCH changes : {"id":1,"name":"Asha Rao","tags":["c"],"address":{"street":"MG Road","zip":"411002"}} first write : 200 | second write with a stale ETag: 412 ETag changed : true

Key points

  • PUT replaces the whole resource; PATCH changes part of it.
  • Merge Patch: null deletes, objects merge, arrays replace.
  • JSON Patch is an explicit list of operations.
  • ETag plus If-Match gives optimistic concurrency over HTTP.
  • A failed precondition is 412.

Common mistakes

  • Using PUT with a partial body and deleting fields by accident.
  • Using Merge Patch when you need to set null or edit an array item.
  • Using last-write-wins updates in a multi-user app.
  • Computing an ETag from something that changes on every request.
  • Answering 409 for every conflict (412 is the precondition code).

Follow-ups

  • When is JSON Patch better than Merge Patch?
  • What is a weak ETag?
  • How does If-None-Match work for caching?

Tips

  • Define each method in one line.
  • Mention null as delete in Merge Patch.
  • Tie ETag to lost updates.
5.backend-0005Hardsenior

How do you version and evolve an API without breaking clients: which changes are breaking, and what are the options (URL, header, no version)?

Prefer evolving one version with backward-compatible changes: add optional fields, add endpoints, never remove or rename fields, never change types or meaning. Clients follow the tolerant reader rule (ignore unknown fields). When a breaking change is unavoidable, introduce a new version (URL like /v2, or a header or media type), run both, announce deprecation with Deprecation and Sunset headers, measure usage per version and retire the old one on a published date.

Full answer

Compatible changes

  • Add a new optional request field or a new response field. Add a new endpoint. Add a new enum value only if clients are told to handle unknown values.

Breaking changes

  • Remove or rename a field, change its type, make an optional field required, change the meaning of a value, tighten validation, change an error code that clients depend on, or change default sorting or paging.

Versioning options

  • URL (/v2/students): clear, easy to route and cache, but it versions the whole API.
  • Header or media type (Accept: application/vnd.school.v2+json, or a custom header): clean URLs, harder to test by hand and to cache.
  • Date based versions (Stripe style): each account is pinned to a version date, and the server applies transforms. Powerful, costs a lot to maintain.
  • No versions, only additive evolution (GraphQL style, or protobuf rules): works when you control or can reach all clients.

Process

  • Contract tests and a schema diff in CI (OpenAPI diff, protobuf breaking checks) catch accidental breaks.
  • Track usage per version and per client. Announce deprecations with a date, send Deprecation and Sunset headers, log callers that still use old versions, and contact them.
  • Keep the number of live versions small (two). Share the domain code and keep only the mapping layer per version.
javascript
// A tiny compatibility checker for object shapes: { field: { type, required } }
function diff(oldSchema, newSchema) {
  const breaking = [], compatible = [];
  for (const [name, spec] of Object.entries(oldSchema)) {
    const next = newSchema[name];
    if (!next) breaking.push(`removed field "${name}"`);
    else if (next.type !== spec.type) breaking.push(`type of "${name}" changed ${spec.type} -> ${next.type}`);
    else if (!spec.required && next.required) breaking.push(`"${name}" became required`);
  }
  for (const [name, spec] of Object.entries(newSchema)) {
    if (oldSchema[name]) continue;
    (spec.required ? breaking : compatible).push(`${spec.required ? 'new required' : 'new optional'} field "${name}"`);
  }
  return { breaking, compatible };
}

const v1 = { id: { type: 'number', required: true }, name: { type: 'string', required: true } };
const v1b = { ...v1, nickname: { type: 'string', required: false } };
const v2 = { id: { type: 'string', required: true }, fullName: { type: 'string', required: true } };
console.log('v1 -> v1 + optional field:', JSON.stringify(diff(v1, v1b)));
console.log('v1 -> v2 (rename, new id type):', JSON.stringify(diff(v1, v2)));

// Tolerant reader: a v1 client keeps working when the server adds fields.
const oldClient = (response) => `Hello ${response.name} (#${response.id})`;
console.log('old client, new payload:', oldClient({ id: 7, name: 'Asha', nickname: 'Ash', badges: ['early'] }));

// Sunset information for a retiring version
const headers = { Deprecation: 'true', Sunset: 'Wed, 30 Jun 2027 23:59:59 GMT', Link: '</v2/students>; rel="successor-version"' };
const daysLeft = Math.round((Date.parse(headers.Sunset) - Date.parse('2026-12-04T00:00:00Z')) / 86400000);
console.log('days until v1 is switched off:', daysLeft);

The checker compares two simple schemas and a fixed date is used for the sunset count, so the output is stable. Real projects use OpenAPI diff tools or protobuf breaking-change checks for the same job. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): v1 -> v1 + optional field: {"breaking":[],"compatible":["new optional field \"nickname\""]} v1 -> v2 (rename, new id type): {"breaking":["type of \"id\" changed number -> string","removed field \"name\"","new required field \"fullName\""],"compatible":[]} old client, new payload: Hello Asha (#7) days until v1 is switched off: 209

Key points

  • Additive, optional changes are compatible; removal, rename and type changes are not.
  • Clients should ignore unknown fields.
  • Versions can live in the URL, a header or a date pin.
  • Automate breaking change detection in CI.
  • Deprecate with a date, headers and usage tracking.

Common mistakes

  • Renaming a field because the new name is nicer.
  • Adding a new required request field to an existing endpoint.
  • Changing the meaning of a value without a new field.
  • Keeping five old versions alive forever.
  • Retiring a version with no usage data and no notice.

Follow-ups

  • How would you version a webhook payload?
  • Why do date-based versions work for Stripe but are hard for small teams?
  • What does the tolerant reader rule ask of clients?

Tips

  • List what counts as breaking.
  • Compare URL and header versioning.
  • Describe the retirement process.
6.backend-0006Easyfresher

What are gRPC and Protocol Buffers, and how do they differ from REST with JSON?

Protocol Buffers (protobuf) is a schema language and a compact binary format. gRPC is an RPC framework that uses protobuf over HTTP/2: you define services and messages in a .proto file and generate typed client and server code. Compared with REST and JSON, gRPC gives smaller messages, strict contracts, streaming and deadlines, while REST gives human readable payloads, simple tooling, browser support and easy caching.

Full answer

Protobuf

  • You describe messages in a .proto file with numbered fields (int32 id = 1; string name = 2;). The field number, not the name, identifies a field on the wire. Values use compact encodings (varints for integers, length-prefixed bytes for strings). Field names are not sent.
  • Code generators create classes for many languages from the same file, so a Node client and a Go server share one contract.

gRPC

  • HTTP/2 transport: many calls over one connection, header compression, and four call types: unary, server streaming, client streaming and bidirectional streaming.
  • Built in: deadlines, cancellation, metadata (headers), status codes and interceptors.

Compared with REST + JSON

  • Size and speed: binary protobuf is usually smaller and faster to parse than JSON.
  • Contract: the schema is the source of truth, and breaking changes are easy to detect.
  • Tooling: curl and browsers work with REST directly. gRPC needs special tools, and browsers need gRPC-Web or a gateway.
  • Caching: HTTP caches and CDNs work well with GET in REST, and not with gRPC.
  • Best fit: internal service to service calls, streaming, polyglot teams. REST fits public APIs and browser clients.
javascript
const protobuf = require('protobufjs');

const root = protobuf.parse(`
  syntax = "proto3";
  message Student { int32 id = 1; string name = 2; repeated string tags = 3; bool active = 4; }
`).root;
const Student = root.lookupType('Student');

const value = { id: 150, name: 'Asha', tags: ['web', 'node'], active: true };
const bytes = Student.encode(Student.create(value)).finish();
const json = JSON.stringify(value);

console.log('JSON bytes     :', Buffer.byteLength(json));
console.log('protobuf bytes :', bytes.length);
console.log('protobuf hex   :', Buffer.from(bytes).toString('hex'));

// Reading the first field by hand: tag 0x08 = field 1, wire type 0 (varint); then 0x96 0x01 = 150.
const [tag, b1, b2] = bytes;
console.log('tag byte       :', tag.toString(16), '= field', tag >> 3, ', wire type', tag & 7);
console.log('varint 96 01   :', (b1 & 0x7f) | ((b2 & 0x7f) << 7));

const decoded = Student.toObject(Student.decode(bytes));
console.log('round trip     :', JSON.stringify(decoded) === json);

Uses the protobufjs library (npm install protobufjs) with an inline schema. Field names do not appear in the bytes, only field numbers and values. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): JSON bytes : 60 protobuf bytes : 22 protobuf hex : 0896011204417368611a037765621a046e6f64652001 tag byte : 8 = field 1 , wire type 0 varint 96 01 : 150 round trip : true

Key points

  • Protobuf is a schema plus a compact binary format identified by field numbers.
  • gRPC adds HTTP/2, streaming, deadlines and generated clients.
  • JSON is readable and works everywhere; protobuf is smaller and strictly typed.
  • Browsers need gRPC-Web or a gateway.
  • gRPC suits internal services; REST suits public APIs.

Common mistakes

  • Choosing gRPC for a public browser API without a gateway.
  • Assuming binary is always much faster in the whole system (network and database often dominate).
  • Reusing or renumbering field numbers.
  • Using gRPC without deadlines.
  • Ignoring load balancing (HTTP/2 keeps a long-lived connection).

Follow-ups

  • How does gRPC streaming differ from WebSockets?
  • What is gRPC-Web?
  • How do you debug gRPC traffic?

Tips

  • Say that the field number identifies the field.
  • Give two strengths and two weaknesses.
  • Place each protocol: internal, public.
7.backend-0007Mediummid

How do you evolve a protobuf schema safely: which changes are compatible, and why must field numbers never be reused?

Protobuf data is identified by field numbers, so you can add new fields (old readers skip them, new readers see defaults for old data), rename fields (names are not on the wire), and stop using a field. You must never reuse a number for a different meaning, change a field's type to an incompatible wire type, or renumber. Mark removed numbers and names as reserved so nobody reuses them by mistake.

Full answer

Compatible changes

  • Add a field with a new number. Old readers ignore it (unknown field), new readers get the default value when decoding old data. Proto3 defaults are 0, empty string, false, empty list.
  • Rename a field. Names are only for code generation. JSON mapping would change, though.
  • Remove a field, and add reserved 2; and reserved "email"; so the number and name stay unused.

Breaking changes

  • Reusing a number for another meaning: old data is read as the new field, silently. This is the worst case because nothing fails.
  • Changing a type to a different wire type (string to int32). Decoding fails or returns garbage. Some changes are compatible (int32 and int64 and bool share the varint wire type, with value limits).
  • Renumbering fields, changing repeated to singular in surprising ways, or changing a field's meaning.

Practices

  • Treat the .proto file as an API contract in version control. Run a breaking-change check in CI (buf breaking).
  • Do not rely on required fields (proto2 required was removed from proto3 for this reason). Validate in code.
  • Use enums with an UNSPECIFIED = 0 value, and handle unknown enum values.
  • Use optional when you need to tell "not set" from the default value.
javascript
const protobuf = require('protobufjs');
const type = (proto) => protobuf.parse(`syntax = "proto3"; ${proto}`).root.lookupType('Student');
const show = (t, bytes) => JSON.stringify(t.toObject(t.decode(bytes), { defaults: true }));

const V1 = type('message Student { int32 id = 1; string name = 2; }');
const V2 = type('message Student { int32 id = 1; string name = 2; string email = 3; }');       // added a field
const Renamed = type('message Student { int32 student_id = 1; string full_name = 2; }');        // renamed, same numbers
const Reused = type('message Student { int32 id = 1; int32 age = 2; }');                       // number 2 changed type

const oldBytes = V1.encode({ id: 7, name: 'Asha' }).finish();
const newBytes = V2.encode({ id: 7, name: 'Asha', email: 'asha@example.com' }).finish();

console.log('new data, old reader  :', show(V1, newBytes), '(email is skipped)');
console.log('old data, new reader  :', show(V2, oldBytes), '(email gets the default)');
console.log('renamed fields        :', show(Renamed, oldBytes), '(same bytes, new names)');
try { console.log('number 2 as int32     :', show(Reused, oldBytes)); }
catch (err) { console.log('number 2 as int32     : decoding failed with', err.name); }

// Reusing a number with the SAME wire type does not fail. It silently changes the meaning.
const Before = protobuf.parse('syntax = "proto3"; message Item { int32 quantity = 1; }').root.lookupType('Item');
const After = protobuf.parse('syntax = "proto3"; message Item { int32 price_in_cents = 1; }').root.lookupType('Item');
const stored = Before.encode({ quantity: 3 }).finish();
console.log('reused number, same type:', show(After, stored), '(3 items is now read as 3 cents, with no error)');

Several schemas are parsed in one script and used to decode the same bytes. The failing case is described by the error name only, because the exact message depends on the library. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): new data, old reader : {"id":7,"name":"Asha"} (email is skipped) old data, new reader : {"id":7,"name":"Asha","email":""} (email gets the default) renamed fields : {"studentId":7,"fullName":"Asha"} (same bytes, new names) number 2 as int32 : decoding failed with RangeError reused number, same type: {"priceInCents":3} (3 items is now read as 3 cents, with no error)

Key points

  • New fields with new numbers are safe in both directions.
  • Names are not on the wire, so renames are safe.
  • Never reuse or change a field number's meaning.
  • Use reserved for removed numbers and names.
  • Automate breaking change checks.

Common mistakes

  • Reusing a deleted field's number for a new field.
  • Changing int32 to string and expecting old data to decode.
  • Using required fields.
  • Not reserving removed names and numbers.
  • Skipping breaking checks in CI.

Follow-ups

  • What is the unknown field behaviour of proto3 in different languages?
  • How do you add a field that has no sensible default?
  • How do you migrate stored data when a field changes meaning?

Tips

  • Say 'wire is numbers, names are code'.
  • Call out the silent reuse bug.
  • Mention reserved.
8.backend-0008Easyfresher

How do you decide between gRPC and REST for a service, and how do gRPC status codes map to HTTP status codes?

Choose by who calls the API and what the call needs. Use REST (or GraphQL) for public APIs, browser clients and cacheable reads. Use gRPC for internal service-to-service calls, streaming, strict contracts across languages and low latency. Many systems use both: gRPC inside, REST at the edge through a gateway. gRPC has its own status codes, which map roughly to HTTP codes (NOT_FOUND to 404, INVALID_ARGUMENT to 400, UNAUTHENTICATED to 401).

Full answer

Decision questions

  1. Who are the clients? Browsers and third parties favour REST. Your own backend services favour gRPC.
  2. Do you need streaming or long-lived calls? gRPC supports it natively. REST needs SSE or WebSockets.
  3. How important is a strict, generated contract across languages? gRPC and protobuf are strong here.
  4. Do you need HTTP caching, simple debugging with curl, or human readable logs? REST is easier.
  5. How many teams and languages? A shared .proto repository scales well with many languages.

Mixed design

  • Public REST API at the edge (or a gRPC-JSON transcoding gateway such as Envoy), internal gRPC between services.

gRPC details to know

  • Errors are a status code plus a message and optional details, not an HTTP status. gRPC over HTTP/2 always returns HTTP 200 for the transport and puts the status in trailers.
  • Deadlines are sent with the call and should be propagated to downstream calls.
  • Client side or proxy-based load balancing is required, because one HTTP/2 connection carries many calls to one server.

Mapping (common): OK 200, INVALID_ARGUMENT 400, UNAUTHENTICATED 401, PERMISSION_DENIED 403, NOT_FOUND 404, ALREADY_EXISTS 409, FAILED_PRECONDITION 400 or 412, RESOURCE_EXHAUSTED 429, CANCELLED 499, INTERNAL 500, UNIMPLEMENTED 501, UNAVAILABLE 503, DEADLINE_EXCEEDED 504.

javascript
const mapping = {
  OK: 200, CANCELLED: 499, INVALID_ARGUMENT: 400, DEADLINE_EXCEEDED: 504, NOT_FOUND: 404, ALREADY_EXISTS: 409,
  PERMISSION_DENIED: 403, RESOURCE_EXHAUSTED: 429, FAILED_PRECONDITION: 400, UNIMPLEMENTED: 501, INTERNAL: 500,
  UNAVAILABLE: 503, UNAUTHENTICATED: 401,
};
const retryable = new Set(['UNAVAILABLE', 'DEADLINE_EXCEEDED', 'RESOURCE_EXHAUSTED']);

function recommend({ clients, streaming, needsHttpCache, polyglotTeams }) {
  if (clients === 'browser' || clients === 'third-party') return needsHttpCache ? 'REST (cacheable GET)' : 'REST, or gRPC behind a gateway';
  if (streaming) return 'gRPC';
  return polyglotTeams ? 'gRPC (shared .proto contract)' : 'either; start with the one your team knows';
}

console.log('gRPC status -> HTTP (common mapping), usually retryable for idempotent calls:');
for (const [grpc, http] of Object.entries(mapping)) console.log(' ', grpc.padEnd(20), http, retryable.has(grpc) ? 'retry with backoff' : '');

console.log('\nscenarios:');
console.log(' public mobile app + web      ->', recommend({ clients: 'browser', needsHttpCache: false }));
console.log(' public price list, cached    ->', recommend({ clients: 'third-party', needsHttpCache: true }));
console.log(' internal live updates        ->', recommend({ clients: 'service', streaming: true }));
console.log(' internal, Go + Node + Java   ->', recommend({ clients: 'service', polyglotTeams: true }));

A mapping table and a small decision helper. The mapping is a common convention (it follows the Google API guidance), and individual gateways may differ. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): gRPC status -> HTTP (common mapping), usually retryable for idempotent calls: OK 200 CANCELLED 499 INVALID_ARGUMENT 400 DEADLINE_EXCEEDED 504 retry with backoff NOT_FOUND 404 ALREADY_EXISTS 409 PERMISSION_DENIED 403 RESOURCE_EXHAUSTED 429 retry with backoff FAILED_PRECONDITION 400 UNIMPLEMENTED 501 INTERNAL 500 UNAVAILABLE 503 retry with backoff UNAUTHENTICATED 401 scenarios: public mobile app + web -> REST, or gRPC behind a gateway public price list, cached -> REST (cacheable GET) internal live updates -> gRPC internal, Go + Node + Java -> gRPC (shared .proto contract)

Key points

  • Public and browser clients favour REST; internal services favour gRPC.
  • Streaming and strict generated contracts favour gRPC.
  • A gateway can expose gRPC services as REST.
  • gRPC errors use status codes with a rough HTTP mapping.
  • gRPC needs deadlines and proper load balancing.

Common mistakes

  • Choosing gRPC because it is fashionable.
  • Exposing internal gRPC directly to browsers.
  • Returning INTERNAL for every error.
  • Retrying non-idempotent calls on DEADLINE_EXCEEDED.
  • Forgetting that load balancers must understand HTTP/2.

Follow-ups

  • How does a gRPC-JSON transcoding gateway work?
  • What is the difference between UNAVAILABLE and INTERNAL?
  • How do you pass deadlines between services?

Tips

  • Start with 'who is the client'.
  • Mention using both.
  • Know a few status mappings.
9.backend-0009Easyfresher

How should passwords be stored: why do you need a salt and a slow hash, and how do you verify and upgrade stored hashes?

Never store passwords in plain text or with a fast hash such as SHA-256. Use a memory-hard, slow password hash (argon2id, scrypt or bcrypt) with a unique random salt per user, so identical passwords give different hashes and attackers cannot use precomputed tables. Store the algorithm, its parameters and the salt with the hash, compare with a constant-time check, and re-hash at login when the parameters are outdated.

Full answer

Why a plain hash is not enough

  • Fast hashes let an attacker with a stolen database test billions of guesses per second on a GPU.
  • Without a salt, equal passwords have equal hashes, and rainbow tables work.

What to do

  1. Use argon2id (preferred), scrypt or bcrypt. They are slow on purpose and (for argon2 and scrypt) need a lot of memory, which limits parallel guessing.
  2. Create a random salt (16 bytes or more) for every password. It is not secret. Store it next to the hash.
  3. Store everything needed to verify in one string, for example algorithm$params$salt$hash. This lets you change the cost later.
  4. Verify by recomputing with the stored salt and parameters, and compare with crypto.timingSafeEqual to avoid timing leaks.
  5. After a successful login, if the stored parameters are weaker than the current policy, hash again and update the record (rehash on login).
  6. Optionally add a pepper (a secret kept outside the database, for example in a key vault). Limit login attempts and use breached password checks. Enforce a sensible length limit, because very long inputs make hashing a denial of service vector.

Node.js ships with crypto.scrypt. Argon2 needs a library.

javascript
const crypto = require('node:crypto');
const { promisify } = require('node:util');
const scrypt = promisify(crypto.scrypt);

const PARAMS = { N: 16384, r: 8, p: 1, keylen: 32 };

async function hashPassword(password, params = PARAMS) {
  const salt = crypto.randomBytes(16);
  const key = await scrypt(password, salt, params.keylen, { N: params.N, r: params.r, p: params.p });
  return ['scrypt', params.N, params.r, params.p, salt.toString('base64'), key.toString('base64')].join('$');
}

async function verifyPassword(password, stored) {
  const [alg, N, r, p, salt, hash] = stored.split('$');
  if (alg !== 'scrypt') return { ok: false };
  const expected = Buffer.from(hash, 'base64');
  const key = await scrypt(password, Buffer.from(salt, 'base64'), expected.length, { N: +N, r: +r, p: +p });
  const ok = crypto.timingSafeEqual(key, expected);
  return { ok, needsRehash: ok && (+N < PARAMS.N || +r < PARAMS.r) };
}

(async () => {
  const a = await hashPassword('correct horse battery');
  const b = await hashPassword('correct horse battery');
  console.log('same password, different hashes:', a !== b);
  console.log('stored format                  :', a.split('$').slice(0, 4).join('$') + '$<salt>$<hash>');
  console.log('right password                 :', JSON.stringify(await verifyPassword('correct horse battery', a)));
  console.log('wrong password                 :', JSON.stringify(await verifyPassword('wrong', a)));

  const old = await hashPassword('secret', { N: 4096, r: 8, p: 1, keylen: 32 });
  console.log('old hash, right password       :', JSON.stringify(await verifyPassword('secret', old)), '(rehash with current cost and save it)');

  const sha = crypto.createHash('sha256').update('secret').digest('hex');
  console.log('plain SHA-256 is the same for every user of "secret":', sha === crypto.createHash('sha256').update('secret').digest('hex'));
})();

Uses the built-in crypto.scrypt. The cost of 16384 is a teaching value. Pick the cost from your own measurements and current guidance, and prefer argon2id when a library is allowed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): same password, different hashes: true stored format : scrypt$16384$8$1$<salt>$<hash> right password : {"ok":true,"needsRehash":false} wrong password : {"ok":false,"needsRehash":false} old hash, right password : {"ok":true,"needsRehash":true} (rehash with current cost and save it) plain SHA-256 is the same for every user of "secret": true

Key points

  • Use a slow, memory-hard password hash with a unique salt.
  • Store algorithm, parameters and salt with the hash.
  • Compare with a constant-time function.
  • Rehash at login when parameters are outdated.
  • Rate limit logins and set a maximum password length.

Common mistakes

  • Using MD5, SHA-1 or plain SHA-256 for passwords.
  • One global salt for all users.
  • Comparing hashes with ===.
  • Never raising the cost as hardware improves.
  • Allowing megabyte-long passwords.

Follow-ups

  • What does argon2id add over scrypt and bcrypt?
  • What is a pepper and where do you keep it?
  • How do you migrate users from an old hash to a new one?

Tips

  • Say 'slow, salted, constant-time compare'.
  • Mention rehash on login.
  • Name argon2id.
10.backend-0010Easyfresher

What are the differences between server-side sessions and JWT access tokens, and when do you choose each?

A session stores the login state on the server and gives the browser an opaque random id (usually in a cookie). A JWT is a signed token that carries claims, so servers can verify it without a lookup. Sessions are easy to revoke and small, but need shared storage. JWTs scale without a store but are hard to revoke before they expire, so keep them short lived and pair them with refresh tokens. Browser apps with one backend are often best served by sessions.

Full answer

Sessions

  • Login creates a record (user id, expiry, device) in a store such as Redis or a database. The client keeps only the random session id in a cookie (HttpOnly, Secure, SameSite).
  • Logging out or banning a user is immediate: delete the record.
  • Cost: a store lookup per request and shared storage for many servers.

JWT

  • Header.payload.signature, each part base64url encoded. Claims such as sub (user), iss, aud, exp. The server checks the signature and claims with a key, with no database call.
  • Cost: you cannot cancel a token before exp unless you keep a denylist (which is state again). Payload data is readable by anyone who holds the token, so never put secrets in it. Tokens are larger than session ids, and key rotation needs care.
  • Use short lifetimes (minutes) and a refresh token that is stored and revocable.

Choosing

  • One web app and one backend: server sessions (simple, safe, revocable).
  • Many services that must verify identity without calling an auth service, or mobile and third-party clients: short-lived access tokens (JWT), with revocable refresh tokens.
  • Do not call a JWT "more secure". Security depends on storage (HttpOnly cookie vs localStorage), expiry, validation and revocation.
javascript
const crypto = require('node:crypto');

// 1. Session: opaque id, state on the server.
const sessions = new Map();
const login = (user) => { const id = crypto.randomBytes(16).toString('hex'); sessions.set(id, { user, expires: Date.now() + 3600e3 }); return id; };
const checkSession = (id) => sessions.get(id)?.user ?? null;

// 2. JWT (HS256), built by hand to show the parts.
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
const SECRET = 'server-secret';
const sign = (data) => crypto.createHmac('sha256', SECRET).update(data).digest('base64url');
const issue = (claims) => { const body = `${b64({ alg: 'HS256', typ: 'JWT' })}.${b64(claims)}`; return `${body}.${sign(body)}`; };
function verify(token, now) {
  const [h, p, s] = token.split('.');
  if (!s || sign(`${h}.${p}`) !== s) return null;
  const claims = JSON.parse(Buffer.from(p, 'base64url').toString());
  return claims.exp > now ? claims : null;
}

const now = 1_800_000_000;
const sessionId = login('asha');
const token = issue({ sub: 'asha', exp: now + 900 });

console.log('session id length  :', sessionId.length, '| token length:', token.length);
console.log('both valid         :', checkSession(sessionId), '|', verify(token, now)?.sub);

sessions.delete(sessionId);                                              // logout or ban
console.log('after revocation   : session =', checkSession(sessionId), '| JWT still verifies =', verify(token, now + 60)?.sub);
console.log('after expiry       : JWT =', verify(token, now + 901));

const tampered = token.split('.'); tampered[1] = b64({ sub: 'admin', exp: now + 900 });
console.log('tampered payload   :', verify(tampered.join('.'), now));
console.log('payload is readable:', Buffer.from(token.split('.')[1], 'base64url').toString());

Both mechanisms are built with Node's crypto module in a few lines. Real systems use a tested library for JWT, and a fixed timestamp keeps the output stable. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): session id length : 32 | token length: 123 both valid : asha | asha after revocation : session = null | JWT still verifies = asha after expiry : JWT = null tampered payload : null payload is readable: {"sub":"asha","exp":1800000900}

Key points

  • Sessions keep state on the server; JWTs carry signed claims.
  • Sessions can be revoked at once; JWTs need short expiry or a denylist.
  • JWT payloads are encoded, not encrypted.
  • Use short access tokens with revocable refresh tokens.
  • Pick by architecture, not by fashion.

Common mistakes

  • Storing JWTs in localStorage where scripts can read them.
  • Long-lived JWTs that cannot be revoked.
  • Putting private data in the JWT payload.
  • Not validating exp, aud and iss.
  • Rolling your own signing code in production.

Follow-ups

  • How do you revoke a JWT before it expires?
  • Where should a browser app store tokens?
  • What is the benefit of a refresh token?

Tips

  • Compare state location.
  • Mention revocation first.
  • Say that payloads are readable.
11.backend-0011Mediummid

How does the OAuth 2.0 authorization code flow work, and what problem does PKCE solve?

In the authorization code flow the app sends the user to the authorization server, the user signs in and consents, and the server redirects back with a short-lived one-time code. The app exchanges the code at the token endpoint for an access token. PKCE (Proof Key for Code Exchange) protects that code: the app creates a random code_verifier, sends only its SHA-256 hash (code_challenge) at the start, and sends the verifier when exchanging. A stolen code is useless without the verifier. PKCE is now recommended for all clients.

Full answer

Roles: resource owner (the user), client (the app), authorization server (issues tokens), resource server (the API).

Steps

  1. The client creates a random state (to tie the response to the request, prevents CSRF) and a code_verifier (43 to 128 random characters). It computes code_challenge = BASE64URL(SHA256(code_verifier)).
  2. It redirects the browser to /authorize with client_id, redirect_uri, scope, state, code_challenge and code_challenge_method=S256.
  3. The user authenticates and approves. The server redirects to the exact registered redirect_uri with code and state.
  4. The client checks that state matches. Then it calls /token (server to server or app to server) with grant_type=authorization_code, code, redirect_uri and code_verifier.
  5. The server hashes the verifier, compares it with the stored challenge, checks the code is unused, unexpired and bound to this client and redirect URI, and returns the access token (and a refresh token or ID token).

What PKCE solves

  • On mobile and single-page apps there is no client secret. If an attacker intercepts the code (a malicious app on the same device, a leaked log or referrer), they cannot redeem it without the verifier that never left the legitimate app.
  • Servers should require S256 (not plain), keep codes valid for about a minute, and allow one use.
javascript
const crypto = require('node:crypto');
const b64url = (buf) => Buffer.from(buf).toString('base64url');
const challengeOf = (verifier) => crypto.createHash('sha256').update(verifier).digest('base64url');

// A very small authorization server.
const REGISTERED = { web: ['https://app.example.com/callback'] };
const codes = new Map();
function authorize({ client_id, redirect_uri, code_challenge, code_challenge_method, state }) {
  if (!REGISTERED[client_id]?.includes(redirect_uri)) return { error: 'invalid_redirect_uri' };
  if (code_challenge_method !== 'S256' || !code_challenge) return { error: 'pkce_required' };
  const code = b64url(crypto.randomBytes(16));
  codes.set(code, { client_id, redirect_uri, code_challenge, used: false });
  return { redirect: `${redirect_uri}?code=${code}&state=${state}` };
}
function token({ client_id, redirect_uri, code, code_verifier }) {
  const entry = codes.get(code);
  if (!entry || entry.used || entry.client_id !== client_id || entry.redirect_uri !== redirect_uri) return { error: 'invalid_grant' };
  entry.used = true;                                                  // one use only
  if (!code_verifier || challengeOf(code_verifier) !== entry.code_challenge) return { error: 'invalid_grant (PKCE check failed)' };
  return { access_token: 'at_' + b64url(crypto.randomBytes(8)) };
}

// The client side.
const verifier = b64url(crypto.randomBytes(32));
const state = b64url(crypto.randomBytes(8));
const request = { client_id: 'web', redirect_uri: 'https://app.example.com/callback', code_challenge: challengeOf(verifier), code_challenge_method: 'S256', state };
const params = (url) => Object.fromEntries(new URL(url).searchParams);

const reply = authorize(request);
const { code, state: returnedState } = params(reply.redirect);
console.log('verifier length          :', verifier.length, '| challenge length:', request.code_challenge.length);
console.log('state matches            :', returnedState === state);
console.log('attacker with stolen code:', JSON.stringify(token({ client_id: 'web', redirect_uri: request.redirect_uri, code })));

const reply2 = authorize(request);
const code2 = params(reply2.redirect).code;
console.log('app with verifier        :', Object.keys(token({ client_id: 'web', redirect_uri: request.redirect_uri, code: code2, code_verifier: verifier })).join(','));
console.log('same code again          :', JSON.stringify(token({ client_id: 'web', redirect_uri: request.redirect_uri, code: code2, code_verifier: verifier })));
console.log('wrong redirect_uri       :', JSON.stringify(authorize({ ...request, redirect_uri: 'https://evil.example/callback' })));
console.log('no PKCE                  :', JSON.stringify(authorize({ ...request, code_challenge: undefined })));

A toy authorization server in memory, to show the checks. A real server is an OAuth product or library, and this code is not production code. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): verifier length : 43 | challenge length: 43 state matches : true attacker with stolen code: {"error":"invalid_grant (PKCE check failed)"} app with verifier : access_token same code again : {"error":"invalid_grant"} wrong redirect_uri : {"error":"invalid_redirect_uri"} no PKCE : {"error":"pkce_required"}

Key points

  • The browser carries only a short-lived code; tokens come from a back channel call.
  • state links the callback to the original request.
  • PKCE sends a hash of a secret first and the secret later.
  • The code must be one-time and bound to client and redirect URI.
  • Use PKCE for all clients.

Common mistakes

  • Skipping the state check on the callback.
  • Allowing wildcard or prefix redirect URIs.
  • Using the implicit flow (tokens in the URL) for new apps.
  • Accepting the plain PKCE method.
  • Letting authorization codes be reused or live for a long time.

Follow-ups

  • What is the difference between OAuth 2.0 and OpenID Connect?
  • Why can a public client not keep a client secret?
  • What are scopes?

Tips

  • Walk through the steps in order.
  • Say 'hash first, secret later'.
  • Mention state and exact redirect URIs.
12.backend-0012Mediummid

What is OpenID Connect, how does an ID token differ from an access token, and which checks must a client make when it validates an ID token?

OAuth 2.0 is about authorization (what an app may access); OpenID Connect (OIDC) adds authentication on top: the ID token is a JWT that tells the client who signed in. The client validates the signature with the provider's public key (from its JWKS), pins the expected algorithm, and checks iss (issuer), aud (this client id), exp, iat and the nonce it sent. The ID token is for the client only. The access token is for calling APIs, and an API must not accept ID tokens as access tokens.

Full answer

OIDC basics

  • Same flows as OAuth (use the code flow with PKCE) with the scope openid. The token response adds an id_token. A /userinfo endpoint returns more claims, and a discovery document (/.well-known/openid-configuration) lists endpoints and the jwks_uri.
  • ID token claims: iss (who issued), sub (stable user id, unique per issuer), aud (client id), exp, iat, nonce, and optional profile claims (email, name).

Validation checklist

  1. Parse the header. Accept only the algorithm you expect (RS256 or ES256 as published by the provider). Never trust alg from the token, and reject none. This blocks algorithm confusion attacks (a token signed with HS256 using the public key as the secret).
  2. Find the key by kid in the provider's JWKS (cache it, refresh on unknown kid), and verify the signature.
  3. iss equals the issuer you configured, exactly.
  4. aud contains your client id.
  5. exp is in the future (allow a small clock skew), and iat is sensible.
  6. nonce equals the value you stored in the session at the start of the login (prevents replay of a token from another login).
  7. Identify users by the pair (iss, sub), not by email.

Access tokens may be opaque. Do not parse them in the client unless the provider documents their format.

javascript
const crypto = require('node:crypto');
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url');

function issue(claims, header = { alg: 'RS256', typ: 'JWT', kid: 'key-1' }, key = privateKey) {
  const body = `${b64(header)}.${b64(claims)}`;
  const sig = header.alg === 'RS256' ? crypto.sign('sha256', Buffer.from(body), key) : crypto.createHmac('sha256', publicKey.export({ type: 'spki', format: 'pem' })).update(body).digest();
  return `${body}.${sig.toString('base64url')}`;
}

function validateIdToken(token, { issuer, clientId, nonce, now }) {
  const [h, p, s] = token.split('.');
  const header = JSON.parse(Buffer.from(h, 'base64url')), claims = JSON.parse(Buffer.from(p, 'base64url'));
  if (header.alg !== 'RS256') return 'rejected: unexpected alg ' + header.alg;               // pinned algorithm
  if (!crypto.verify('sha256', Buffer.from(`${h}.${p}`), publicKey, Buffer.from(s, 'base64url'))) return 'rejected: bad signature';
  if (claims.iss !== issuer) return 'rejected: wrong issuer';
  if (![].concat(claims.aud).includes(clientId)) return 'rejected: wrong audience';
  if (claims.exp <= now - 60) return 'rejected: expired';
  if (claims.nonce !== nonce) return 'rejected: nonce mismatch';
  return `accepted: user key = ${claims.iss}|${claims.sub}`;
}

const now = 1_800_000_000;
const ctx = { issuer: 'https://id.example.com', clientId: 'my-client', nonce: 'n-123', now };
const good = { iss: ctx.issuer, sub: 'u-42', aud: 'my-client', exp: now + 600, iat: now, nonce: 'n-123' };

console.log('valid token       :', validateIdToken(issue(good), ctx));
console.log('wrong audience    :', validateIdToken(issue({ ...good, aud: 'other-app' }), ctx));
console.log('wrong issuer      :', validateIdToken(issue({ ...good, iss: 'https://evil.example' }), ctx));
console.log('expired           :', validateIdToken(issue({ ...good, exp: now - 3600 }), ctx));
console.log('nonce replay      :', validateIdToken(issue({ ...good, nonce: 'old' }), ctx));
console.log('tampered claims   :', validateIdToken(issue(good).replace(/\.[^.]+\./, '.' + b64({ ...good, sub: 'admin' }) + '.'), ctx));
console.log('alg confusion     :', validateIdToken(issue(good, { alg: 'HS256', typ: 'JWT' }), ctx));

A fresh RSA key pair is generated for each run, so only the results are printed, never the tokens. Real clients fetch the public key from the provider's JWKS and use a maintained library such as jose. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): valid token : accepted: user key = https://id.example.com|u-42 wrong audience : rejected: wrong audience wrong issuer : rejected: wrong issuer expired : rejected: expired nonce replay : rejected: nonce mismatch tampered claims : rejected: bad signature alg confusion : rejected: unexpected alg HS256

Key points

  • OIDC adds identity (an ID token) on top of OAuth 2.0.
  • The ID token is for the client; the access token is for APIs.
  • Check signature, algorithm, iss, aud, exp and nonce.
  • Pin the expected algorithm and fetch keys from the JWKS.
  • Use (iss, sub) as the user key.

Common mistakes

  • Using an ID token to call an API.
  • Not checking aud, so a token for another app is accepted.
  • Trusting the alg field from the token header.
  • Identifying users by email address.
  • Skipping nonce checks.

Follow-ups

  • What is a JWKS and how do you handle key rotation?
  • What is the difference between the UserInfo endpoint and ID token claims?
  • What does at_hash protect?

Tips

  • Contrast authentication with authorization.
  • List the checks quickly.
  • Mention algorithm pinning.
13.backend-0013Easyfresher

How should a service issue, store and validate API keys, and when are API keys the wrong tool?

An API key is a long random secret that identifies a calling application. Generate it with a secure random source, show it once, and store only a hash (a fast SHA-256 is fine because the key has high entropy) plus a short public prefix for lookup. Validate with a constant-time comparison, attach scopes, track last use, and support rotation and revocation. API keys identify apps, not users, so they are the wrong tool for end-user login or for fine-grained delegation (use OAuth).

Full answer

Design

  • Format: a readable prefix plus random bytes, for example sk_live_ab12cd34_<32 random bytes in base64url>. The prefix tells which environment the key is for, helps secret scanners find leaks, and gives a lookup id (ab12cd34).
  • Generate with crypto.randomBytes (at least 128 bits, 256 is common). Show the full key once at creation.
  • Store: prefix (indexed), SHA-256 of the secret part, owner, scopes, created, last used, expires, revoked flag. Never store the plain key. A slow password hash is not needed for random high entropy keys, and would slow every request.
  • Validate: parse the key, look up the record by prefix, hash the presented secret, compare with crypto.timingSafeEqual, then check revoked, expiry and scope for the endpoint.

Operations

  • Support more than one active key per account so keys can be rotated without downtime. Allow instant revocation.
  • Limit scope and rate per key. Log key id (never the key). Send keys in a header (Authorization: Bearer or X-API-Key), not in URLs, because URLs end up in logs.
  • Enable secret scanning and alert on leaks.

Limits of API keys

  • They are bearer secrets: whoever holds one is the app. They carry no user identity and no consent flow. Use OAuth 2.0 for user-delegated access and mutual TLS or signed requests for higher assurance.
javascript
const crypto = require('node:crypto');

const store = new Map();                                    // prefix -> record (a table in real life)
const sha256 = (s) => crypto.createHash('sha256').update(s).digest();

function createKey({ owner, scopes }) {
  const prefix = crypto.randomBytes(4).toString('hex');
  const secret = crypto.randomBytes(32).toString('base64url');
  store.set(prefix, { owner, scopes, hash: sha256(secret), revoked: false, lastUsed: null });
  return `sk_live_${prefix}_${secret}`;                     // returned once to the user
}

function authenticate(key, neededScope, now) {
  const match = /^sk_live_([0-9a-f]{8})_([\w-]{43})$/.exec(key || '');
  if (!match) return { ok: false, reason: 'malformed' };
  const record = store.get(match[1]);
  const given = sha256(match[2]);
  if (!record || !crypto.timingSafeEqual(given, record.hash)) return { ok: false, reason: 'invalid key' };
  if (record.revoked) return { ok: false, reason: 'revoked' };
  if (!record.scopes.includes(neededScope)) return { ok: false, reason: 'missing scope ' + neededScope };
  record.lastUsed = now;
  return { ok: true, owner: record.owner };
}

const key = createKey({ owner: 'billing-service', scopes: ['students:read'] });
console.log('key shape            :', key.replace(/_[0-9a-f]{8}_.+$/, '_<prefix>_<secret>'), '| secret length:', key.slice('sk_live_'.length + 9).length);
console.log('stored fields        :', Object.keys([...store.values()][0]).join(', '), '(no plain key)');
console.log('valid read           :', JSON.stringify(authenticate(key, 'students:read', 1)));
console.log('missing scope        :', JSON.stringify(authenticate(key, 'students:write', 2)));
console.log('altered secret       :', JSON.stringify(authenticate(key.slice(0, -1) + (key.endsWith('A') ? 'B' : 'A'), 'students:read', 3)));
store.get(key.split('_')[2]).revoked = true;
console.log('after revocation     :', JSON.stringify(authenticate(key, 'students:read', 4)));

In-memory demo with Node's crypto module. A real store is a database table with an index on the prefix. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): key shape : sk_live_<prefix>_<secret> | secret length: 43 stored fields : owner, scopes, hash, revoked, lastUsed (no plain key) valid read : {"ok":true,"owner":"billing-service"} missing scope : {"ok":false,"reason":"missing scope students:write"} altered secret : {"ok":false,"reason":"invalid key"} after revocation : {"ok":false,"reason":"revoked"}

Key points

  • Use random keys with a prefix; show them once.
  • Store a hash and a lookup prefix, never the key.
  • Compare in constant time and check scopes and revocation.
  • Support rotation with several active keys.
  • Keys identify apps, not users.

Common mistakes

  • Storing keys in plain text.
  • Putting API keys in URLs or front-end code.
  • One key forever, with no rotation.
  • No scopes, so every key can do everything.
  • Comparing keys with ===.

Follow-ups

  • Why is SHA-256 acceptable for API keys but not for passwords?
  • How would you rotate a key with zero downtime?
  • How do secret scanners find leaked keys?

Tips

  • Say 'show once, store hash'.
  • Mention prefix lookup.
  • State the limits: apps, not users.
14.backend-0014Hardsenior

What are the common security mistakes in OAuth 2.0 and OIDC implementations (redirect URI matching, state, implicit flow, token storage), and how do you prevent them?

The usual failures are: loose redirect URI matching (an attacker gets the code or token at their own URL), a missing state check (login CSRF), the implicit flow and tokens in URLs, missing PKCE, tokens stored where scripts can read them, accepting tokens for the wrong audience, and over-broad scopes. Prevent them with exact redirect URI comparison, state and PKCE on every login, the code flow only, short-lived tokens with rotation, audience checks, and server-side or HttpOnly cookie handling of tokens.

Full answer
  1. Redirect URI matching: the authorization server must compare the whole URI to a registered one, character by character. Prefix, wildcard or domain-only matching lets attackers use open redirects or look-alike hosts (https://app.example.com.evil.com) to receive the code.
  2. state (login CSRF): without it an attacker can make a victim's browser finish the attacker's login, linking the attacker's account. Generate state per request, bind it to the user's session, check it on the callback.
  3. Implicit flow and response_type=token: tokens appear in URLs, history and logs. OAuth 2.1 removes it. Use the code flow with PKCE.
  4. PKCE downgrade: if the server accepts an exchange when no challenge was sent, an attacker can skip PKCE. Require it for public clients, and reject the plain method.
  5. Token storage: tokens in localStorage can be stolen by any XSS. Prefer a backend for frontend (BFF) that keeps tokens server-side and gives the browser an HttpOnly, Secure, SameSite session cookie. Mobile apps use the OS secure storage.
  6. Audience and scope: APIs must check aud and scope. Do not accept ID tokens as access tokens. Request the least scope.
  7. Refresh tokens: rotate them on use and detect reuse (revoke the family). Bind or limit them for public clients.
  8. Mix-up and confused deputy: with several providers, check the iss of the response, and keep redirect URIs per provider.
  9. Open redirectors in your own app, tokens in logs and referrer headers, and long-lived tokens are common leak routes.
javascript
const registered = ['https://app.example.com/callback'];
const prefixMatch = (uri) => registered.some((r) => uri.startsWith(new URL(r).origin));       // a weak check
const exactMatch = (uri) => registered.includes(uri);                                          // the right check

const attempts = [
  'https://app.example.com/callback',
  'https://app.example.com.evil.net/callback',
  'https://app.example.com/callback/../open-redirect?to=https://evil.net',
  'https://app.example.com/other',
  'https://evil.net/callback',
];
console.log('redirect_uri'.padEnd(72), 'weak  exact');
for (const uri of attempts) console.log(uri.padEnd(72), String(prefixMatch(uri)).padEnd(5), exactMatch(uri));

// state is stored in the user's session at the start, and compared on the callback.
const sessionState = 'a1b2c3';
const callback = (queryState) => (queryState && queryState === sessionState ? 'continue login' : 'reject: state missing or different');
console.log('\ncallback with the right state :', callback('a1b2c3'));
console.log('callback forged by an attacker:', callback('zzz'));
console.log('callback with no state        :', callback(undefined));

// Token checks an API must do on every request
function checkAccessToken(claims, { audience, scope, now }) {
  if (claims.aud !== audience) return 'reject: token is for another API';
  if (claims.exp <= now) return 'reject: expired';
  if (!claims.scope.split(' ').includes(scope)) return 'reject: scope missing';
  return 'allow';
}
const now = 1_800_000_000;
console.log('\nright audience and scope      :', checkAccessToken({ aud: 'api://students', exp: now + 60, scope: 'read write' }, { audience: 'api://students', scope: 'read', now }));
console.log('ID token used as access token :', checkAccessToken({ aud: 'my-client', exp: now + 60, scope: 'openid' }, { audience: 'api://students', scope: 'read', now }));
console.log('token with too little scope   :', checkAccessToken({ aud: 'api://students', exp: now + 60, scope: 'read' }, { audience: 'api://students', scope: 'write', now }));

Pure functions that compare a weak and an exact redirect URI check, a state check and an access token check. No network is used. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): redirect_uri weak exact https://app.example.com/callback true true https://app.example.com.evil.net/callback true false https://app.example.com/callback/../open-redirect?to=https://evil.net true false https://app.example.com/other true false https://evil.net/callback false false callback with the right state : continue login callback forged by an attacker: reject: state missing or different callback with no state : reject: state missing or different right audience and scope : allow ID token used as access token : reject: token is for another API token with too little scope : reject: scope missing

Key points

  • Compare redirect URIs exactly.
  • Always use state and PKCE; use the code flow only.
  • Keep tokens out of JavaScript reachable storage when you can.
  • Check audience and scope in every API.
  • Rotate refresh tokens and detect reuse.

Common mistakes

  • Registering http://localhost and wildcards in production.
  • Treating a valid token as proof of permission without scope checks.
  • Keeping long-lived access tokens in localStorage.
  • Allowing the implicit flow because an old library does.
  • Logging full callback URLs (codes and tokens end up in logs).

Follow-ups

  • What is a backend for frontend (BFF)?
  • How does refresh token reuse detection work?
  • What changed from OAuth 2.0 to OAuth 2.1?

Tips

  • Name the attack for each pitfall.
  • Mention the BFF.
  • End with token validation at the API.
15.backend-0015Easyfresher

What is the cache-aside pattern, how do you implement it with Redis and a TTL, and what must you do when data changes?

In cache-aside (lazy loading) the application checks the cache first. On a hit it returns the cached value. On a miss it reads the database, stores the result in the cache with a TTL, and returns it. When data changes, the application updates the database and deletes the cache key (it is safer to delete than to update), so the next read reloads fresh data. The TTL is a safety net that limits how long a stale value can live.

Full answer

Read path

  1. GET key from the cache. If found, return it (hit).
  2. If not found (miss), query the database.
  3. Store the value with SET key value EX ttl, then return it.

Write path

  • Update the database first, then DELETE the cache key. Deleting is simpler and safer than writing the new value, because concurrent writers could leave the cache with the older value if their cache writes arrive out of order.
  • A short window of stale data is still possible (a reader loaded the old row just before the update and writes it after the delete). A TTL bounds this.

Details

  • Choose the TTL from how stale data may be: seconds for prices or stock, minutes or hours for reference data. Add random jitter so many keys do not expire together.
  • Negative caching: also cache "not found" for a short time so repeated lookups of missing ids do not hit the database.
  • Key design: include a prefix, entity and version, for example student:v1:42.
  • The application must work when the cache is down (fall back to the database, with protection against overload).
  • Serialise values (JSON). Keep values small. Never cache per-user private data under a shared key.
javascript
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);

const db = { 42: { id: 42, name: 'Asha' } };                 // a stand-in for the database
let dbReads = 0;
const loadFromDb = async (id) => { dbReads++; return db[id] ?? null; };

async function getStudent(id) {
  const key = `bk15:student:${id}`;
  const cached = await redis.get(key);
  if (cached !== null) return { source: 'cache', value: JSON.parse(cached) };
  const value = await loadFromDb(id);
  // a missing row is cached for a short time, found rows for longer
  await redis.set(key, JSON.stringify(value), 'EX', value ? 60 : 5);
  return { source: 'database', value };
}

async function updateStudent(id, changes) {
  db[id] = { ...db[id], ...changes };                        // 1. write the database
  await redis.del(`bk15:student:${id}`);                     // 2. then delete the cache key
}

(async () => {
  await redis.del('bk15:student:42', 'bk15:student:99');
  const show = (label, r) => console.log(label.padEnd(26), r.source.padEnd(9), JSON.stringify(r.value));
  show('first read', await getStudent(42));
  show('second read', await getStudent(42));
  console.log('TTL on the key (seconds)  :', await redis.ttl('bk15:student:42'));
  await updateStudent(42, { name: 'Asha Rao' });
  show('after update', await getStudent(42));
  show('missing id', await getStudent(99));
  show('missing id again', await getStudent(99));
  console.log('database reads in total   :', dbReads);
  await redis.del('bk15:student:42', 'bk15:student:99');
  redis.disconnect();
})();

Runs against the local Redis server. The 'database' is a plain object with a read counter, so the effect of the cache can be counted. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): first read database {"id":42,"name":"Asha"} second read cache {"id":42,"name":"Asha"} TTL on the key (seconds) : 60 after update database {"id":42,"name":"Asha Rao"} missing id database null missing id again cache null database reads in total : 3

Key points

  • Check the cache, on a miss read the database and fill the cache.
  • On updates, write the database and delete the key.
  • TTL limits staleness and memory.
  • Cache missing results briefly (negative caching).
  • The system must still work when the cache is unavailable.

Common mistakes

  • Updating the cache value instead of deleting it, with racing writers.
  • No TTL, so stale or unused data stays forever.
  • Caching null results forever.
  • Using one global key for per-user data.
  • Letting a cache outage take down the whole service.

Follow-ups

  • What is read-through compared with cache-aside?
  • Why delete the key instead of setting it on update?
  • How do you choose a TTL?

Tips

  • Describe read path and write path separately.
  • Say 'delete, not update'.
  • Mention TTL and negative caching.
16.backend-0016Easyfresher

How do the caching strategies cache-aside, read-through, write-through and write-behind differ, and what are their trade-offs?

Cache-aside: the application manages the cache. Read-through: the cache loads from the database on a miss for you. Write-through: every write goes to the cache and the database together, so reads are fresh but writes are slower. Write-behind (write-back): writes go to the cache and are saved to the database later in batches, which is fast and merges repeated updates, but data can be lost if the cache fails before the flush.

Full answer
  • Cache-aside: the app reads the cache, on a miss loads the database and fills the cache. The app deletes keys on writes. Flexible, the most common. Stale data is possible until a delete or the TTL.
  • Read-through: the cache layer itself fetches from the database on a miss (the app only talks to the cache). Same freshness as cache-aside, less code in the app, depends on the cache product.
  • Write-through: a write updates the cache and the database in the same operation (the write is complete only when both succeeded). Reads after a write are fresh, but each write is as slow as the database, and rarely read data fills the cache.
  • Write-behind: a write updates the cache and returns. A background job flushes changes to the database later. Very fast writes, repeated updates to one key become one database write (coalescing). Risk: data loss if the cache node dies before the flush, and the database is briefly out of date, which complicates other readers.
  • Write-around: write to the database only, and let the cache fill on reads.

Choosing: cache-aside for most services. Write-through when reads must see the latest value and the write rate is modest. Write-behind only for data you can afford to lose a little of (counters, view counts, analytics), with a durable queue or a log when you cannot.

javascript
// Simulated database and cache with counters, to compare the write strategies.
const makeDb = () => ({ rows: new Map(), writes: 0, write(k, v) { this.writes++; this.rows.set(k, v); } });

function writeThrough(db) {
  const cache = new Map();
  return { cache, write(k, v) { db.write(k, v); cache.set(k, v); } };       // both, before returning
}

function writeBehind(db) {
  const cache = new Map(), dirty = new Set();
  return {
    cache,
    write(k, v) { cache.set(k, v); dirty.add(k); },                          // returns at once
    flush() { for (const k of dirty) db.write(k, cache.get(k)); dirty.clear(); },
    crash() { cache.clear(); dirty.clear(); },                               // the cache node dies
  };
}

const updates = Array.from({ length: 5 }, (_, i) => ['views:page1', 100 + i]);   // the same counter updated 5 times

const db1 = makeDb(), wt = writeThrough(db1);
updates.forEach(([k, v]) => wt.write(k, v));
console.log('write-through: database writes =', db1.writes, '| database value =', db1.rows.get('views:page1'));

const db2 = makeDb(), wb = writeBehind(db2);
updates.forEach(([k, v]) => wb.write(k, v));
console.log('write-behind : before flush, database writes =', db2.writes, '| database value =', db2.rows.get('views:page1'));
wb.flush();
console.log('write-behind : after flush,  database writes =', db2.writes, '| database value =', db2.rows.get('views:page1'));

const db3 = makeDb(), wb2 = writeBehind(db3);
updates.forEach(([k, v]) => wb2.write(k, v));
wb2.crash();
wb2.flush();
console.log('write-behind : crash before flush, database has the value =', db3.rows.has('views:page1'), '(updates lost)');

Counters show the cost of each strategy. This is a model, not a Redis test, and real write-behind systems use durable queues to reduce loss. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): write-through: database writes = 5 | database value = 104 write-behind : before flush, database writes = 0 | database value = undefined write-behind : after flush, database writes = 1 | database value = 104 write-behind : crash before flush, database has the value = false (updates lost)

Key points

  • Cache-aside is app-managed; read-through is cache-managed.
  • Write-through keeps cache and database in step at the cost of write latency.
  • Write-behind is fast and batches writes but can lose data.
  • Pick by freshness need and loss tolerance.
  • Most systems start with cache-aside.

Common mistakes

  • Using write-behind for money or orders.
  • Expecting write-through to make the cache and database atomic across crashes.
  • Caching write-through data that is never read.
  • No monitoring of the flush backlog in write-behind.
  • Mixing strategies for the same key.

Follow-ups

  • How does a write-ahead log help write-behind?
  • What happens in write-through if the cache update fails after the database write?
  • When is write-around a good choice?

Tips

  • Define each in one line.
  • Give the main risk of each.
  • Name an example use case.
17.backend-0017Mediummid

How does HTTP caching work: what do Cache-Control, ETag, If-None-Match, Last-Modified and Vary do, and how do you cache static files versus API responses?

Cache-Control tells browsers and shared caches how long a response is fresh (max-age, s-maxage) and who may store it (public, private, no-store). When a response is stale, the cache revalidates: it sends the validator (If-None-Match with the ETag, or If-Modified-Since) and the server answers 304 Not Modified with no body if nothing changed. Vary says which request headers change the response. Fingerprinted static files get a very long max-age with immutable. APIs usually use no-cache (revalidate each time) or short lifetimes.

Full answer

Freshness

  • Cache-Control: max-age=N (seconds, browser and shared caches), s-maxage=N (shared caches such as a CDN). While fresh, the cache answers without contacting the server.
  • public allows shared caches. private means only the browser may store it (user-specific data). no-store means do not store at all (sensitive data). no-cache means store but revalidate before every use. immutable says the file never changes during its freshness.

Validation

  • The server sends ETag: "v7" (or Last-Modified). After the response is stale, the client asks GET with If-None-Match: "v7". If unchanged, the server answers 304 and no body, which saves bandwidth and time.

Vary

  • Vary: Accept-Encoding (or Accept-Language, Origin) tells caches to keep separate copies per header value. Vary: Cookie makes shared caching almost useless.

Patterns

  • Static assets with a content hash in the file name (app.3f9a.js): Cache-Control: public, max-age=31536000, immutable. To release, change the name.
  • HTML and API responses: Cache-Control: no-cache plus an ETag (always revalidate, usually a 304), or a short max-age with stale-while-revalidate.
  • Personal data: private, no-store.
  • Do not cache POST responses by default. Keep error responses short lived.
javascript
const http = require('node:http');
const crypto = require('node:crypto');

let requestsSeen = 0;
const price = { value: 100 };
const server = http.createServer((req, res) => {
  requestsSeen++;
  if (req.url === '/app.3f9a.js') {
    res.writeHead(200, { 'cache-control': 'public, max-age=31536000, immutable' }); return res.end('console.log("app")');
  }
  if (req.url === '/api/price') {
    const body = JSON.stringify(price);
    const etag = '"' + crypto.createHash('sha1').update(body).digest('hex').slice(0, 8) + '"';
    if (req.headers['if-none-match'] === etag) { res.writeHead(304, { etag }); return res.end(); }
    res.writeHead(200, { etag, 'cache-control': 'no-cache', vary: 'Accept-Encoding', 'content-type': 'application/json' }); return res.end(body);
  }
  res.writeHead(200, { 'cache-control': 'private, no-store' }); res.end('{"me":"asha"}');
});

// A very small browser cache.
const cache = new Map(); let clock = 0;
async function get(path) {
  const entry = cache.get(path);
  const url = `http://127.0.0.1:${server.address().port}${path}`;
  if (entry && entry.freshUntil > clock) return 'served from cache, no request';
  const r = await fetch(url, { headers: entry?.etag ? { 'if-none-match': entry.etag } : {} });
  if (r.status === 304) return 'revalidated: 304, body reused (' + entry.body + ' bytes saved)';
  const body = await r.text();
  const cc = r.headers.get('cache-control') || '';
  const maxAge = /max-age=(\d+)/.exec(cc)?.[1];
  if (!/no-store/.test(cc)) cache.set(path, { etag: r.headers.get('etag'), body: body.length, freshUntil: maxAge ? clock + Number(maxAge) : 0 });
  return `200 from server, cache-control: ${cc}`;
}

server.listen(0, '127.0.0.1', async () => {
  for (const path of ['/app.3f9a.js', '/app.3f9a.js', '/api/price', '/api/price', '/api/me', '/api/me']) console.log(path.padEnd(14), await get(path));
  price.value = 120;
  console.log('price changed  ', await get('/api/price'));
  clock += 86400 * 30;
  console.log('30 days later  ', await get('/app.3f9a.js'));
  console.log('requests that reached the server:', requestsSeen);
  server.close();
});

A small server and a simplified browser cache with a fake clock (real browsers add heuristics and more rules). The count of requests at the end shows what the cache saved. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): /app.3f9a.js 200 from server, cache-control: public, max-age=31536000, immutable /app.3f9a.js served from cache, no request /api/price 200 from server, cache-control: no-cache /api/price revalidated: 304, body reused (13 bytes saved) /api/me 200 from server, cache-control: private, no-store /api/me 200 from server, cache-control: private, no-store price changed 200 from server, cache-control: no-cache 30 days later served from cache, no request requests that reached the server: 6

Key points

  • max-age sets freshness; s-maxage targets shared caches.
  • ETag with If-None-Match gives cheap revalidation (304).
  • no-cache means revalidate; no-store means never keep.
  • Vary separates cached variants by request header.
  • Fingerprint static files and cache them for a year.

Common mistakes

  • Using no-cache when you meant no-store for secrets.
  • Long max-age on files without a content hash in the name.
  • Vary: Cookie on public pages.
  • Forgetting that a CDN follows s-maxage and Vary.
  • Weak or missing ETags on large API responses.

Follow-ups

  • What is stale-while-revalidate?
  • How does the Age header relate to max-age?
  • How do you cache an API response per user safely?

Tips

  • Separate freshness from validation.
  • Give the static file recipe.
  • Mention Vary.
18.backend-0018Hardsenior

What is a cache stampede (thundering herd), and how do you prevent it with locks, request coalescing and TTL jitter?

A stampede happens when a hot cache key expires and many requests miss at once, so they all hit the database to rebuild the same value and may overload it. Prevent it by letting only one request rebuild: coalesce concurrent callers in a process (single-flight), use a short distributed lock (SET NX PX) across processes while the others wait or serve stale data, add random jitter to TTLs so keys do not expire together, and refresh popular keys before they expire.

Full answer

The problem

  • A key with 5,000 requests per second expires. During the 100 ms that the database query takes, 500 requests miss and send the same query. The database slows down, rebuilds take longer, more requests pile up, and the system can collapse.

Defences

  1. Single-flight (request coalescing) inside one process: keep a map of key to the in-flight promise. The first miss starts the load, the others await the same promise.
  2. Distributed lock for many processes: SET lock:key token NX PX 2000. The winner loads and fills the cache, and releases the lock only if it still owns it (compare the token in a Lua script). The losers wait briefly and re-read the cache, or return stale data.
  3. TTL jitter: add 10 to 20 percent random time to each TTL so keys created together do not expire together.
  4. Early refresh or stale-while-revalidate: store a soft expiry. After it, serve the old value and refresh in the background. Probabilistic early expiration (refresh a bit before expiry with growing probability) also spreads the load.
  5. Warm important keys on deploy, and protect the database with timeouts, a concurrency limit and a circuit breaker.

Always give the lock a TTL (a crashed winner must not block forever) and a waiting limit, and fall back to loading the value yourself when the wait ends.

javascript
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

let dbCalls = 0;
const slowQuery = async () => { dbCalls++; await sleep(50); return 'expensive result'; };

async function naive(key) {
  const hit = await redis.get(key);
  if (hit) return hit;
  const value = await slowQuery();
  await redis.set(key, value, 'EX', 30);
  return value;
}

const RELEASE_LOCK = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
async function withLock(key) {
  for (let attempt = 0; attempt < 50; attempt++) {
    const hit = await redis.get(key);
    if (hit) return hit;
    const token = Math.random().toString(36).slice(2);
    if (await redis.set(`lock:${key}`, token, 'PX', 2000, 'NX')) {         // only one caller gets the lock
      try {
        const value = await slowQuery();
        await redis.set(key, value, 'EX', 30 + Math.floor(Math.random() * 6));    // TTL with jitter
        return value;
      } finally { await redis.eval(RELEASE_LOCK, 1, `lock:${key}`, token); }
    }
    await sleep(10);                                                        // others wait and look again
  }
  return slowQuery();                                                       // give up waiting, load it ourselves
}

(async () => {
  await redis.del('bk18:a', 'bk18:b', 'lock:bk18:b');
  await Promise.all(Array.from({ length: 20 }, () => naive('bk18:a')));
  console.log('20 concurrent misses, no protection :', dbCalls, 'database calls');

  dbCalls = 0;
  const results = await Promise.all(Array.from({ length: 20 }, () => withLock('bk18:b')));
  console.log('20 concurrent misses, with a lock   :', dbCalls, 'database call | all got the value:', results.every((r) => r === 'expensive result'));
  const ttl = await redis.ttl('bk18:b');
  console.log('TTL is inside the jitter range      :', ttl >= 29 && ttl <= 35);
  console.log('lock released after the load        :', (await redis.exists('lock:bk18:b')) === 0);
  await redis.del('bk18:a', 'bk18:b');
  redis.disconnect();
})();

Runs against the local Redis server with a 50 ms fake query. Twenty requests start together, and the database call count is the measurement. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 20 concurrent misses, no protection : 20 database calls 20 concurrent misses, with a lock : 1 database call | all got the value: true TTL is inside the jitter range : true lock released after the load : true

Key points

  • Many concurrent misses on one key overload the database.
  • Single-flight lets one caller rebuild and others share the result.
  • A lock with a TTL and an owner token works across processes.
  • Jitter and early refresh avoid synchronised expiry.
  • Add timeouts and fallbacks to every wait.

Common mistakes

  • A lock with no expiry that blocks everyone after a crash.
  • Releasing a lock with DEL without checking the owner.
  • Everyone waiting forever instead of falling back.
  • Setting the same TTL for all keys.
  • Protecting the cache but not the database behind it.

Follow-ups

  • How does probabilistic early expiration work?
  • When would you serve stale data instead of waiting?
  • How is single-flight different from a distributed lock?

Tips

  • Explain the failure chain first.
  • List four defences.
  • Mention token-checked release.
19.backend-0019Hardsenior

How do you handle cache invalidation across layers (browser, CDN, application cache), and when do you choose purging, versioned URLs or short TTLs?

Prefer designs where invalidation is not needed: immutable, versioned (content-hashed) URLs for assets, and short TTLs with revalidation for data. When content must change at a fixed URL, use explicit purging (by URL or by tag or surrogate key) at the CDN, plus stale-while-revalidate to hide revalidation cost. Choose the mix by how stale a response may be, how expensive the origin is, and how many layers hold copies.

Full answer

Layers

  • Browser cache, CDN or edge cache, reverse proxy, application cache (Redis), database buffers. Each layer has its own TTL, so the worst-case staleness is roughly the sum of what you allow on each path.

Strategies

  1. Versioned (fingerprinted) URLs: app.3f9a.js or /v42/config.json. A new version is a new URL, so the old copies are never wrong. Cache for a year. Best for static assets.
  2. TTL only: accept staleness up to max-age or s-maxage. Simple. Good for public listings and non-critical data.
  3. Revalidation: no-cache plus ETag. Always correct, costs a conditional request (304) per use. Pair with stale-while-revalidate and stale-if-error for speed and resilience.
  4. Purge: on change, call the CDN API to remove a URL, a prefix, or all objects with a tag (surrogate key, for example product-42). Fast but needs reliable event hooks, and purge propagation is not instant everywhere. Browser copies are not purged.
  5. Event-based invalidation for application caches: delete the key on write, or publish an invalidation message for local caches in many instances.

Design guidelines

  • Separate content by volatility (static assets, shared pages, personalised data).
  • Never cache personalised responses in shared caches (Cache-Control: private, correct Vary).
  • Keep keys predictable and tag related objects.
  • Measure hit ratio and stale reads, and always test the failure of invalidation (what is the maximum staleness if the purge fails?).
javascript
const crypto = require('node:crypto');

// 1. A content hash in the file name makes the URL change with the content.
const fingerprint = (name, content) => name.replace(/(\.\w+)$/, '.' + crypto.createHash('sha256').update(content).digest('hex').slice(0, 8) + '$1');
console.log('v1 file name :', fingerprint('app.js', 'console.log(1)'));
console.log('v2 file name :', fingerprint('app.js', 'console.log(2)'), '(new content, new URL, nothing to purge)');
console.log('same content :', fingerprint('app.js', 'console.log(1)') === fingerprint('app.js', 'console.log(1)'));

// 2. How a shared cache treats a response of a given age.
const parse = (header) => Object.fromEntries(header.split(',').map((p) => p.trim().split('=')).map(([k, v]) => [k.toLowerCase(), v === undefined ? true : Number(v)]));
function freshness(header, ageSeconds) {
  const cc = parse(header);
  const maxAge = cc['s-maxage'] ?? cc['max-age'] ?? 0;
  if (cc['no-store']) return 'never stored';
  if (cc['no-cache']) return 'stored, but must revalidate every time';
  if (ageSeconds < maxAge) return 'fresh: served from cache';
  if (cc['stale-while-revalidate'] && ageSeconds < maxAge + cc['stale-while-revalidate']) return 'stale: served now, refreshed in the background';
  return 'expired: the origin is asked again';
}
const policy = 'public, s-maxage=60, stale-while-revalidate=300';
for (const age of [10, 90, 400]) console.log(`age ${String(age).padEnd(3)} with "${policy}" ->`, freshness(policy, age));
console.log('no-cache      ->', freshness('no-cache', 5));
console.log('private, no-store ->', freshness('private, no-store', 5));

// 3. Purging by tag: which cached URLs carry the tag product-42?
const cdn = new Map([['/p/42', ['product-42']], ['/p/42/reviews', ['product-42', 'reviews']], ['/p/7', ['product-7']]]);
const purgeTag = (tag) => { const gone = [...cdn].filter(([, tags]) => tags.includes(tag)).map(([url]) => url); gone.forEach((u) => cdn.delete(u)); return gone; };
console.log('purge tag product-42 removes:', purgeTag('product-42').join(', '), '| left:', [...cdn.keys()].join(', '));

Small functions model fingerprinted names, the freshness decision of a shared cache, and tag-based purge. Real CDNs add their own rules and propagation delays. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): v1 file name : app.0a286891.js v2 file name : app.f2ae6bd0.js (new content, new URL, nothing to purge) same content : true age 10 with "public, s-maxage=60, stale-while-revalidate=300" -> fresh: served from cache age 90 with "public, s-maxage=60, stale-while-revalidate=300" -> stale: served now, refreshed in the background age 400 with "public, s-maxage=60, stale-while-revalidate=300" -> expired: the origin is asked again no-cache -> stored, but must revalidate every time private, no-store -> never stored purge tag product-42 removes: /p/42, /p/42/reviews | left: /p/7

Key points

  • Fingerprinted URLs avoid invalidation for static assets.
  • TTL, revalidation and purging trade freshness against load.
  • Surrogate keys let a CDN purge related objects together.
  • Browser caches cannot be purged, so choose max-age carefully.
  • Know the worst-case staleness across all layers.

Common mistakes

  • Purging as the only plan with no maximum staleness.
  • Long max-age on non-fingerprinted files.
  • Caching personalised pages in the CDN.
  • Forgetting the browser layer.
  • Never measuring the hit ratio.

Follow-ups

  • What is stale-if-error?
  • How do surrogate keys work?
  • How would you cache an API with per-user authorization?

Tips

  • List layers first.
  • Prefer versioned URLs.
  • Describe the worst-case staleness.
20.backend-0020Easyfresher

What is the difference between a message queue and publish/subscribe, and when do you use each?

A queue holds messages until a consumer takes them. With several consumers on one queue each message is processed by exactly one of them (competing consumers), which spreads work. In publish/subscribe a publisher sends an event to a topic and every subscriber receives its own copy (fan-out). Queues are for tasks (send this email), pub/sub is for notifications (an order was placed). Brokers such as Kafka, RabbitMQ and SQS/SNS combine both ideas.

Full answer

Queue (point to point)

  • Producers add messages. Consumers take messages. A message goes to one consumer, then it is acknowledged and removed. Adding consumers increases throughput. Use it for jobs: send email, resize image, charge a card.
  • The queue buffers bursts and decouples producer speed from consumer speed (load levelling).

Publish/subscribe

  • A publisher sends to a topic and does not know who listens. Each subscriber (or subscriber group) receives every message. Use it for events that several systems care about: the billing, email and analytics services all react to order.placed.
  • Plain Redis pub/sub is fire and forget: a subscriber that is offline misses messages. Durable brokers (Kafka, SNS with SQS, RabbitMQ with durable queues) store messages per subscriber.

Combined pattern

  • Publish an event to a topic, and give each subscribing service its own queue. Each service then processes events independently with its own retries, and scales its own consumers.

Questions to ask: must the message survive a restart (durability)? Does one or every consumer process it? Is order needed? What happens when the consumer fails?

javascript
const Redis = require('ioredis');
const url = process.env.REDIS_URL;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

(async () => {
  const admin = new Redis(url);
  await admin.del('bk20:jobs');

  // 1. Queue: two consumers compete for six jobs.
  await admin.lpush('bk20:jobs', ...[1, 2, 3, 4, 5, 6].map((n) => `job-${n}`));
  const taken = { A: [], B: [] };
  const consumer = async (name) => {
    const conn = new Redis(url);
    for (;;) {
      const item = await conn.brpop('bk20:jobs', 1);
      if (!item) break;
      taken[name].push(item[1]);
      await sleep(5);
    }
    conn.disconnect();
  };
  await Promise.all([consumer('A'), consumer('B')]);
  const all = [...taken.A, ...taken.B].sort();
  console.log('queue: every job handled once :', all.join(',') === 'job-1,job-2,job-3,job-4,job-5,job-6');
  console.log('queue: work was shared        :', taken.A.length > 0 && taken.B.length > 0, '| total =', taken.A.length + taken.B.length);

  // 2. Pub/sub: every subscriber receives each message.
  const received = { s1: [], s2: [], late: [] };
  const subscribe = async (name) => {
    const sub = new Redis(url);
    await sub.subscribe('bk20:events');
    sub.on('message', (_, msg) => received[name].push(msg));
    return sub;
  };
  const s1 = await subscribe('s1'), s2 = await subscribe('s2');
  for (const m of ['order.placed #1', 'order.placed #2', 'order.placed #3']) await admin.publish('bk20:events', m);
  await sleep(50);
  const late = await subscribe('late');                           // subscribes after the messages were sent
  await sleep(50);
  console.log('pub/sub: s1 got', received.s1.length, '| s2 got', received.s2.length, '| late subscriber got', received.late.length, '(missed earlier messages)');
  [s1, s2, late].forEach((c) => c.disconnect());
  admin.disconnect();
})();

Runs on the local Redis server with a list as the queue (LPUSH and BRPOP) and with Redis pub/sub. Which consumer takes which job varies, so only totals are printed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): queue: every job handled once : true queue: work was shared : true | total = 6 pub/sub: s1 got 3 | s2 got 3 | late subscriber got 0 (missed earlier messages)

Key points

  • A queue delivers each message to one consumer.
  • Pub/sub delivers each message to every subscriber.
  • Queues spread work and absorb bursts.
  • Redis pub/sub does not store messages for absent subscribers.
  • Each subscriber service usually has its own durable queue.

Common mistakes

  • Using pub/sub when a task must be processed exactly by one worker.
  • Expecting Redis pub/sub to store messages.
  • A queue with no consumer monitoring or backlog alert.
  • Treating a queue as a database.
  • Sharing one queue between subscribers that need every message.

Follow-ups

  • What is a consumer group in Kafka?
  • How do SNS and SQS work together?
  • How does a queue help when traffic spikes?

Tips

  • Start with 'one consumer or all consumers'.
  • Give a task example and an event example.
  • Mention durability.