← Interview prep

Backend interview questions

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

50 questions · Page 3 of 3

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

Page 3 of 3

Questions 41–50 of 50 · 0 of 10 on this page marked learned

41.backend-0041Easyfresher

What is the test pyramid, how do unit, integration and end-to-end tests differ for a backend service, and how do you balance them?

The test pyramid says to write many fast, focused unit tests, fewer integration tests that check real collaboration (a database, a message broker, an HTTP boundary), and very few slow end-to-end tests of whole user journeys. The shape follows cost: lower tests are cheap, fast and precise about failures, while higher tests give more confidence per test but are slow, flaky and hard to debug. Many backend teams use a 'trophy' variant with more integration tests, because most bugs live at the boundaries.

Full answer

Layers

  • Unit tests: one function or class, with no network or database. Milliseconds. They check business rules (price calculation, validation) and edge cases. Test doubles replace collaborators.
  • Integration tests: several parts together with real infrastructure: the repository against a real PostgreSQL, the HTTP layer with real routing and serialisation, the consumer with a real queue. Seconds. They catch SQL mistakes, mapping errors and configuration problems that unit tests cannot see.
  • Contract tests: check the agreement between two services without running both (see the contract testing item).
  • End-to-end tests: a deployed system through its public interface. Minutes, more flaky. Keep a small set for critical journeys (sign up, pay).

Guidelines

  • Push each check to the lowest level that can prove it.
  • Make tests deterministic: control time, random values and ids; use isolated data per test; avoid sleeps.
  • Test behaviour, not implementation details, so refactoring does not break tests.
  • Run unit tests on every change and integration tests in CI with disposable containers or databases. Track flaky tests and fix or remove them.
  • Coverage is a signal, not a goal. Mutation testing and production monitoring complement it.
javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pyramid-'));
fs.writeFileSync(path.join(dir, 'app.test.js'), `
const { describe, it, before, after } = require('node:test');
const assert = require('node:assert');
const http = require('node:http');
const { Client } = require(${JSON.stringify(require.resolve('pg'))});

const price = (qty, unit, discount = 0) => Math.round(qty * unit * (1 - discount) * 100) / 100;     // business rule

describe('unit: price rules', () => {
  it('multiplies quantity and unit price', () => assert.strictEqual(price(3, 9.99), 29.97));
  it('applies a discount', () => assert.strictEqual(price(2, 50, 0.1), 90));
  it('handles zero quantity', () => assert.strictEqual(price(0, 50), 0));
});

describe('integration: real PostgreSQL', () => {
  it('stores and reads a row', async () => {
    const db = new Client(); await db.connect();
    await db.query('CREATE TEMP TABLE t (id int, name text)');
    await db.query("INSERT INTO t VALUES (1, 'Asha')");
    assert.strictEqual((await db.query('SELECT name FROM t WHERE id = 1')).rows[0].name, 'Asha');
    await db.end();
  });
});

describe('end to end style: a real HTTP request', () => {
  let server;
  before(() => new Promise((resolve) => { server = http.createServer((req, res) => res.end(JSON.stringify({ total: price(2, 50, 0.1) }))).listen(0, resolve); }));
  after(() => server.close());
  it('returns the total over HTTP', async () => {
    const body = await (await fetch('http://127.0.0.1:' + server.address().port + '/orders/1')).json();
    assert.deepStrictEqual(body, { total: 90 });
  });
});
`);

const run = spawnSync(process.execPath, ['--test', '--test-reporter=tap', path.join(dir, 'app.test.js')], { encoding: 'utf8', env: process.env });
const lines = run.stdout.split('\n');
const groups = lines.filter((l) => /^# Subtest: (unit|integration|end to end)/.test(l)).map((l) => l.replace('# Subtest: ', ''));
console.log('test groups :', groups.join(' | '));
for (const key of ['tests', 'pass', 'fail']) console.log(key.padEnd(12), ':', (lines.find((l) => l.startsWith('# ' + key + ' ')) || '').split(' ').pop());

const pyramid = [['end-to-end', 1], ['integration', 1], ['unit', 3]];
console.log('\nthe run above, drawn as a pyramid (one # per test):');
for (const [name, n] of pyramid) console.log(name.padStart(12), '|', '#'.repeat(n));
fs.rmSync(dir, { recursive: true });

A temporary test file with three tiers is run with node --test against the local PostgreSQL. It is a miniature of the idea, not a complete suite. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): test groups : unit: price rules | integration: real PostgreSQL | end to end style: a real HTTP request tests : 5 pass : 5 fail : 0 the run above, drawn as a pyramid (one # per test): end-to-end | # integration | # unit | ###

Key points

  • Many unit tests, fewer integration tests, very few end-to-end tests.
  • Lower levels are faster and pinpoint failures.
  • Integration tests use real infrastructure at the boundaries.
  • Keep tests deterministic and isolated.
  • Test behaviour rather than implementation.

Common mistakes

  • An inverted pyramid: mostly slow end-to-end tests.
  • Mocking everything so no test touches real SQL.
  • Tests that depend on the order of other tests.
  • Sleeping instead of waiting for a condition.
  • Chasing a coverage number.

Follow-ups

  • What is the testing trophy?
  • How do you test code that uses the current time?
  • How do you run a real database in CI?

Tips

  • Explain by cost and confidence.
  • Give an example for each layer.
  • Mention flaky tests.
42.backend-0042Mediummid

What are the different kinds of test doubles (dummy, stub, spy, mock, fake), and how do you choose between state-based and interaction-based tests?

Test doubles replace real collaborators in tests. A dummy fills an argument and is never used. A stub returns canned answers. A spy records how it was called so you can check it afterwards. A mock is a spy with expectations that fail the test if they are not met. A fake is a working but simplified implementation (an in-memory repository). Prefer state-based assertions with fakes where possible, because they survive refactoring. Use interaction checks (spies, mocks) for side effects that leave your system, such as sending an email.

Full answer

Kinds

  • Dummy: passed around but never used (a logger the code does not call in this case).
  • Stub: provides indirect input, a fixed answer (a clock that always returns the same time, a rate service that returns 1.5).
  • Spy: a stub that also remembers its calls (arguments, count). You assert on the record.
  • Mock: pre-programmed with expectations about calls, and verifies them. In practice many libraries blur spy and mock.
  • Fake: a lightweight real implementation (in-memory database, local file storage). It has behaviour of its own.

Choosing

  • State-based verification: run the code, then check the result or the state of the fake. It is less tied to how the code works, so refactoring does not break the test.
  • Interaction-based verification: check that a call happened (the email was sent once, with the right address). Use it when the call itself is the result and there is no state to look at.
  • Over-mocking makes tests pass while the real wiring is broken. Do not mock what you do not own (wrap third-party clients in your own interface and test the adapter with an integration test). Do not mock simple value objects.
  • Use real infrastructure in integration tests so that doubles are not the only evidence.
javascript
const assert = require('node:assert');
const { mock } = require('node:test');

// The code under test: registers a user, then sends a welcome email.
async function register({ repo, mailer, clock, logger }, email) {
  if (await repo.findByEmail(email)) return { ok: false, reason: 'duplicate' };
  const user = await repo.save({ email, createdAt: clock() });
  await mailer.send(email, 'Welcome!');
  return { ok: true, user };
}

// Fake: a simple but working in-memory repository.
const fakeRepo = () => { const rows = []; return { rows, findByEmail: async (e) => rows.find((r) => r.email === e), save: async (u) => { rows.push({ id: rows.length + 1, ...u }); return rows.at(-1); } }; };
const stubClock = () => '2026-12-04T00:00:00Z';                       // Stub: a fixed answer
const dummyLogger = null;                                             // Dummy: never used here
const spyMailer = () => ({ send: mock.fn(async () => {}) });          // Spy / mock: records calls

(async () => {
  const deps = { repo: fakeRepo(), mailer: spyMailer(), clock: stubClock, logger: dummyLogger };

  const first = await register(deps, 'asha@example.com');
  assert.strictEqual(first.ok, true);
  assert.deepStrictEqual(deps.repo.rows.map((r) => r.createdAt), ['2026-12-04T00:00:00Z']);        // state-based check (fake + stub)
  console.log('state check : user stored with the stubbed time -> pass');

  assert.strictEqual(deps.mailer.send.mock.callCount(), 1);                                          // interaction check (spy)
  assert.deepStrictEqual(deps.mailer.send.mock.calls[0].arguments, ['asha@example.com', 'Welcome!']);
  console.log('spy check   : one email, correct arguments -> pass');

  const second = await register(deps, 'asha@example.com');
  assert.deepStrictEqual(second, { ok: false, reason: 'duplicate' });
  assert.strictEqual(deps.mailer.send.mock.callCount(), 1);
  console.log('duplicate   : rejected and no second email -> pass');

  // A refactoring that does not change behaviour (save first, then check) still passes the state checks,
  // but a test that asserted "findByEmail was called once" would break. Interaction checks are more fragile.
  const failing = { ...deps, mailer: { send: mock.fn(async () => { throw new Error('smtp down'); }) }, repo: fakeRepo() };
  await assert.rejects(() => register(failing, 'ravi@example.com'), /smtp down/);
  console.log('failure path: a failing mailer surfaces the error ->', failing.repo.rows.length, 'row was already saved (is that what you want?)');
})();

Uses node:assert and the mock helper of node:test, with no test runner needed. The last line shows a design question that the double made visible. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): state check : user stored with the stubbed time -> pass spy check : one email, correct arguments -> pass duplicate : rejected and no second email -> pass failure path: a failing mailer surfaces the error -> 1 row was already saved (is that what you want?)

Key points

  • Stubs give input, spies and mocks check output calls, fakes work in memory.
  • Prefer state-based assertions with fakes.
  • Use interaction checks for side effects that leave the system.
  • Do not over-mock, and do not mock types you do not own.
  • Back doubles with integration tests.

Common mistakes

  • Mocking the database client so no SQL is ever tested.
  • Asserting call order and counts that are not part of the behaviour.
  • Sharing mutable fakes between tests.
  • Mocking value objects and pure functions.
  • Mocking a third-party library directly instead of wrapping it.

Follow-ups

  • What is the difference between a mock and a spy in your favourite library?
  • How do you keep a fake in line with the real implementation?
  • When is a test with real PostgreSQL better than a fake?

Tips

  • Give one sentence per double.
  • State the case for state-based checks.
  • Mention what not to mock.
43.backend-0043Hardsenior

What is consumer-driven contract testing, how does it differ from end-to-end tests, and how does it catch a breaking API change?

In a contract test the consumer of an API records what it actually needs (requests it makes and the fields and types it reads from responses). The provider replays those requests against its real code in its own pipeline and verifies that the responses satisfy the contract. A provider change that removes or retypes a field used by a consumer fails the provider's build before release, without deploying both services together. Contracts cover only what consumers use, so providers stay free to change the rest.

Full answer

How it works

  1. Consumer side: tests run the consumer code against a mock of the provider. The mock records each interaction (request, expected response shape). The result is a contract file.
  2. The contract is shared (a broker such as Pact Broker, or a repository).
  3. Provider side: the provider's pipeline fetches the contracts of all its consumers, starts the provider (with test data for the given states), replays each request and checks the response against the matchers (types and structure, not exact values where unnecessary).
  4. Results are published. A "can I deploy" check blocks a release that would break a deployed consumer.

Compared with other tests

  • End-to-end tests with everything deployed are slow, flaky and give late feedback. Contract tests run in each service's own pipeline.
  • Provider unit and integration tests prove the provider works, but not that it still matches what its consumers expect.
  • Schema checks (OpenAPI diff) find structural breaking changes in the whole API, while consumer contracts find only what matters to real consumers. They complement each other.

Practices: use type matchers, not exact values. Keep contracts small. Version contracts with the consumer. Cover errors and edge cases the consumer handles. Contracts also work for message queues (event payloads).

javascript
// A tiny contract test. A contract lists the requests a consumer makes and the shape it reads.
const contract = {
  consumer: 'mobile-app', provider: 'student-service',
  interactions: [
    { description: 'get a student', request: { method: 'GET', path: '/students/42' }, response: { status: 200, body: { id: 'number', name: 'string', city: 'string' } } },
    { description: 'unknown student', request: { method: 'GET', path: '/students/0' }, response: { status: 404, body: { error: 'string' } } },
  ],
};

function verify(provider, contract) {
  const problems = [];
  for (const { description, request, response } of contract.interactions) {
    const actual = provider(request);
    if (actual.status !== response.status) { problems.push(`${description}: status ${actual.status}, expected ${response.status}`); continue; }
    for (const [field, type] of Object.entries(response.body)) {
      if (!(field in actual.body)) problems.push(`${description}: missing field "${field}"`);
      else if (typeof actual.body[field] !== type) problems.push(`${description}: "${field}" is a ${typeof actual.body[field]}, expected ${type}`);
    }
  }
  return problems;
}

const providerV1 = ({ path }) => path === '/students/42' ? { status: 200, body: { id: 42, name: 'Asha', city: 'Pune', joined: '2026-01-01' } } : { status: 404, body: { error: 'not found' } };
const providerAdditive = (req) => { const r = providerV1(req); return r.status === 200 ? { ...r, body: { ...r.body, badges: ['early'] } } : r; };
const providerRenamed = (req) => { const r = providerV1(req); if (r.status !== 200) return r; const { name, ...rest } = r.body; return { ...r, body: { ...rest, fullName: name } }; };
const providerRetyped = (req) => { const r = providerV1(req); return r.status === 200 ? { ...r, body: { ...r.body, id: String(r.body.id) } } : r; };

for (const [label, provider] of [['current provider', providerV1], ['adds a field', providerAdditive], ['renames name to fullName', providerRenamed], ['id becomes a string', providerRetyped]]) {
  const problems = verify(provider, contract);
  console.log(label.padEnd(26), problems.length ? 'FAILS: ' + problems.join('; ') : 'passes');
}

A simplified consumer contract and a verifier, in plain Node. Tools such as Pact add recording, a broker, provider states and many more matchers. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): current provider passes adds a field passes renames name to fullName FAILS: get a student: missing field "name" id becomes a string FAILS: get a student: "id" is a string, expected number

Key points

  • Consumers state what they need; providers verify it.
  • Failures appear in the provider's pipeline before release.
  • Matchers check structure and types, not exact values.
  • No need to deploy all services together.
  • Complements schema diff checks and integration tests.

Common mistakes

  • Contracts with exact values that break on every data change.
  • Treating contract tests as a replacement for provider tests.
  • Consumers that record everything, not only what they use.
  • No 'can I deploy' check in the pipeline.
  • Letting contracts go stale.

Follow-ups

  • How do provider states work in Pact?
  • How would you contract-test an event on a message queue?
  • How does this relate to OpenAPI diff?

Tips

  • Say 'consumer states needs, provider verifies'.
  • Contrast with e2e tests.
  • Mention type matchers.
44.backend-0044Easyfresher

What are the three pillars of observability (logs, metrics, traces), what is each good for, and how do structured logs and correlation ids tie them together?

Logs are timestamped records of events (good for the details of one occurrence). Metrics are numbers aggregated over time (good for dashboards, alerts and trends). Traces follow one request across services as a tree of timed spans (good for finding where time is spent). Write structured logs (JSON with fields) and include a request or trace id in every log line and span, so you can jump from an alert to the trace to the logs of one request.

Full answer

Pillars

  • Logs: discrete events with context. Use JSON with stable fields (time, level, message, requestId, userId, error). Log at the right level, do not log secrets or full personal data, and sample noisy logs.
  • Metrics: counters (requests, errors), gauges (queue length, memory), histograms (latency). Cheap to store, good for alerting. Keep label cardinality low (route, status class, not user id).
  • Traces: a trace is the path of a request. Each unit of work is a span with start, duration, attributes and a parent span. The trace context (W3C traceparent header) is passed between services so that spans connect.

Linking them

  • Create or accept a correlation id at the edge, put it in async context storage, add it to every log line, propagate it on outgoing calls, and return it in a response header.
  • Exemplars link a slow metric bucket to a concrete trace.

Observability is the ability to ask new questions about a running system from its outputs, without shipping new code. Monitoring is checking known conditions. Start with RED metrics and structured logs, then add tracing. OpenTelemetry is the common standard for all three.

javascript
const { AsyncLocalStorage } = require('node:async_hooks');
const als = new AsyncLocalStorage();

let clock = 0;                                                        // fake clock in milliseconds, advanced by the work below
const logs = [], spans = [], metrics = { requests: 0, errors: 0, durations: [] };

const log = (level, message, extra = {}) => logs.push(JSON.stringify({ t: clock, level, message, requestId: als.getStore()?.requestId, ...extra }));
async function span(name, fn, work) {
  const store = als.getStore(); const span = { name, parent: store.span ?? null, start: clock };
  spans.push(span);
  return als.run({ ...store, span: name }, async () => { clock += work; const r = await fn(); span.end = clock; return r; });
}

async function handleRequest(requestId, path) {
  return als.run({ requestId }, async () => {
    const start = clock;
    metrics.requests++;
    log('info', 'request started', { path });
    await span('GET ' + path, async () => {
      await span('db.query students', async () => { log('debug', 'query ran', { rows: 3 }); }, 12);
      await span('cache.set', async () => {}, 2);
    }, 1);
    metrics.durations.push(clock - start);
    log('info', 'request finished', { status: 200, ms: clock - start });
  });
}

(async () => {
  await handleRequest('req-1', '/students');
  await handleRequest('req-2', '/students');
  console.log('--- logs (JSON, one per line)');
  logs.slice(0, 4).forEach((l) => console.log(l));
  console.log('--- spans of the first request');
  spans.slice(0, 3).forEach((s) => console.log(`${s.parent ? '  ' : ''}${s.name} ${s.end - s.start} ms`));
  console.log('--- metrics:', JSON.stringify({ requests: metrics.requests, errors: metrics.errors, durationsMs: metrics.durations }));
  const ids = new Set(logs.map((l) => JSON.parse(l).requestId));
  console.log('--- every log line has a request id:', logs.every((l) => JSON.parse(l).requestId), '| distinct ids:', [...ids].join(', '));
})();

A fake clock and in-memory arrays stand in for a log pipeline, a metrics backend and a tracer. AsyncLocalStorage carries the request id through async calls without passing it by hand. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): --- logs (JSON, one per line) {"t":0,"level":"info","message":"request started","requestId":"req-1","path":"/students"} {"t":13,"level":"debug","message":"query ran","requestId":"req-1","rows":3} {"t":15,"level":"info","message":"request finished","requestId":"req-1","status":200,"ms":15} {"t":15,"level":"info","message":"request started","requestId":"req-2","path":"/students"} --- spans of the first request GET /students 15 ms db.query students 12 ms cache.set 2 ms --- metrics: {"requests":2,"errors":0,"durationsMs":[15,15]} --- every log line has a request id: true | distinct ids: req-1, req-2

Key points

  • Logs give detail, metrics give trends and alerts, traces give request paths.
  • Use structured JSON logs.
  • Put a correlation id in logs, spans and responses.
  • Keep metric label cardinality low.
  • Do not log secrets.

Common mistakes

  • Unstructured text logs that cannot be searched by field.
  • No correlation id across services.
  • High cardinality labels (user ids) on metrics.
  • Logging secrets or full request bodies.
  • Alerting on logs instead of metrics.

Follow-ups

  • What is OpenTelemetry?
  • What is the W3C traceparent header?
  • How do you decide what to log at which level?

Tips

  • Define each pillar in one line.
  • Describe the correlation id.
  • Start with RED metrics.
45.backend-0045Mediummid

What are the RED and USE methods, and how do counters, gauges and histograms give you request rate, errors, latency percentiles and resource saturation?

RED is for request-driven services: Rate (requests per second), Errors (failed requests per second or ratio) and Duration (latency distribution). USE is for resources such as CPU, memory, disks and pools: Utilization (how busy), Saturation (queued work) and Errors. Counters only go up (rate and errors come from their increase), gauges move both ways (queue length), and histograms count observations in buckets so that you can estimate percentiles (p95, p99) and aggregate them across instances. Averages hide tail latency, so alert on percentiles.

Full answer

RED (for each service or endpoint)

  • Rate: rate(http_requests_total[5m]).
  • Errors: the share of 5xx (and failed business operations) in the total.
  • Duration: a histogram of latency, read as p50, p95 and p99.

USE (for each resource)

  • Utilization: the percentage of time the resource is busy (CPU use, connection pool in use).
  • Saturation: extra work waiting (run queue, pending pool requests, event loop delay).
  • Errors: error counts of the resource (disk errors, dropped packets, connection errors).

Metric types

  • Counter: monotonic total. Rates are computed from differences, and resets are handled by the query layer.
  • Gauge: current value (in-flight requests, memory).
  • Histogram: bucket counters (le="0.1") plus sum and count. Percentiles are estimated by interpolating inside the bucket that contains the rank. Buckets must fit your latency range. Summaries compute percentiles in the client but cannot be aggregated across instances.

Cautions: keep labels low cardinality (route template, method, status class). Do not average percentiles of different instances. Use histograms with the same buckets everywhere.

javascript
// A tiny histogram with Prometheus style cumulative buckets.
const buckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 2.5];
const hist = { counts: new Array(buckets.length + 1).fill(0), sum: 0, count: 0 };
const observe = (seconds) => { hist.sum += seconds; hist.count++; hist.counts[buckets.findIndex((b) => seconds <= b) === -1 ? buckets.length : buckets.findIndex((b) => seconds <= b)]++; };

// Deterministic fake traffic: mostly fast, a slow tail, some errors.
let seed = 42; const rand = () => (seed = (seed * 1664525 + 1013904223) % 4294967296) / 4294967296;
const samples = Array.from({ length: 2000 }, () => ({ seconds: rand() < 0.95 ? 0.01 + rand() * 0.04 : 0.4 + rand() * 1.2, status: rand() < 0.02 ? 500 : 200 }));
let requests = 0, errors = 0;
for (const s of samples) { requests++; if (s.status >= 500) errors++; observe(s.seconds); }

// Percentile estimate from the buckets (linear interpolation inside the bucket).
function quantile(q) {
  const rank = q * hist.count; let cumulative = 0;
  for (let i = 0; i < buckets.length; i++) {
    const next = cumulative + hist.counts[i];
    if (next >= rank) { const lower = i === 0 ? 0 : buckets[i - 1]; return lower + ((rank - cumulative) / hist.counts[i]) * (buckets[i] - lower); }
    cumulative = next;
  }
  return Infinity;
}
const exact = (q) => samples.map((s) => s.seconds).sort((a, b) => a - b)[Math.floor(q * (samples.length - 1))];

console.log('RED  rate      :', requests, 'requests in the window');
console.log('RED  errors    :', (errors / requests * 100).toFixed(1) + '% of requests failed');
console.log('RED  duration  : mean', (hist.sum / hist.count * 1000).toFixed(0), 'ms | p50', (quantile(0.5) * 1000).toFixed(0), 'ms | p95', (quantile(0.95) * 1000).toFixed(0), 'ms | p99', (quantile(0.99) * 1000).toFixed(0), 'ms');
console.log('exact p99      :', (exact(0.99) * 1000).toFixed(0), 'ms (the bucket estimate is close, and the mean hides the tail)');

console.log('\n# exposition format (cumulative buckets)');
let cumulative = 0;
buckets.forEach((b, i) => { cumulative += hist.counts[i]; console.log(`http_request_duration_seconds_bucket{le="${b}"} ${cumulative}`); });
console.log(`http_request_duration_seconds_bucket{le="+Inf"} ${hist.count}`);
console.log(`http_requests_total{status_class="5xx"} ${errors}`);

// USE for one resource: a connection pool.
const pool = { size: 10, inUse: 9, waiting: 4, errors: 0 };
console.log('\nUSE pool       : utilization', pool.inUse / pool.size * 100 + '%', '| saturation', pool.waiting, 'waiting | errors', pool.errors);

Synthetic traffic from a fixed random seed, so the numbers repeat. The percentile estimate uses the same interpolation idea as Prometheus histogram_quantile. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): RED rate : 2000 requests in the window RED errors : 1.8% of requests failed RED duration : mean 84 ms | p50 32 ms | p95 529 ms | p99 1386 ms exact p99 : 1337 ms (the bucket estimate is close, and the mean hides the tail) # exposition format (cumulative buckets) http_request_duration_seconds_bucket{le="0.005"} 0 http_request_duration_seconds_bucket{le="0.01"} 0 http_request_duration_seconds_bucket{le="0.025"} 660 http_request_duration_seconds_bucket{le="0.05"} 1888 http_request_duration_seconds_bucket{le="0.1"} 1888 http_request_duration_seconds_bucket{le="0.25"} 1888 http_request_duration_seconds_bucket{le="0.5"} 1897 http_request_duration_seconds_bucket{le="0.75"} 1923 http_request_duration_seconds_bucket{le="1"} 1941 http_request_duration_seconds_bucket{le="1.25"} 1968 http_request_duration_seconds_bucket{le="1.5"} 1990 http_request_duration_seconds_bucket{le="2"} 2000 http_request_duration_seconds_bucket{le="2.5"} 2000 http_request_duration_seconds_bucket{le="+Inf"} 2000 http_requests_total{status_class="5xx"} 36 USE pool : utilization 90% | saturation 4 waiting | errors 0

Key points

  • RED: rate, errors, duration for services.
  • USE: utilization, saturation, errors for resources.
  • Counters go up, gauges go both ways, histograms bucket observations.
  • Estimate percentiles from histogram buckets.
  • Averages hide slow requests.

Common mistakes

  • Alerting on average latency.
  • Averaging percentiles from several instances.
  • Labels such as user id or full URL path on metrics.
  • Histogram buckets that do not cover the real latency range.
  • Monitoring only the service and not its resources.

Follow-ups

  • How does histogram_quantile work?
  • What is the difference between a histogram and a summary?
  • Which saturation signals matter for a Node.js service?

Tips

  • Define RED and USE in one line each.
  • Name the three metric types.
  • Say why percentiles beat averages.
46.backend-0046Hardsenior

What are SLIs, SLOs and error budgets, and how do burn-rate alerts work?

An SLI (service level indicator) is a measured ratio of good events to all events, such as the share of requests that succeed in under 300 ms. An SLO is the target for it over a window (99.9 percent over 30 days). The error budget is the allowed failure, 0.1 percent, which is about 43 minutes of full outage per 30 days. Burn rate says how fast you spend the budget compared with the steady rate that would use it exactly over the window. Alerts fire on high burn rates over short and long windows together, so you are paged quickly for big problems and not for noise.

Full answer

