Observability across layers

Advanced · 38 min

Follow one Taskboard request from the browser through the API to the database using a request id, structured logs, and traces, and know what to alert on.

Before thisZero-downtime deploys and schema changesError handling across the stackThe life of a request, end to end

Better Stack · 38 min

Observability across layers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Better StackReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Observability means you can answer a question you did not plan for, such as why one user's request failed, from the data the app already emits.
  • A request id created at the edge and attached to every log line lets you follow one request across the client, the API and the database.
  • Logs say what happened, metrics say how often and how slow, and traces say where the time went inside one request.
  • Log as JSON with a stable set of fields, because a search over structured fields works and a search over free text does not.
  • Alert on symptoms users feel, such as error rate and latency, not on every internal cause, or you will train yourself to ignore alerts.

The problem: a user says “it broke”

A Taskboard user writes: “I tried to add a task at about two o’clock and got an error.” You have an API on one host, a database on another, a client in their browser, and probably a log search that returns four thousand lines for “error”. Where do you start?

Observability is whether you can answer that question from what the system already records. You cannot add logging after the incident. The work is done beforehand, and it comes down to three kinds of signal and one habit that connects them.

Three signals

  • Logs are events: “created task 812 for project 3”, “insert failed: foreign key violation”. Good for what happened to one request.
  • Metrics are numbers over time: requests per minute, error rate, the 95th percentile of latency. Good for “is something wrong right now” and for trends.
  • Traces are the timed steps inside one request: the route took 240 ms, of which 210 ms was one query. Good for where the time went.

Each answers a different question. Metrics tell you something is slow, a trace shows which step, a log tells you the details of one failing case. For how to emit each from application code, see structured logging and correlation ids and metrics and instrumentation. This lesson is about carrying them across layers.

The habit: one id for one request

The seam problem: the browser, the API and the database each know a piece of the story, and nothing links the pieces. A request id is the link. The API creates one (or accepts one from the caller), puts it on every log line for that request, and returns it in a response header.

Here is a Hono middleware setup I ran for Taskboard, with the id stored in Node’s AsyncLocalStorage so any code in the request can log it without passing it around:

const als = new AsyncLocalStorage<{ id: string }>();
const log = (msg: string, extra = {}) =>
  console.log(JSON.stringify({ level: "info", reqId: als.getStore()?.id, msg, ...extra }));

app.use(requestId());
app.use(secureHeaders());
app.use(async (c, next) => {
  const t = performance.now();
  await als.run({ id: c.get("requestId") }, async () => {
    await next();
    log("request", { method: c.req.method, path: c.req.path,
      status: c.res.status, ms: Math.round(performance.now() - t) });
  });
});

Calling GET /api/x, whose handler logs “loading tasks” and sleeps 20 ms, printed:

{"level":"info","reqId":"35f77f5c-...","msg":"loading tasks"}
{"level":"info","reqId":"35f77f5c-...","msg":"request","method":"GET","path":"/api/x","status":200,"ms":23}

and the response carried x-request-id: 35f77f5c-.... I ran this on Hono 4.13.20 and Node 26. The two lines share a reqId without the handler ever receiving it as an argument. That is what AsyncLocalStorage is for, covered in AsyncLocalStorage and context propagation. From Hono’s documentation, the requestId middleware also reuses an incoming X-Request-Id header, so a gateway in front of you can set it first. I did not test that part.

Now the incident is searchable. If the client shows the id on the error screen (Something went wrong. Reference: 35f77f5c), the user sends it to you, and one search finds every line for that request. The answer to “where do I start” becomes a copy and a paste.

Log JSON, not sentences. A line like {"msg":"request","status":500,"path":"/api/projects/3/tasks","ms":812} can be filtered by status, grouped by path and graphed by latency. The sentence “Failed to create task for project 3!” can only be searched as text. Pick a small stable set of fields (reqId, userId, method, path, status, ms) and use them everywhere.

Two cautions. Do not log secrets or personal data: passwords, tokens, full request bodies. And log errors where you handle them, once, with the stack, instead of at every layer they pass through, or one failure becomes six lines.

The client is a layer too

Errors that only happen in browsers are invisible to server logs: a failed fetch, a thrown exception in a React component, a slow render. Capture them with a client error reporter (a service such as Sentry, or a small endpoint of your own that receives window.onerror reports). Include the request id from the failed response when there is one, so the client report and the server log meet. See error handling across the stack for how the error shape carries it.

Traces

A trace follows one request through steps called spans: the HTTP handler, the database query, the call to the payment provider. OpenTelemetry is the vendor-neutral standard for emitting them; its Node setup instruments the HTTP server and common database drivers automatically, and sends data to a backend you choose. A trace turns “the endpoint is slow” into “the third query inside the endpoint takes 700 ms”. The concept across services is in distributed tracing. For a single API and one database, logs with a request id plus a few timings will get you a long way before you need a tracing backend.

I did not set up OpenTelemetry for this lesson, so everything in this paragraph is from its documentation rather than a run of mine.

What to alert on

An alert is a promise that a person should wake up. Make it count.

  • Error rate: the share of requests returning 5xx, over a few minutes.
  • Latency: the 95th or 99th percentile of response time, not the average, because averages hide the slow tail.
  • Availability: an external check that loads the real site and signs in, because a green internal health check can coexist with a broken app.
  • Saturation that precedes failure: disk almost full, database connections near the limit.

Alerting on CPU or on every individual exception teaches people to ignore the pager. Tie the alerts to what users feel, a topic developed in SLIs, SLOs and error budgets and monitoring, logging and alerting.

What the video covers

Better Stack’s “OpenTelemetry in Node.js - Traces, Metrics and Logs” is about 38 minutes and two years old. By its title it shows setting up OpenTelemetry in a Node app for all three signals, which is this lesson’s tracing and metrics half. It is from a company that sells an observability product, so expect that product in the demos. OpenTelemetry’s Node packages change quickly, so versions and import names in a two-year-old video may differ from today’s docs. I could not read a transcript. Hussein Nasser’s waterfall video is linked for the browser-side view of the same request.

Where this fits

Observability tells you something is slow. The next lesson is about finding out why, from the browser’s waterfall to the database query: performance across the stack.

Check yourself

  1. 01What problem does a request id solve?

    It ties together every log line, from the client report through the API to the query, that belongs to one request, so a single failure can be found by searching one value.

  2. 02How do logs, metrics and traces differ?

    Logs are individual events, metrics are numbers aggregated over time such as error rate and latency percentiles, and traces show the timed steps within one request.

  3. 03Why return the request id in a response header?

    So the client can show it in an error message or send it with a bug report, which lets you find that exact request in the logs.

  4. 04Why alert on error rate and latency rather than on CPU?

    Error rate and latency are what users experience, while high CPU might be harmless and low CPU might hide a broken app, so symptoms make better pages.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark