Skip to article content
FrontendXLesson 16 / 20

Observability: structured logs and request metrics

Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.

advanced · about 45 minutes · 4 exercises

  • Predict
  • Explain
  • Implement

What you will be able to do

#
  • Build a structured, redacted log entry per model request with identity, parameters, outcome class and token usage.
  • Compute p50 and p95 latency from a fixed sample with a stated nearest-rank rule, and read what the gap between them says.
  • Choose counters and rates over prose for aggregate questions, and explain why message content does not belong in default logs.

Overview

#

Two questions every AI feature must answer

Operations needs to answer two questions continuously: is the feature working, and how fast is it. Per-request logs answer the first question for a specific request; aggregated metrics answer both questions for the whole feature. You need both shapes, and they fail differently: a log you cannot search is a diary, and a metric you cannot alert on is a decoration.

The structured log entry

Write one structured record per model request, at the boundary where the request is made:

snippet.javascript
function buildLogEntry(request, outcome) {
  return {
    requestId: outcome.requestId,
    model: request.model,
    temperature: request.temperature,
    outcomeClass: outcome.class,
    finishReason: outcome.finishReason,
    inputTokens: outcome.usage.inputTokens,
    outputTokens: outcome.usage.outputTokens,
    latencyMs: outcome.latencyMs
  };
}

Note what is absent: message content. Prompts and replies are user data (lesson 12), and logs are copied more widely and retained longer than almost any other artifact. The default log line carries identifiers, parameters, outcome classes, token counts and timings, never text. If debugging genuinely requires content, route it to a separate access-controlled, redacted, retention-bounded channel; the operational default stays clean.

The outcome classes reuse lesson 7's failure taxonomy plus cache_hit from lesson 15: ok, rate_limited, server_error, timeout, invalid_request, unauthorized, content_filtered, invalid_output, cache_hit. Counting by class converts "the feature feels broken" into "invalid_output rose from 0.1 percent to 4 percent after the prompt change", which is a statement you can act on.

Percentiles without a statistics library

Latency is a distribution, not a number. The two summaries that matter are p50, the typical request, and p95, the tail your users actually feel. The nearest-rank rule is precise enough to implement in five lines:

snippet.javascript
function percentile(sortedValues, p) {
  if (sortedValues.length === 0) return null;
  const rank = Math.ceil((p * sortedValues.length) / 100);
  const index = Math.min(sortedValues.length - 1, Math.max(0, rank - 1));
  return sortedValues[index];
}

State the rule you use: sort ascending, rank is ceil of p percent of n, take the value at index rank minus 1, clamped to the array. Other percentile definitions exist and give slightly different numbers; the engineering requirement is that yours is written down and never changes silently.

Worked sample, ten sorted request latencies in milliseconds: [120, 180, 210, 240, 260, 300, 320, 480, 900, 1500].

PercentileRankValue
p50ceil(500 / 100) = 5260
p95ceil(950 / 100) = 101500

The gap is the story: the median request is fine and the tail is almost six times worse, usually from retries stacking on cold starts. Averages hide exactly this, which is why the average is the first number to stop trusting.

Counters and rates

snippet.javascript
const counters = {};

function recordOutcome(label) {
  counters[label] = (counters[label] || 0) + 1;
}

A counter per outcome class is the cheapest useful metric. Alert on rates over a window, never on single failures: one timeout is noise, a rising timeout rate is a signal, and lesson 19 turns that rate arithmetic into an error budget.

Trace ids across the pipeline

One requestId threaded through the cache lookup, the routing decision, every tool-loop step and the final log line is what makes a request explainable after the fact. In this course that is a plain string passed through function arguments; in production it is the same idea carried in headers and log fields. Without it, "why did the agent do that" (lesson 11) has no answer.

Honest limits of the mock

The mock registry is in-memory with a fixed sample: no clock skew, no log shipping or retention, no cardinality explosion (the model label has a handful of values; a user-id label would have millions), no trace sampling, and no alert routing. Production observability adds all of those, plus the discipline of separating model-caused failures from your own code's failures on the dashboard.