Definitions

  • SLI: good events / valid events, measured at a meaningful point (at the load balancer or from the user's side). Typical SLIs: availability, latency below a threshold, freshness, correctness.
  • SLO: the goal for the SLI over a rolling window. Choose with the business, as 100 percent is not a sensible target.
  • SLA: a contract with consequences. SLOs are internal and stricter than SLAs.
  • Error budget: 1 - SLO. It is the amount of unreliability you can spend on releases, experiments and failures. When the budget is used up, the team shifts effort to reliability.

Burn rate

  • burn rate = observed error ratio / allowed error ratio. A burn rate of 1 uses the whole budget exactly at the end of the window. A burn rate of 14.4 uses 2 percent of a 30-day budget in one hour.
  • Alert with multiple windows: page when the burn rate is above 14.4 over both 1 hour and 5 minutes (a big, current problem). Page for 6 over 6 hours and 30 minutes. Ticket for 1 over 3 days. The short window makes the alert reset quickly once the problem is fixed.

Benefits: alerts are tied to user impact, not to causes such as CPU. Releases can be judged against the remaining budget.

javascript
const SLO = 0.999, WINDOW_DAYS = 30;
const allowedErrorRatio = 1 - SLO;
const budgetMinutes = WINDOW_DAYS * 24 * 60 * allowedErrorRatio;
console.log('SLO', SLO * 100 + '%', 'over', WINDOW_DAYS, 'days -> error budget =', budgetMinutes.toFixed(1), 'minutes of full outage');

const burnRate = (errors, total) => errors / total / allowedErrorRatio;
const hoursToExhaust = (rate) => (WINDOW_DAYS * 24) / rate;

// Request counts for a recent time window: [errors, total]
const scenarios = {
  'normal day (0.05% errors)': { '1h': [180, 360000], '5m': [15, 30000] },
  'slow leak (0.3% errors)': { '1h': [1080, 360000], '5m': [90, 30000] },
  'bad deploy (5% errors)': { '1h': [18000, 360000], '5m': [1500, 30000] },
  'bad deploy, already fixed': { '1h': [18000, 360000], '5m': [0, 30000] },
};

for (const [name, w] of Object.entries(scenarios)) {
  const long = burnRate(...w['1h']), short = burnRate(...w['5m']);
  const page = long > 14.4 && short > 14.4;
  console.log(name.padEnd(28), 'burn 1h =', long.toFixed(1).padStart(5), '| burn 5m =', short.toFixed(1).padStart(5), '| page:', page, '| budget gone in', Math.round(hoursToExhaust(Math.max(long, 0.0001))), 'h at the 1h rate');
}
console.log('fraction of budget used by one hour at burn rate 14.4:', (14.4 * 1 / (WINDOW_DAYS * 24) * 100).toFixed(1) + '%');

The calculations use fixed request counts. The numbers 14.4 and 6 follow the widely used multi-window burn-rate recipe from the Google SRE workbook. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): SLO 99.9% over 30 days -> error budget = 43.2 minutes of full outage normal day (0.05% errors) burn 1h = 0.5 | burn 5m = 0.5 | page: false | budget gone in 1440 h at the 1h rate slow leak (0.3% errors) burn 1h = 3.0 | burn 5m = 3.0 | page: false | budget gone in 240 h at the 1h rate bad deploy (5% errors) burn 1h = 50.0 | burn 5m = 50.0 | page: true | budget gone in 14 h at the 1h rate bad deploy, already fixed burn 1h = 50.0 | burn 5m = 0.0 | page: false | budget gone in 14 h at the 1h rate fraction of budget used by one hour at burn rate 14.4: 2.0%

Key points

  • SLI measures, SLO targets, SLA is a contract.
  • Error budget is 1 minus the SLO.
  • Burn rate compares the current error ratio with the allowed one.
  • Use long and short windows together in alerts.
  • Alert on user-visible symptoms.

Common mistakes

  • A 100 percent target.
  • Measuring SLIs at the server only, missing what users see.
  • Alerting on every CPU spike instead of budget burn.
  • Too many SLOs per service.
  • Not using the budget to decide on releases.

Follow-ups

  • How do you pick an SLO for a new service?
  • Why use two windows in one alert?
  • What is the difference between SLA and SLO?

Tips

  • Give the budget in minutes.
  • Explain burn rate with one number.
  • Mention multi-window alerts.
47.backend-0047Easyfresher

What is the OWASP Top 10, which risks does the 2025 edition list, and how would you address the most important ones in a backend service?

The OWASP Top 10 is a regularly updated awareness list of the most critical web application security risks. The 2025 edition lists: A01 Broken Access Control (which now includes SSRF), A02 Security Misconfiguration, A03 Software Supply Chain Failures, A04 Cryptographic Failures, A05 Injection, A06 Insecure Design, A07 Authentication Failures, A08 Software or Data Integrity Failures, A09 Security Logging and Alerting Failures, and A10 Mishandling of Exceptional Conditions. In a backend, deny by default, validate and parameterise, keep dependencies and configuration under control, and log security events.

Full answer

What to do for each risk (backend view)

  • A01 Broken Access Control: check authorisation on the server for every request and object (no IDOR), deny by default, test roles, and validate outgoing request targets (SSRF).
  • A02 Security Misconfiguration: secure defaults, no debug modes or default accounts in production, minimal permissions, security headers, the same hardened config in every environment, automated config checks.
  • A03 Software Supply Chain Failures: lockfiles, pinned versions, dependency and image scanning, signed artifacts, review of build pipelines and who can publish.
  • A04 Cryptographic Failures: TLS everywhere, strong algorithms, correct password hashing, key management, no sensitive data in logs or URLs.
  • A05 Injection: parameterised queries, safe APIs for commands, output encoding, input validation with allowlists.
  • A06 Insecure Design: threat modelling, abuse cases, rate limits and business logic checks in the design phase.
  • A07 Authentication Failures: strong password policy and hashing, MFA, brute force protection, safe session and token handling.
  • A08 Software or Data Integrity Failures: verify updates and serialised data, no unsafe deserialisation, protected CI/CD.
  • A09 Logging and Alerting Failures: log security events (login failures, access denials), protect logs, alert on them, and test the alerts.
  • A10 Mishandling of Exceptional Conditions: fail closed, handle every error path, no sensitive details in error messages, and keep transactions consistent when something fails.

The list is a starting point, not a standard checklist. Combine it with ASVS and threat modelling. Check the current edition, because it changes every few years.

javascript
// A tiny configuration audit that maps findings to the OWASP Top 10:2025 categories.
function audit(config) {
  const findings = [];
  const add = (category, text) => findings.push(`${category}: ${text}`);
  if (config.debug) add('A02 Security Misconfiguration', 'debug mode is on');
  if (config.adminPassword === 'admin') add('A02 Security Misconfiguration', 'default admin password');
  if (!config.tls) add('A04 Cryptographic Failures', 'TLS is off');
  if (config.passwordHash === 'sha256') add('A04 Cryptographic Failures', 'fast hash used for passwords');
  if (!config.lockfile) add('A03 Software Supply Chain Failures', 'no lockfile committed');
  if (config.cors === '*' && config.cookies) add('A02 Security Misconfiguration', 'wildcard CORS together with cookie authentication');
  if (!config.logFailedLogins) add('A09 Security Logging and Alerting Failures', 'failed logins are not logged');
  if (config.errorDetails) add('A10 Mishandling of Exceptional Conditions', 'stack traces are returned to clients');
  if (config.outboundFetchAllowlist === false) add('A01 Broken Access Control', 'server fetches user-supplied URLs with no allowlist (SSRF)');
  return findings;
}

const risky = { debug: true, adminPassword: 'admin', tls: false, passwordHash: 'sha256', lockfile: false, cors: '*', cookies: true, logFailedLogins: false, errorDetails: true, outboundFetchAllowlist: false };
const hardened = { debug: false, adminPassword: 'rotated-secret', tls: true, passwordHash: 'argon2id', lockfile: true, cors: 'https://app.example.com', cookies: true, logFailedLogins: true, errorDetails: false, outboundFetchAllowlist: true };

console.log('risky configuration:');
audit(risky).forEach((f) => console.log(' -', f));
console.log('hardened configuration:', audit(hardened).length, 'findings');

A toy audit function that maps config mistakes to the categories of the 2025 list (checked against owasp.org on 2026-12-04). It is an illustration, not a scanner. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): risky configuration: - A02 Security Misconfiguration: debug mode is on - A02 Security Misconfiguration: default admin password - A04 Cryptographic Failures: TLS is off - A04 Cryptographic Failures: fast hash used for passwords - A03 Software Supply Chain Failures: no lockfile committed - A02 Security Misconfiguration: wildcard CORS together with cookie authentication - A09 Security Logging and Alerting Failures: failed logins are not logged - A10 Mishandling of Exceptional Conditions: stack traces are returned to clients - A01 Broken Access Control: server fetches user-supplied URLs with no allowlist (SSRF) hardened configuration: 0 findings

Key points

  • The OWASP Top 10 is an awareness list of the main web risks.
  • Broken access control is first, and SSRF now sits inside it.
  • Injection, misconfiguration and supply chain failures need constant care.
  • Fail closed and log security events.
  • Use it with ASVS and threat modelling.

Common mistakes

  • Treating the list as a complete security program.
  • Relying on the front end for access control.
  • Using an outdated edition of the list in documents.
  • Fixing symptoms (blocking one payload) instead of root causes.
  • Only testing the happy path of authorisation.

Follow-ups

  • How does OWASP ASVS differ from the Top 10?
  • What is threat modelling?
  • Why was SSRF folded into Broken Access Control?

Tips

  • Name the top three and one control each.
  • Say 'deny by default'.
  • Mention that the list changes.
48.backend-0048Mediummid

How does SQL injection work, why do parameterized queries prevent it, and what do you do about parts of a query that cannot be parameters, such as column names?

SQL injection happens when user input is concatenated into the SQL text, so the input can change the structure of the query (OR '1'='1', or a second statement). With parameterized queries the SQL text and the values travel separately, so the database always treats the values as data. Values must always be parameters. Identifiers (column or table names), sort directions and similar parts cannot be parameters, so choose them from an allowlist in code, or quote them with a library function. Least-privilege database users limit the damage.

Full answer

The attack

  • Code: "SELECT * FROM users WHERE name = '" + name + "'". Input ' OR '1'='1 turns the condition into always true. Input x'; DROP TABLE users; -- ends the first statement and runs another one.

The defence

  1. Parameterized (prepared) queries: db.query('SELECT * FROM users WHERE name = $1', [name]). The driver sends the parameters separately from the SQL, and PostgreSQL never parses them as SQL. This also works for LIKE patterns (pass the pattern as the value), IN lists (= ANY($1)) and numbers.
  2. Allowlist for structure: ORDER BY column and direction, table names and operators come from a fixed map in code. If you must use an identifier from input, escape it with the driver's identifier function (pg: escapeIdentifier) after checking it against known names.
  3. Validate input type and length, as defence in depth (not the main defence).
  4. Least privilege: the application's database user should not own tables or run DDL, and should use only the permissions it needs.
  5. ORMs and query builders help, but raw fragments (sequelize.literal, knex.raw) can reintroduce the problem.
  6. Do not hide errors in logs, but never return database errors to users. Test with automated scanners and code review.

Second-order injection: data that was stored safely and later concatenated into a query. Parameterise there too.

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

(async () => {
  const db = new Client(); await db.connect();
  await db.query(`DROP TABLE IF EXISTS bk48_users; DROP TABLE IF EXISTS bk48_victim;
    CREATE TABLE bk48_users (id serial PRIMARY KEY, name text, secret text);
    INSERT INTO bk48_users (name, secret) VALUES ('asha', 'a-secret'), ('ravi', 'r-secret');
    CREATE TABLE bk48_victim (id int)`);
  const exists = async () => (await db.query("SELECT to_regclass('bk48_victim') IS NOT NULL AS e")).rows[0].e;

  const vulnerable = (name) => db.query(`SELECT name FROM bk48_users WHERE name = '${name}'`);          // string concatenation: do not do this
  const safe = (name) => db.query('SELECT name FROM bk48_users WHERE name = $1', [name]);

  const attack1 = "x' OR '1'='1";
  console.log('input                 :', attack1);
  console.log('concatenated returns  :', (await vulnerable(attack1)).rows.map((r) => r.name).join(', '), '(every user)');
  console.log('parameterized returns :', (await safe(attack1)).rows.length, 'rows');

  const attack2 = "x'; DROP TABLE bk48_victim; --";
  await vulnerable(attack2);
  console.log('victim table after the concatenated query:', (await exists()) ? 'still exists' : 'DROPPED');
  await db.query('CREATE TABLE IF NOT EXISTS bk48_victim (id int)');
  await safe(attack2);
  console.log('victim table after the parameterized one :', (await exists()) ? 'still exists' : 'DROPPED');

  // Identifiers cannot be parameters. Use an allowlist.
  const sortable = { name: 'name', id: 'id' };
  const listUsers = async (sortKey, direction) => {
    const column = sortable[sortKey];
    if (!column) throw new Error('invalid sort column');
    const dir = direction === 'desc' ? 'DESC' : 'ASC';
    return db.query(`SELECT name FROM bk48_users ORDER BY ${column} ${dir}`);
  };
  console.log('allowlisted sort      :', (await listUsers('name', 'desc')).rows.map((r) => r.name).join(', '));
  console.log('malicious sort column :', await listUsers('name; DROP TABLE x', 'asc').catch((e) => e.message));
  console.log('quoted identifier     :', db.escapeIdentifier('name"; DROP TABLE x; --'));

  await db.query('DROP TABLE bk48_users; DROP TABLE IF EXISTS bk48_victim');
  await db.end();
})();

