RecapsKayavak

Kayavak / Recaps / Observability and SRE

Recaps · Volume 9

Observability and SRE

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

97

The Signals of Observability

Key ideas

  • Monitoring vs observability: known conditions vs answering new questions from high-dimensional telemetry.
  • Signals: logs (events), metrics (aggregates), traces (request paths), profiles (where resources go), plus events such as deploys.
  • Cost models: metrics by series count; logs and traces by volume; sampling and retention as levers.
  • Correlation: trace/span IDs in logs, exemplars, resource attributes, consistent naming (OpenTelemetry semantic conventions).
  • Stack: instrumentation (SDKs, auto-instrumentation, eBPF), collection (agents, Collector), storage (Prometheus/Mimir/Thanos, Loki/Elasticsearch/ClickHouse, Tempo/Jaeger), visualisation (Grafana), vendors.

Numbers to remember

  • Lab: 412 bytes of logs and ~2.3 KB of spans per request vs a fixed 13 histogram series; 1,000 req/s ≈ 36 GB logs or ≈ 200 GB unsampled traces per day; logs gzip ~8.6×; 400 requests left 10 exemplars.

Pitfalls

  • High-cardinality metric labels.
  • Logging everything at DEBUG in production.
  • Signals without shared IDs or attributes.
  • Tracing without sampling at scale (or sampling away the errors).
  • Reading rates right after restarts or for brand-new series.

Glossary

  • Cardinality: number of distinct time series (label combinations).
  • Exemplar: example trace ID attached to a metric sample.
  • Resource attributes: attributes describing the emitting entity (service, host, version).
  • Sampling: keeping a subset of traces.
  • Profile: statistical record of where CPU or memory is spent.

98

OpenTelemetry

Key ideas

  • API / SDK split: libraries and apps depend on the no-op API; the application configures the SDK once (resource, sampler, processors, exporters).
  • Resource: who emits (service.name, service.version, deployment.environment.name, service.instance.id, host, k8s attributes).
  • Propagation: W3C traceparent (version-traceid-spanid-flags), tracestate, baggage; inject on outgoing, extract on incoming.
  • Semantic conventions: standard attribute names (http.request.method, url.path, db.system.name) so tools work across services.
  • OTLP over gRPC (4317) or HTTP/protobuf (4318).
  • Collector: receivers → processors → exporters in pipelines; connectors join pipelines; agent (near the app) and gateway (central) tiers; OTTL for transforms.
  • Sampling: head (parent-based ratio, decided at the root) vs tail (after completion, in a gateway); derive metrics before sampling.

Numbers to remember

  • Ports 4317 (gRPC) and 4318 (HTTP). BatchSpanProcessor default queue 2,048 spans, batch 512.
  • Lab: 300 spans in, 200 out after filtering; 60 spans buffered and delivered 7 s after the backend returned; 5,000 spans created in 0.09 s with no backend, then dropped.

Pitfalls

  • Using a vendor's API in application code.
  • Context not propagated (thread pools, async, queues, or the context= vs attach mistake): broken traces.
  • Secrets or large values in baggage.
  • Processors in the wrong order (batch before filter, no memory_limiter).
  • In-memory queues only, and nobody watching the Collector's own metrics.
  • Per-instance labels multiplying span-metric series.

Glossary

  • Span processor: SDK component that receives finished spans (batching, exporting).
  • Exporter: sends telemetry somewhere (OTLP, Prometheus, file).
  • Connector: Collector component that's an exporter of one pipeline and a receiver of another (spanmetrics, count, routing).
  • OTTL: OpenTelemetry Transformation Language for transform and filter processors.
  • Parent-based sampler: follows the parent's sampled flag; samples roots by a ratio.

99

Logging

Key ideas

  • Structured logs: one event per line, named fields, constant message, UTC timestamps, semantic-convention names.
  • Canonical log lines / wide events: one rich line per request per service.
  • Levels: DEBUG off in production; INFO for significant events; WARN for handled surprises; ERROR for failures.
  • Correlation: trace_id and span_id in every line, injected automatically by the logging integration.
  • Sensitive data: never log secrets; redact at the source and again in the pipeline; separate audit logs.
  • Collection: stdout → node agent (Collector, Fluent Bit, Vector) → backend (Loki, Elasticsearch/OpenSearch, ClickHouse-based, cloud logging); checkpoints; at-least-once.
  • Cost: volume × retention × indexing; sample noisy INFO, drop health checks, tier storage.

Numbers to remember

  • Lab: 12–15 µs per line to a file, 224 µs with fsync per line; disabled f-string debug 85.6 µs vs 0.23 µs lazy; JSON 148 vs text 65 bytes per line; print from 8 threads corrupted ~6% of lines.

Pitfalls

  • Variable messages; inconsistent field names across services.
  • Eager formatting in disabled debug calls.
  • Synchronous network or fsync sinks on the request path.
  • Lines interleaved by threads or processes sharing a stream.
  • Lost collector checkpoints (duplicates or gaps); copytruncate rotation.
  • Secrets, tokens and personal data in logs.

