Logging and Monitoring
Structured logs, metrics, and traces for reliable AI backends.
In plain words
Logs are the diary of what your app did, and metrics are the counters and gauges that show how it's doing right now, so you can find and fix problems quickly.
Think of it like…
A flight recorder plus a cockpit dashboard. The dashboard (metrics) shows live altitude and speed at a glance, the recorder (logs) captures detailed events for later investigation and the flight path (traces) links them, but the recorder only keeps what is needed and never records passengers' private conversations.
Where you’ve seen it
Every request produces one wide structured log event at completion: {"ts":"2026-11-21T09:27:00Z","level":"info","request_id":"req_91","trace_id":"...","tenant_hash":"7c1a","route":"/v1/messages","status":200,"latency_ms":3410,"ttft_ms":610,"model":"large-2026-05","prompt_version":"15.1.0","tokens_in":3100,"tokens_out":420,"cost_usd":0.01195,"cache":"miss","retries":0,"finish":"stop"}, about 1.5 KB. At 100 requests a second that is 150 KB/s = 12.96 GB a day; adding the raw prompt and response (about 5 KB more) would raise it to 6.5 KB per request, 56.2 GB a day, so raw text is not logged by default: it is captured for 1% of traffic and for all errors, redacted for personal data, in a separate store with restricted access and a 14-day retention. Metrics follow the RED method (rate, errors, duration) plus AI signals: requests_total{route,status}, request_duration_seconds and ttft_seconds as histograms (so p50, p95 and p99 can be computed, since an average of 3.4 seconds hides a p99 of 12), tokens_total{direction}, cost_usd_total{model}, provider_errors_total{provider,code} and cache_hits_total. Cardinality is the trap: labelling a histogram by tenant_id for 10,000 tenants, 20 routes and 10 buckets creates 10,000 × 20 × 10 = 2,000,000 time series and a surprise monitoring bill; labelling by plan (3 values) gives 3 × 20 × 10 = 600, and per-tenant detail goes to logs or a dedicated analytics table instead. Logs and metrics share names and a request_id/trace_id, so an alert on rising p99 leads to the matching log lines and trace within a click. Levels are used with discipline: info for one event per request, warn for retries and fallbacks, error for failures that need attention, and debug off in production except with a time-limited flag. Dashboards show traffic, errors, latency percentiles, cost per hour, cache hit rate and provider health, annotated with deploys, and alerts (see the alerts lesson) page on user-visible symptoms. Access to log stores is role-based and audited.
Words you’ll hear
- Structured log
- A log event as a JSON object with named fields rather than free text.
- Histogram
- A metric type that counts observations in buckets so percentiles can be computed.
- Cardinality
- The number of distinct label combinations, and therefore time series, a metric creates.
- RED method
- Rate, errors and duration: the three basic service metrics.
Visual diagram
Theory & deep dive
Structured logging and its costs
Log events as JSON with a stable schema so they can be filtered and aggregated: timestamp, level, request_id, trace_id, route, status, latency and your AI fields (model, prompt version, tokens, cost, TTFT, cache result, retries, finish reason). Prefer one wide event per request at completion, supplemented by warn and error events for exceptional paths, over scattering many narrow lines. Propagate the request_id through every service and return it to clients so support can find a request instantly. Use levels with discipline (info for the request summary, warn for retries and fallbacks, error for failures needing attention) and keep debug off in production, enabled temporarily by flag for a tenant or request.
Volume costs money. A 1.5 KB event at 100 requests a second is 150 KB/s, 12.96 GB a day; adding raw prompts and responses (about 5 KB more) takes it to 6.5 KB per request, 56.2 GB a day, and puts sensitive text into a general-purpose store. So don't log raw payloads by default. Instead sample (for example 1% of requests plus 100% of errors), redact personal data and secrets before writing, store sampled payloads in a separate, access-controlled location with a short retention (14 days) and log hashes or lengths where you only need to correlate. Set retention tiers (hot for 14 days, cold archive for compliance if required) and monitor ingestion volume as a metric of its own.
Summary event 1.5 KB × 100 req/s = 150 KB/s × 86,400 s = 12.96 GB/day. With raw prompt and response (+5 KB): 6.5 KB × 100 × 86,400 = 56.2 GB/day, 4.3× larger and carrying personal data. Sampling 1% of payloads plus all errors keeps it near 13–14 GB/day.
Metrics, cardinality and linking signals
Metrics summarise behaviour cheaply. Use counters (requests, errors, tokens, cost), gauges (queue depth, open streams, in-flight requests) and histograms (latency, TTFT). Always prefer histograms over averages: a mean of 3.4 seconds can hide a p99 of 12 seconds, and percentiles are what users feel. The RED method (rate, errors, duration) covers every service; for AI add tokens in and out, cost per request, cache hit rate, provider error rate by code, queue age for workers and refusal or safety-flag rates. Slice by low-cardinality labels: route, status class, model, provider, plan.
Cardinality determines cost and performance of a metrics system: every distinct label combination is a time series. A latency histogram with 10 buckets labelled by tenant_id (10,000 tenants) and route (20) creates 10,000 × 20 × 10 = 2,000,000 series; labelling by plan (3 values) gives 3 × 20 × 10 = 600. Put high-cardinality detail (tenant, user, request) in logs or an analytics table, not metric labels. Make the three signals navigable: shared request_id and trace_id, metric exemplars that link a slow bucket to a trace, deploy and flag-change annotations on dashboards, and consistent field names across services. Finally, test your monitoring: simulate a provider outage or a prompt regression in staging and confirm that dashboards, logs and alerts show it, and review telemetry access and retention regularly as a privacy control.
Labels tenant_id (10,000) × route (20) × buckets (10) = 2,000,000 series. Labels plan (3) × route (20) × buckets (10) = 600 series. Same dashboards for the business, 3,333 times fewer series; per-tenant detail comes from the log pipeline.
How it works, step by step
Step 1 of 41. Define the log schema
Choose fixed JSON fields including request_id, trace_id and the AI fields, and emit one wide event per request.
- Size
- ≈ 1.5 KB
When to use it & trade-offs
What it is
Logging and monitoring give you visibility into a running backend. Structured logs are machine-readable events (JSON with fixed fields such as timestamp, level, request_id, tenant, route, status, latency_ms) that you can search and aggregate. Metrics are numeric time series (counters, gauges, histograms) cheap enough to keep for months and ideal for dashboards and alerts. Traces follow one request across services. For AI backends you add domain fields and metrics: model, prompt version, input and output tokens, cost, time to first token, finish reason, retries, cache hit, safety flags. The art is deciding what to record, at what volume and at what cost, while keeping personal data and raw prompts out of general-purpose logs.
Why it matters: When a model answer is wrong, slow or expensive, the only way to explain it is evidence captured at the time: which prompt version ran, how many tokens it used, which provider answered and how long each stage took. But telemetry has its own failure modes: unstructured logs nobody can query, metric labels that explode into millions of series, log bills that rival the compute bill and prompts full of personal data stored in a place with weak access control. Disciplined logging and monitoring turn incidents from guesswork into a few queries.
When to reach for it
- One structured summary event per request with AI fields
- RED metrics plus tokens, cost and TTFT histograms
- Sampled, redacted payload capture for debugging quality
When to avoid or be careful
- Logging raw prompts and responses for all traffic
- Tenant or user IDs as metric labels
- Free-text logs with no request ID
Telemetry types
Strengths: Rich context; searchable fields.
Watch out: Volume and privacy risk.
Strengths: Cheap, aggregated, long retention.
Watch out: Low detail; cardinality limits.
Strengths: Shows where time and cost go.
Watch out: Needs sampling and instrumentation.
Interview signals & numbers to know
When this topic comes up
- “How would you monitor an LLM service?”
- Logs versus metrics versus traces
- Why not use average latency
- Metric cardinality
- Handling personal data in logs
Benchmarks & rules of thumb
- 12.96 GB/day
- 1.5 KB summary events at 100 requests/s
- 56.2 GB/day
- the same traffic with raw prompts and responses added
- 2,000,000 vs 600
- series with tenant_id labels versus plan labels
Common mistakes & follow-ups
Common interview mistakes
- Alerting on averages that hide tail latency.
- Putting request IDs in metric labels.
- Storing prompts that contain personal data in a widely readable log index.
Likely interviewer follow-ups
- How would you debug one customer's slow requests?
- How would you find which prompt version raised costs?
- What would you log about a tool call?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Logging and Monitoring with generative AI interview Q&A and hands-on practice.