Step 4 of 6

Observability & Caching

Logs, metrics, and traces tied together with correlation IDs; SLOs and alerts; and the caching patterns that keep systems fast.

15 min read

When a production system is slow or wrong, the first question is always where? Observability is how you answer it without guessing. Caching is how you stop paying - in latency and money - for work you've already done. This guide covers both, with notes on what's different for LLM systems.

Logs, metrics, and traces#

The three pillars answer different questions:

Logs

what happened

Discrete events with context: 'payment failed for order 123: card declined.' Best for debugging a specific request.

Metrics

how much, how often

Numbers aggregated over time: requests per second, error rate, p95 latency. Cheap to store; best for dashboards and alerts.

Traces

where time went

One request's path across services as a tree of timed spans. Best for finding the slow or failing hop.

Logs that help at 3 a.m.#

  • Structured JSON, not free text - so you can filter by user_id, route, or error_code.
  • A request id on every line, propagated across services.
  • Consistent levels (DEBUG, INFO, WARN, ERROR) with sensible defaults per environment.
  • No secrets or raw personal data. Redact tokens, passwords, and PII at the logger, not by hoping developers remember.
{"ts":"2026-09-28T21:14:03Z","level":"error","request_id":"req_8f2c","user_id":"u_1942",
 "route":"/api/answer","model":"small-v3","latency_ms":2310,"error":"retrieval_timeout"}

Metrics: the ones that matter#

For any service, start with the golden signals: traffic, errors, latency, and saturation. The common Prometheus → Grafana setup scrapes counters and histograms and graphs them.

MetricWhy it matters
RPS (requests per second)Load, capacity planning, anomaly detection
Error rateThe most direct measure of user pain
p50 / p95 / p99 latencyAverages hide the tail; p99 is what your unluckiest users feel
SaturationCPU, memory, GPU utilization, queue depth - how close you are to falling over
  • p50 (median)180 ms
  • p95620 ms
  • p992.4 s
Why percentiles: a service with a pleasant median can still have a painful tail. (Illustrative numbers.)

Traces and correlation ids#

A trace follows one request through the whole system. Each step is a span with a start time, duration, and attributes; spans nest to show what called what. Propagating a correlation id (trace id) through headers ties logs, metrics exemplars, and spans together - you jump from an alert, to a slow trace, to the exact log lines.

  1. 01API12 ms
  2. 02Retrieve140 ms
  3. 03Rerank95 ms
  4. 04LLM call1,850 ms
  5. 05Guardrail60 ms
A trace of one RAG request. The bottleneck is obvious - and it's rarely where people guess.

OpenTelemetry is the vendor-neutral standard for emitting all three signals; instrument once and send the data to whichever backend you like.

SLIs, SLOs, and alerts#

  • SLI (indicator): a measured ratio, e.g., "fraction of requests answered successfully in under 2 s."
  • SLO (objective): the target for it, e.g., "99.5% over 28 days."
  • Error budget: the 0.5% you're allowed to miss - spend it on shipping; when it's gone, prioritize reliability.

Alert on symptoms users feel (SLO burn rate, error spikes), not on every CPU blip. And watch cardinality: putting unbounded values like user ids into metric labels creates millions of time series and takes monitoring down with it - keep those in logs and traces.

SLI
Service Level Indicator - a measured ratio, e.g., 'fraction of requests answered successfully in under 2 seconds.'
SLO
Service Level Objective - the target for an SLI, e.g., '99.5% over 28 days.' The gap to 100% is the error budget you can spend on shipping.
Cardinality
The number of unique label combinations in a metric. Unbounded values (like user IDs) in labels create millions of time series and can crash monitoring.
Golden signals
The four metrics that matter for any service - traffic, errors, latency, and saturation.

What's different for LLM systems#

Add these to every trace of a model call: prompt and model version, input/output token counts, cost, time-to-first-token, tool calls made, and the retrieved document ids. Then you can answer "did the new prompt make answers worse?" and "which feature is burning our budget?" LLM-focused tools like Langfuse, Arize Phoenix, and Helicone build on these same ideas.

Caching strategies and patterns#

A cache keeps a copy of expensive-to-get data somewhere faster. The patterns differ in who loads the cache and when writes reach the database.

Cache-aside (lazy loading)

most common

The app checks the cache; on a miss, it reads the database and fills the cache. Simple and resilient - if the cache dies, the app still works. Risk: stale data until expiry.

Read-through

cache loads

The app only talks to the cache; the cache fetches from the database on a miss. Cleaner app code; needs a cache that supports loaders.

Write-through

sync writes

Every write goes to the cache and the database together. Cache is always fresh; writes are slower.

Write-back (write-behind)

async writes

Writes land in the cache and flush to the database later. Very fast writes; risk of data loss if the cache fails before flushing.

Write-around

skip cache on write

Writes go straight to the database; the cache fills only on reads. Avoids polluting the cache with data that's rarely read.

Keeping caches correct#

There are only two hard things in computer science: cache invalidation and naming things. - Phil Karlton

  • TTL (time-to-live): every entry expires after a set time. Simple, bounds staleness. Add random jitter so many keys don't expire at once.
  • Explicit invalidation: delete or update the key when the underlying data changes.
  • Versioned keys: include a version in the key (user:42:v7) so a change simply stops reading old entries.
  • Stampede protection: when a hot key expires, let one request rebuild it while others wait or serve the stale value.

Eviction policies#

When the cache is full, something must go:

PolicyEvictsGood for
LRU (least recently used)The item untouched the longestGeneral-purpose default
LFU (least frequently used)The item used least oftenStable popularity patterns
FIFOThe oldest inserted itemSimple, predictable workloads
TTL-basedExpired items firstData with natural freshness limits

Tools#

Redis - in-memory data structures (strings, hashes, sorted sets, streams), persistence options, replication, pub/sub; the default choice. Memcached - a simpler, multi-threaded key-value cache for pure caching. Managed services (e.g., AWS ElastiCache) run either for you in distributed setups.

Caching for LLM apps#

Exact cacheHash the full request; return the stored response. Great for repeated identical queries
Semantic cacheEmbed the query; reuse a response if a past query is similar enough. Tune the threshold carefully - near-duplicates aren't always the same question
Prompt (prefix) cachingProviders cache the processed prefix of long prompts (system prompt, documents), cutting cost and time-to-first-token on reuse
Retrieval cacheCache embeddings and search results for popular queries

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.