Glossary

  • logfmt: key=value text format, a lighter alternative to JSON.
  • Canonical log line: a single summarising line per request.
  • Checkpoint/offset: a collector's saved read position in a file.
  • Async appender / QueueHandler: hands records to a background thread.
  • Severity number: OpenTelemetry's numeric level (INFO = 9, WARN = 13, ERROR = 17).

100

Metrics

Key ideas

  • Data model: name + labels = series; samples of (timestamp, value).
  • Types: counter (rate/increase), gauge, histogram (buckets, _sum, _count), summary (client-side quantiles, not aggregatable); OpenTelemetry instruments map onto these.
  • Prometheus: pull scrapes, service discovery, PromQL, recording and alerting rules, remote write to Mimir/Thanos/Cortex/managed services.
  • Cardinality: series = product of label values; keep labels bounded; drop or limit at scrape time.
  • Percentiles: averages lie; percentiles aren't averageable; aggregate histogram buckets; bucket choice limits accuracy; native histograms.
  • What to measure: golden signals (latency, traffic, errors, saturation), RED for services, USE for resources.

Numbers to remember

  • Lab: one user_id label → 112 to 160,128 series, 87 to 350 MiB Prometheus RSS, a 12 MB metrics page and scrape timeouts.
  • Counter restart: increase() 394,773 (right) vs max − min 2,612,000 (wrong).
  • Combined p99 0.81 s vs average of p99s 1.11 s.

Pitfalls

  • Unbounded labels (IDs, URLs, emails, error messages).
  • sum() before rate(); arithmetic on raw counters.
  • Averaging percentiles; summaries when you need aggregation.
  • Buckets that don't straddle the SLO threshold.
  • Rate windows shorter than about four scrape intervals.

Glossary

  • Head block: Prometheus's in-memory recent data.
  • Recording rule: precomputed query saved as a new series.
  • Exemplar: trace ID attached to a sample.
  • Native histogram: sparse exponential-bucket histogram in one series.
  • Relabelling: rewriting or dropping targets and labels at discovery or scrape time.

101

Distributed Tracing

Key ideas

  • Model: trace = tree (DAG with links) of spans; span = name, kind, start, duration, attributes, events, status, parent, links.
  • Reading a trace: critical path, the deepest span explaining the time, gaps (queueing, uninstrumented work), fan-out.
  • Propagation: inject/extract at every boundary; carry context through thread pools, async tasks, queues (in message headers) and proxies.
  • Links vs parents: batch consumers and fan-in use span links.
  • Sampling: parent-based head sampling; tail sampling in a gateway with trace-ID load balancing; derive metrics before sampling.
  • Analytics: compare slow vs fast traces by attribute, service dependency maps, span metrics.

Numbers to remember

  • Lab: head 10% kept 2 of 24 errors; tail sampling kept 18/18 errors and 68/68 slow traces while storing 14% of traces; broken propagation joined 0 of 1,000 traces silently.

Pitfalls

  • A single library or proxy dropping traceparent.
  • Head sampling at low rates (losing rare errors).
  • Tail sampling without trace-aware routing; decision waits shorter than trace duration.
  • Huge spans (every SQL row, request bodies) or high-cardinality span names (IDs in names).
  • Clock skew between hosts confusing waterfalls.

Glossary

  • Span kind: SERVER, CLIENT, PRODUCER, CONSUMER, INTERNAL.
  • Critical path: the chain of spans that determines total latency.
  • Span link: reference to a span in another trace (or a non-parent in the same one).
  • Decision wait: how long tail sampling buffers before deciding.
  • loadbalancing exporter: Collector exporter that routes spans by trace ID.

102

SLIs, SLOs, SLAs and Error Budgets

Key ideas

  • SLI = good events / valid events; measured as close to the user as possible.
  • SLO = SLI target over a window (rolling 28/30 days for engineering, calendar for reporting); SLA = contract, looser than the SLO.
  • Error budget = 1 − SLO; an error budget policy decides what happens as it's consumed.
  • Burn rate = error ratio / budget ratio; multi-window, multi-burn-rate alerts page on fast burn and ticket on slow burn.
  • Composite SLOs across dependencies; SLOs per user journey, few and meaningful.
  • Tools: Sloth, Pyrra, OpenSLO, managed SLO features; test rules with promtool.

Numbers to remember

  • 28-day all-or-nothing budgets: 99% ≈ 6 h 43 min, 99.9% ≈ 40 min, 99.99% ≈ 4 min.
  • Workbook alerts (30-day window): 14.4× over 1 h/5 min (2% budget), 6× over 6 h/30 min (5%), 1× over 3 d/6 h (10%).
  • Lab: page after 9 min at 10% errors, 44 min at 2%; naive alert 12 false pages in 2 days.

Pitfalls

  • SLIs measured where users aren't (server CPU instead of request success).
  • Too many SLOs; 100% targets; SLOs nobody acts on.
  • Alerting on raw error rate.
  • Low-traffic services and new series breaking long-window maths.
  • Excluding "not our fault" failures users still felt.