Continue with ai-engineering-model-routing-and-cost: routing decisions are defensible only when cost and quality are measured, which is what these logs and counters enable.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement buildLogEntry(request, outcome) with exactly these fields in this order: requestId, model, temperature, outcomeClass, finishReason, inputTokens, outputTokens, latencyMs. requestId, outcomeClass, finishReason, usage and latencyMs come from outcome; model and temperature come from request. Log the entry for the scripted request.

    starter.javascript
    function buildLogEntry(request, outcome) {
      // Return { requestId, model, temperature, outcomeClass, finishReason,
      //   inputTokens, outputTokens, latencyMs } in exactly that order.
      // requestId, outcomeClass, finishReason, usage, latencyMs: from outcome.
      // model, temperature: from request.
    }
    
    const entry = buildLogEntry(
      { model: "mock-mini", temperature: 0 },
      { requestId: "req-1042", class: "ok", finishReason: "stop",
        usage: { inputTokens: 21, outputTokens: 8 }, latencyMs: 240 }
    );
    console.log(JSON.stringify(entry));

    Reveal the reference answer
    reference.javascript
    function buildLogEntry(request, outcome) {
      return {
        requestId: outcome.requestId,
        model: request.model,
        temperature: request.temperature,
        outcomeClass: outcome.class,
        finishReason: outcome.finishReason,
        inputTokens: outcome.usage.inputTokens,
        outputTokens: outcome.usage.outputTokens,
        latencyMs: outcome.latencyMs
      };
    }
    
    const entry = buildLogEntry(
      { model: "mock-mini", temperature: 0 },
      { requestId: "req-1042", class: "ok", finishReason: "stop",
        usage: { inputTokens: 21, outputTokens: 8 }, latencyMs: 240 }
    );
    console.log(JSON.stringify(entry));

    Authored expected output: {"requestId":"req-1042","model":"mock-mini","temperature":0,"outcomeClass":"ok","finishReason":"stop","inputTokens":21,"outputTokens":8,"latencyMs":240}

    The entry records identity, configuration, outcome class, finish reason, token usage and latency, and nothing about the message text. That shape is machine-parseable, redacted by construction, and sufficient to answer both operational questions.

  2. Exercise 2Implement

    Implement percentile(sortedValues, p) with the nearest-rank rule: rank = Math.ceil((p * sortedValues.length) / 100), then return sortedValues[rank - 1], clamped to the array bounds; return null for an empty array. Log p50 and p95 for the ten-latency sample.

    starter.javascript
    const LATENCIES = [120, 180, 210, 240, 260, 300, 320, 480, 900, 1500];
    
    function percentile(sortedValues, p) {
      // Empty array -> null. rank = Math.ceil((p * length) / 100).
      // Return sortedValues[rank - 1], clamped to the array bounds.
    }
    
    console.log(String(percentile(LATENCIES, 50)));
    console.log(String(percentile(LATENCIES, 95)));

    Reveal the reference answer
    reference.javascript
    const LATENCIES = [120, 180, 210, 240, 260, 300, 320, 480, 900, 1500];
    
    function percentile(sortedValues, p) {
      if (sortedValues.length === 0) return null;
      const rank = Math.ceil((p * sortedValues.length) / 100);
      const index = Math.min(sortedValues.length - 1, Math.max(0, rank - 1));
      return sortedValues[index];
    }
    
    console.log(String(percentile(LATENCIES, 50)));
    console.log(String(percentile(LATENCIES, 95)));

    Authored expected output: 260 1500

    p50 has rank ceil(500 / 100) = 5, so index 4 gives 260. p95 has rank ceil(950 / 100) = 10, so index 9 gives 1500. The 260 versus 1500 gap is the tail story: the median user is fine, the p95 user waits six times longer.

  3. Exercise 3Predict

    The mock registry counts outcome classes in insertion order. Five requests are recorded: ok, cache_hit, ok, rate_limited, ok. Predict both logged lines: the counters snapshot and the ok rate over the total.

    starter.javascript
    const counters = {};
    
    function recordOutcome(label) {
      counters[label] = (counters[label] || 0) + 1;
    }
    
    recordOutcome("ok");
    recordOutcome("cache_hit");
    recordOutcome("ok");
    recordOutcome("rate_limited");
    recordOutcome("ok");
    
    console.log(JSON.stringify(counters));
    const total = Object.values(counters).reduce((a, b) => a + b, 0);
    console.log(String(counters["ok"] / total));

    Reveal the reference answer
    reference.javascript
    // Predicted output:
    //
    // {"ok":3,"cache_hit":1,"rate_limited":1}
    // 0.6
    //
    // Trace: ok is recorded first, so it is the first key; cache_hit and
    // rate_limited follow in first-recorded order. Counts are ok 3,
    // cache_hit 1, rate_limited 1, total 5, so the ok rate is 3 / 5 = 0.6.
    // The rate is the alertable number; the class breakdown is the
    // diagnostic one.

    Authored expected output: {"ok":3,"cache_hit":1,"rate_limited":1} 0.6

    Insertion order keeps the snapshot deterministic, and the ok rate 0.6 over five requests is exactly the kind of windowed number lesson 19 turns into an error-budget check. Counts plus rate beat either alone.

  4. Exercise 4Explain

    Knowledge check: which set of fields belongs in the default per-request log line?

    starter.text
    // Choose the correct option.

    Reveal the reference answer
    reference.text
    Request id, model, outcome class, token usage and latency. These are identifiers and measurements, not user content, so the line is useful for operations and safe to retain, search and share.

    Authored expected output: Identifiers and measurements only, never message content

    Content in default logs is the most common observability defect in AI features; it turns every log store into a PII store. Lesson 12's data-boundary rules apply to logs too.

Common misconceptions

#
  • Myth: log the prompt and reply so debugging is easy. Fact: prompts and replies are user data; logging them creates a PII and retention liability. Log identifiers, counts, classes and timings, and keep content in a separate access-controlled channel when truly needed.
  • Myth: average latency is the number to watch. Fact: averages hide the tail; p95 and p99 describe the experience of the users who suffer.
  • Myth: a single failed request should page someone. Fact: single failures are noise; rates and error-budget burn over a window are the signals that merit action (lesson 19).

Follow-up practice

#
  • ai-engineering-model-routing-and-cost

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.