← Back to Backend, page 3

backend-0044 · Easy fresher

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.