Glossary

  • Valid events: the denominator after exclusions.
  • Rolling window: last N days, always moving.
  • Error budget policy: agreed consequences of budget levels.
  • Fast burn / slow burn: high burn rate over short windows / modest burn rate over long ones.
  • Composite SLO: combination of dependent services' SLOs for a journey.

103

Incident Management

Key ideas

  • Alerting: page on user-facing symptoms that need a human now; tickets for the rest; every page actionable with a runbook.
  • Routing: Alertmanager or an incident platform: grouping, inhibition, silences, escalation, schedules.
  • Severities: a shared scale (SEV1–SEV4) tied to user impact and response expectations.
  • Lifecycle: detect → triage/declare → mobilise (incident commander, communications, operations, scribe) → mitigate → diagnose → resolve → learn.
  • Communication: status page and stakeholder updates on a fixed cadence.
  • Postmortems: blameless, contributing factors rather than a single root cause, tracked action items.
  • Metrics: time to detect, acknowledge, mitigate, resolve; incident count by severity; repeat incidents.

Numbers to remember

  • Lab: 17 s to page (2 s scrapes + for: 10s + group_wait: 5s); 37 s to mitigate; 1 page with inhibition vs 2 without; 0 pages under a silence while users still saw errors.

Pitfalls

  • Paging on causes (CPU) rather than symptoms; unactionable pages; alert fatigue.
  • Debugging before mitigating.
  • No incident commander in a large incident; everyone debugging, nobody communicating.
  • Silences without expiry or comment; maintenance that hurts users.
  • Postmortems that blame people, or action items nobody tracks.

Glossary

  • Incident commander (IC): coordinates the response; doesn't debug.
  • Runbook / playbook: steps for a known alert or scenario.
  • Inhibition: suppressing alerts explained by another firing alert.
  • Silence: muting matching alerts for a period.
  • Game day: a planned exercise that injects failure to test systems and people.

104

Reliability Engineering

Key ideas

  • Redundancy without single points of failure; isolation with bulkheads, cells and shuffle sharding.
  • Health checks: liveness (restart me) vs readiness (send me traffic); don't let dependency failures fail liveness.
  • Timeouts and deadlines on every remote call; retries with backoff, jitter, caps and budgets, only for idempotent work.
  • Circuit breakers, graceful degradation and fallbacks; load shedding and admission control.
  • Autoscaling (with limits), failover (tested), disaster recovery with RPO/RTO and restore tests.

Numbers to remember

  • Retry amplification = attempts^layers (3 layers × 3 attempts = 27).
  • Lab: no timeout → /menu 91% failed; 500 ms timeout → 0%; breaker cut calls to a hung dependency 289 → 53; full jitter peak 18 vs 191 per 100 ms.

Pitfalls

  • Missing or infinite default timeouts; caller timeout shorter than callee's.
  • Retries at every layer; retrying non-idempotent operations.
  • Synchronised retries (no jitter); unbounded queues.
  • Health checks that cascade (liveness depending on the database).
  • Failover and backups never tested.

Glossary

  • Deadline propagation: passing the remaining time budget downstream.
  • Retry budget: cap on retries as a share of traffic.
  • Bulkhead: resource partition per dependency or tenant.
  • Shuffle sharding: assigning each customer a random subset of workers to limit blast radius.
  • RPO / RTO: maximum acceptable data loss / time to restore.

105

Production Performance Engineering

Key ideas

  • Vocabulary: latency (percentiles), throughput, utilisation, saturation, goodput, headroom.
  • Queueing: waiting time grows non-linearly with utilisation (roughly ρ / (1 − ρ)); variability makes it worse.
  • Little's law L = λW; utilisation law U = X × S; the bottleneck is the resource with the highest demand.
  • Scalability: Amdahl (serial fraction caps speed-up), USL (contention and coherence make throughput fall at high concurrency).
  • Method: USE for resources, RED for services, then profile; optimise the biggest share first.
  • Load testing: open vs closed models, coordinated omission, test types (load, stress, soak, spike), realistic data and think times.
  • Capacity planning: forecast demand, measure per-instance capacity at target latency, keep headroom, plan for failures (N+1 / N+2).

Numbers to remember

  • Lab: 4 workers × 10 ms → 400/s capacity; p50 8.4 ms at 30% load, 16.5 ms at 80%, 251 ms at 95%.
  • Overload at 120%: unbounded queue goodput 0; queue limit 40 kept p99 at 169 ms.
  • Coordinated omission: closed loop p99 7 ms vs open loop p99 996 ms on the same server.
  • Profiling: list → set took a job from 18.9 to 7.8 ms.

Pitfalls

  • Running near 100% utilisation; scaling on averages.
  • Unbounded queues and no admission control.
  • Closed-loop benchmarks quoted as latency results; tests from one region with tiny data sets.
  • Optimising without profiles; micro-optimising code that's 4% of the time.
  • Forgetting overhead (serialisation, network, GC) in capacity models.

Glossary

  • Goodput: useful throughput (within deadline, correct).
  • Coordinated omission: missing measurements because the load generator waits for the system.
  • Open / closed model: arrivals independent of / dependent on responses.
  • Inclusive / self time: with / without callees.
  • Congestion collapse: throughput maintained but goodput falling to zero under overload.