Runs against the local PostgreSQL and attacks its own demo tables only. The concatenated query is shown to explain the bug, and it must never be used in real code. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): input : x' OR '1'='1 concatenated returns : asha, ravi (every user) parameterized returns : 0 rows victim table after the concatenated query: DROPPED victim table after the parameterized one : still exists allowlisted sort : ravi, asha malicious sort column : invalid sort column quoted identifier : "name""; DROP TABLE x; --"

Key points

  • Injection changes the structure of a query through concatenated input.
  • Parameterized queries send values separately from the SQL text.
  • Identifiers and keywords need an allowlist or proper quoting.
  • Use least-privilege database accounts.
  • Raw fragments in ORMs are still dangerous.

Common mistakes

  • Escaping quotes by hand.
  • Parameterising values but concatenating the ORDER BY from input.
  • Using raw query fragments in ORM code.
  • A database user with owner or superuser rights.
  • Showing database error messages to users.

Follow-ups

  • How do prepared statements differ from parameterized queries?
  • How do you pass an array to IN safely?
  • What is second-order SQL injection?

Tips

  • Show the vulnerable and the safe version.
  • Mention identifiers and allowlists.
  • Add least privilege.
49.backend-0049Hardsenior

What is Server-Side Request Forgery (SSRF), why is it dangerous in cloud environments, and how do you defend a feature that fetches user-supplied URLs?

SSRF makes your server send requests to a destination the attacker chooses, such as internal services, localhost admin ports or the cloud metadata address (169.254.169.254) that returns credentials. Defend in layers: avoid fetching user URLs when possible, use an allowlist of hosts, allow only http and https, resolve DNS yourself and reject private, loopback and link-local addresses (including IPv6 and encoded forms), connect to the validated IP (to stop DNS rebinding), do not follow redirects blindly, limit response size and time, and use network egress rules and metadata protections (IMDSv2) as the last line.

Full answer

Why it works

  • The server sits inside a trusted network. A "fetch this URL" feature (webhooks, image import, link previews, PDF generators) lets the user aim the server at internal addresses. In cloud environments the metadata endpoint can hand out credentials.

Bypass tricks to expect

  • Alternate IP spellings: http://2130706433/ (decimal), http://0x7f.1/, http://127.1/, IPv6 ::1, IPv4-mapped ::ffff:127.0.0.1.
  • A public name that resolves to a private IP, or a name that resolves to a public IP first and a private one later (DNS rebinding).
  • Redirects from an allowed URL to an internal one. Different parsers (validation and request libraries) reading the same URL differently.

Defences (use several)

  1. Prefer an allowlist of hosts or domains. If users must supply arbitrary URLs, use a blocklist of address ranges as a second step.
  2. Parse the URL with the standard URL class. Allow http and https only, and disallow credentials in the URL and unusual ports.
  3. Resolve the hostname, check every resolved address against blocked ranges (10/8, 172.16/12, 192.168/16, 127/8, 169.254/16, 0/8, ::1, fc00::/7, fe80::/10, and mapped IPv4), then connect to that checked IP (pin it) with the original Host header, so a second resolution cannot change the target.
  4. Re-validate on each redirect, or disable redirects.
  5. Set timeouts and a response size limit, and do not return raw responses to users.
  6. Egress firewall rules, a separate network zone or proxy for outgoing fetches, and metadata service hardening (IMDSv2 needs a header and a hop limit).
javascript
const net = require('node:net');

const blocked = new net.BlockList();
for (const [addr, bits] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.168.0.0', 16]]) blocked.addSubnet(addr, bits, 'ipv4');
blocked.addAddress('::1', 'ipv6'); blocked.addSubnet('fc00::', 7, 'ipv6'); blocked.addSubnet('fe80::', 10, 'ipv6');

function isBlockedIp(ip) {
  const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip);
  if (mapped) return blocked.check(mapped[1], 'ipv4');
  const hexMapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(ip);                 // the URL class writes mapped addresses in hex
  if (hexMapped) { const n = (parseInt(hexMapped[1], 16) << 16) | parseInt(hexMapped[2], 16); return blocked.check([n >>> 24, (n >> 16) & 255, (n >> 8) & 255, n & 255].join('.'), 'ipv4'); }
  return blocked.check(ip, net.isIPv6(ip) ? 'ipv6' : 'ipv4');
}

// resolve is injectable so the demo needs no network. A real version would use dns.promises.lookup(host, { all: true }).
async function checkUrl(input, resolve) {
  let url; try { url = new URL(input); } catch { return 'rejected: not a URL'; }
  if (!['http:', 'https:'].includes(url.protocol)) return 'rejected: scheme ' + url.protocol;
  if (url.username || url.password) return 'rejected: credentials in URL';
  const host = url.hostname.replace(/^\[|\]$/g, '');
  const addresses = net.isIP(host) ? [host] : await resolve(host);
  for (const ip of addresses) if (isBlockedIp(ip)) return `rejected: ${host} -> ${ip} is internal`;
  return `allowed: connect to ${addresses[0]} (pinned)`;
}

const fakeDns = { 'cdn.example.com': ['93.184.216.34'], 'localhost': ['127.0.0.1'], 'internal.corp.example': ['10.1.2.3'], 'sneaky.example.com': ['93.184.216.34', '169.254.169.254'] };
const resolve = async (host) => fakeDns[host] ?? [];

(async () => {
  for (const u of ['https://cdn.example.com/logo.png', 'http://localhost:8080/admin', 'http://169.254.169.254/latest/meta-data/', 'http://2130706433/', 'http://0x7f.1/',
    'http://[::1]/', 'http://[::ffff:127.0.0.1]/', 'http://internal.corp.example/', 'http://sneaky.example.com/', 'file:///etc/passwd', 'http://user:pw@cdn.example.com/', 'http://192.168.1.10:9200/'])
    console.log(u.padEnd(46), await checkUrl(u, resolve));

  // DNS rebinding: a second lookup returns a different answer than the one that was checked.
  let calls = 0;
  const rebinding = async () => (++calls === 1 ? ['93.184.216.34'] : ['127.0.0.1']);
  console.log('\nrebinding host, validated lookup :', await checkUrl('http://rebind.example.com/', rebinding));
  console.log('a second lookup at connect time  :', (await rebinding())[0], '(so connect to the validated IP, do not resolve again)');
})();

Address checks use Node's net.BlockList, and DNS is replaced by a fake table so no network is needed. A real fetch adds the pinned connection, redirects, timeouts and a size limit. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): https://cdn.example.com/logo.png allowed: connect to 93.184.216.34 (pinned) http://localhost:8080/admin rejected: localhost -> 127.0.0.1 is internal http://169.254.169.254/latest/meta-data/ rejected: 169.254.169.254 -> 169.254.169.254 is internal http://2130706433/ rejected: 127.0.0.1 -> 127.0.0.1 is internal http://0x7f.1/ rejected: 127.0.0.1 -> 127.0.0.1 is internal http://[::1]/ rejected: ::1 -> ::1 is internal http://[::ffff:127.0.0.1]/ rejected: ::ffff:7f00:1 -> ::ffff:7f00:1 is internal http://internal.corp.example/ rejected: internal.corp.example -> 10.1.2.3 is internal http://sneaky.example.com/ rejected: sneaky.example.com -> 169.254.169.254 is internal file:///etc/passwd rejected: scheme file: http://user:pw@cdn.example.com/ rejected: credentials in URL http://192.168.1.10:9200/ rejected: 192.168.1.10 -> 192.168.1.10 is internal rebinding host, validated lookup : allowed: connect to 93.184.216.34 (pinned) a second lookup at connect time : 127.0.0.1 (so connect to the validated IP, do not resolve again)

Key points

  • SSRF aims your server at internal or metadata addresses.
  • Check every resolved IP, including IPv6 and mapped forms.
  • Connect to the checked IP to prevent DNS rebinding.
  • Handle redirects, timeouts and size limits.
  • Add network-level controls as well.

Common mistakes

  • Blocklisting a few strings such as 'localhost'.
  • Checking the hostname but not the resolved IP.
  • Resolving the name twice (check, then connect).
  • Following redirects to internal addresses.
  • Returning fetched content or errors that reveal internal details.

Follow-ups

  • How does IMDSv2 reduce the SSRF risk?
  • How would you build a safe link preview service?
  • Why is an allowlist better than a blocklist?

Tips

  • Start with a cloud metadata example.
  • List the bypass tricks.
  • Say 'check the IP and connect to that IP'.
50.backend-0050Easyfresher

How should a backend service manage secrets (API keys, database passwords, signing keys): where to store them, how to keep them out of code and logs, and how to rotate them?

Keep secrets out of source code and images. Inject them at runtime from environment variables or, better, a secrets manager (a cloud secret store, Vault, Kubernetes secrets with encryption) with access control and audit logs. Give each environment and service its own secrets with the least privilege, never log them (redact), scan repositories for leaks, and rotate regularly and immediately after exposure. Design for rotation by allowing two valid secrets during the change.

Full answer

Storage and delivery

  • Never commit secrets, including in .env files, test fixtures, Docker layers, and CI logs. Use .gitignore and pre-commit and CI secret scanning.
  • Load from the environment or from a secrets manager at start-up (or on demand with caching). The manager gives encryption at rest, fine-grained access, audit trails and versioning. Prefer short-lived credentials (workload identity, database IAM auth) over long-lived passwords.
  • Separate secrets per environment and per service. Production secrets should not be readable from developer laptops or staging.

Handling

  • Validate that required secrets exist on start-up and fail fast with a message that does not print the value.
  • Do not log secrets or whole config objects and request headers. Redact known keys (authorization, password, token, cookie) in logs, errors and traces.
  • Do not pass secrets in URLs or command-line arguments (they appear in process lists and logs).

Rotation

  • Rotate on a schedule and on any suspicion of exposure. Support two active secrets at once (old and new) so that clients and servers can switch without downtime, then retire the old one. Automate it.
  • If a secret leaks to a repository, revoking it is the fix. Removing it from the git history is not enough.
javascript
// 1. Load required secrets at start-up and fail fast without printing values.
function loadConfig(env) {
  const required = ['DATABASE_URL', 'JWT_SIGNING_KEY'];
  const missing = required.filter((name) => !env[name]);
  if (missing.length) throw new Error('missing required secrets: ' + missing.join(', '));
  return { databaseUrl: env.DATABASE_URL, jwtKey: env.JWT_SIGNING_KEY };
}
try { loadConfig({ DATABASE_URL: 'postgres://app:pw@db/app' }); } catch (err) { console.log('1. start-up check      :', err.message); }

// 2. Redact sensitive fields before logging.
const SENSITIVE = /^(authorization|password|token|secret|cookie|api[-_]?key)$/i;
const redact = (value) => Array.isArray(value) ? value.map(redact)
  : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SENSITIVE.test(k) ? '[redacted]' : redact(v)])) : value;
console.log('2. redacted log object :', JSON.stringify(redact({ user: 'asha', headers: { authorization: 'Bearer abc', 'content-type': 'json' }, body: { password: 'hunter2', note: 'hi' } })));

// 3. A simple scanner for secrets that were committed by mistake (patterns for well known example keys).
const patterns = { 'AWS access key id': /\bAKIA[0-9A-Z]{16}\b/, 'private key block': /-----BEGIN (RSA |EC )?PRIVATE KEY-----/, 'password in URL': /:\/\/[^\s:@]+:[^\s@]+@/ };
const sampleFile = 'const key = "AKIAIOSFODNN7EXAMPLE";\nconst url = "postgres://app:s3cret@db.internal/app";\nconst ok = process.env.API_KEY;';
sampleFile.split('\n').forEach((line, i) => { for (const [name, re] of Object.entries(patterns)) if (re.test(line)) console.log(`3. scanner, line ${i + 1}      : ${name}`); });

// 4. Rotation: accept the new and the previous secret during the change.
const crypto = require('node:crypto');
const sign = (secret, data) => crypto.createHmac('sha256', secret).update(data).digest('hex');
const accepted = ['new-secret', 'old-secret'];
const verify = (data, signature) => accepted.some((s) => crypto.timingSafeEqual(Buffer.from(sign(s, data)), Buffer.from(signature)));
const oldSig = sign('old-secret', 'payload'), newSig = sign('new-secret', 'payload');
console.log('4. during rotation     : old signature valid =', verify('payload', oldSig), '| new signature valid =', verify('payload', newSig));
accepted.pop();
console.log('   after retiring old  : old signature valid =', verify('payload', oldSig), '| new signature valid =', verify('payload', newSig));

The example key in the scanner is the well-known fake value from AWS documentation. Each numbered line shows one practice in plain Node. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. start-up check : missing required secrets: JWT_SIGNING_KEY 2. redacted log object : {"user":"asha","headers":{"authorization":"[redacted]","content-type":"json"},"body":{"password":"[redacted]","note":"hi"}} 3. scanner, line 1 : AWS access key id 3. scanner, line 2 : password in URL 4. during rotation : old signature valid = true | new signature valid = true after retiring old : old signature valid = false | new signature valid = true

Key points

  • Do not keep secrets in code, images or logs.
  • Use a secrets manager and least-privilege access.
  • Prefer short-lived credentials.
  • Redact sensitive fields and fail fast on missing config.
  • Rotate regularly with two active secrets during the change.

Common mistakes

  • Committing a .env file or a key to a repository.
  • Logging request headers or the whole config object.
  • One shared secret for every environment.
  • Rotating only after an incident, with no automated process.
  • Putting secrets in build arguments and image layers.

Follow-ups

  • How do you handle a secret that was committed by mistake?
  • What is workload identity and why is it better than a stored key?
  • How does Vault issue dynamic database credentials?

Tips

  • Say 'not in code, not in logs, rotated'.
  • Mention a secrets manager.
  • Describe dual-secret rotation.