Rana Maninder Singh
Lesson 9 of 12DevOps & Platform Engineering

Observability: Metrics, Logs, Traces & Alerts

Lesson opener

In one line: Move beyond "is it up?" monitoring to genuine observability—correlating metrics, logs, and traces so any novel failure becomes diagnosable without deploying new code.

Why it matters: Systems fail in ways that were never anticipated. Monitoring tells you that something is wrong; observability tells you why. Without structured telemetry, correlation IDs, and calibrated alerts, engineers spend the incident fighting the instrumentation rather than the fault.

Before this lesson: Source Control & Collaboration, CI/CD Pipelines, Testing & Quality Gates, Containerisation & Docker, Kubernetes & Managed Runtimes, Infrastructure as Code, Deployment Strategies, Security in the Pipeline.

Cross-domain references: Cybersecurity Foundations, Network & Cloud Security, Cloud Security for Data & AI, Security Architecture & Governance, Scalability, Reliability & Resilience, Real-Time Data Engineering: Analytics & Monitoring, LLMOps: Observability, Tracing & Operational Dashboards, MLOps: Monitoring & Drift.

What you will be able to do

Deliverable: an observability design document for the Northline order-processing service covering: SLI/SLO table with error budgets, correlation-ID propagation plan, alert rules for the four golden signals (burn-rate style), a retention and privacy table, and a three-entry runbook for the most frequent alert scenarios.

Prerequisites

PrerequisiteWhy it matters here
CI/CD PipelinesObservability instrumentation is wired into the build; dashboards validate each deployment.
Containerisation & DockerContainer metadata labels propagate into metric dimensions and log fields.
Kubernetes & Managed RuntimesCluster-level signals (node pressure, pod restarts, HPA events) feed the platform dashboard.
Deployment StrategiesCanary and blue/green promotions use SLO signals as their automated gate.
Security in the PipelineAudit logs from security scanning feed the observability platform.
Scalability, Reliability & ResilienceCapacity models set the saturation thresholds that alerts reference.
LLMOps: Observability, Tracing & Operational DashboardsParallel treatment for ML inference paths; same pillars, different signal names.
MLOps: Monitoring & DriftDrift detection adds a model-specific signal dimension when serving ML predictions.
Real-Time Data Engineering: Analytics & MonitoringStream-processing pipelines have consumer-lag and throughput SLIs built on the same pillars.

Plain English

Monitoring vs observability

Monitoring answers a question you anticipated: "Is the error rate above 5 %?" It works by comparing current measurements against pre-defined thresholds. A threshold, an alert, a dashboard—monitoring is necessary and valuable for known failure modes.

Observability is a property of the system, not a product you buy. A system is observable when you can understand its internal state from its external outputs alone, without needing to deploy new code or add new instrumentation. The practical test: when something fails in a way that has never happened before, can the on-call engineer diagnose it from already-flowing telemetry?

Monitoring and observability are complementary and both required. Monitoring wakes the engineer; observability guides the diagnosis.

The three telemetry pillars

Metrics

A metric is a numeric measurement sampled over time. Prometheus defines four types:

TypeWhat it capturesExample
CounterMonotonically increasing countrequests_total, errors_total
GaugeCurrent value, can go up or downactive_connections, memory_bytes
HistogramDistribution of observations in configurable bucketsrequest_duration_seconds_bucket
SummaryClient-side quantile computationAvoid for multi-instance services (not re-aggregatable)

Metrics answer "how much?" and "how fast?". They are cheap to store, fast to query, and suitable for alerting and capacity planning. What they cannot answer is why a counter rose or which specific request caused a latency spike.

Naming convention: <namespace>_<subsystem>_<measurement>_<unit>[_total|_bucket|_count|_sum]. Example: northline_orders_http_request_duration_seconds_bucket. Consistent naming makes dashboards composable across teams.

Use OpenMetrics format and expose metrics on /metrics. All services in the platform use the same scrape configuration and label taxonomy (service, version, environment, region).

Logs

A log is a timestamped, discrete record of an event: a request arrived, a query executed, an exception was thrown, a configuration was loaded. Logs answer "what happened and in what context?"

Structured logging (JSON or logfmt) is mandatory in a microservices environment. Free-text strings are human-readable for a single process but are unqueryable at scale. Every log line must carry at minimum:

{
  "timestamp": "2026-10-01T15:42:00.123Z",
  "level": "ERROR",
  "service": "order-processing",
  "version": "2.7.1",
  "environment": "production",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "span_id": "00f067aa0ba902b7",
  "message": "payment gateway timeout",
  "order_id": "ORD-8821",
  "gateway_host": "pay.internal.northline.com"
}

Privacy in logs. Logs must never contain passwords, API keys, session tokens, full payment-card numbers, national identity numbers, or health records. Apply scrubbing at the point of emission—in the logging middleware—not downstream in a pipeline. If a field is necessary for diagnosis (user ID, order ID), pseudonymise it or record only a hash. Disabling logging to improve performance is never acceptable. Profile the logging code, switch to an asynchronous appender, reduce DEBUG verbosity in production, or sample non-error trace logs—but audit and error logs remain intact always.

Retention follows data classification. Debug logs: 7–14 days. Application INFO logs: 30 days. Security and audit logs: 90 days to 1 year (confirm against organisational policy and any applicable regulation). Retention is enforced at the log-platform level, not by manual deletion.

Traces

A trace is a record of the complete journey of one request through a distributed system. It is composed of spans: each span is one unit of work—a service call, a database query, an external API call—with start time, duration, attributes, and status.

Traces answer "where did the time go and where did it break?" They expose the specific hop in a five-service chain that added 800 ms, the database query that never returned, and the retry loop that inflated tail latency.

W3C Trace Context (traceparent, tracestate HTTP headers) and OpenTelemetry are the open standards. Adopt them from day one; proprietary tracing formats create vendor lock-in and prevent cross-service correlation.

Sampling. Storing every span at 10,000 req/s is expensive. Head-based sampling (decide at ingress) discards interesting errors. Tail-based sampling—buffer spans and sample retrospectively once the trace is complete—retains all errors and slow traces while discarding a proportion of routine successful traces. A practical default: sample 1–5 % of fast, successful traces; retain 100 % of error traces and traces exceeding the p99 latency threshold.

Events

An event is a discrete, structured occurrence that does not fit neatly into the metric/log/trace model: a deployment, a feature-flag toggle, a scale-out action, a certificate rotation. Events overlay on dashboards as annotations, so engineers can correlate a latency spike with the deployment that caused it. Events are lightweight and should be emitted by every pipeline action and every infrastructure change.

Correlation IDs

A correlation ID (also called request ID or trace ID) is a unique identifier generated at the entry point of a request—the API gateway, load balancer, or BFF—and propagated in every downstream call, every log line, every span, and every message-queue message attribute.

Propagation rules:

  1. Generate at the system boundary if the inbound request carries no traceparent. Accept the caller's ID if it does (trusted B2B or service-mesh calls).
  2. Forward in HTTP headers (traceparent), gRPC metadata, and message-queue attributes.
  3. Inject into every log line via a logging middleware or MDC (Mapped Diagnostic Context in JVM; contextvars in Python).
  4. Do not log the correlation ID alongside sensitive fields in the same log entry without scrubbing the sensitive fields first.

Without correlation IDs, a five-service call chain produces five independent, unrelated log streams. With them, a single query returns one explorable timeline for any request—even one that happened three days ago.

SLIs, SLOs and error budgets

Service Level Indicator (SLI): a quantitative measure of one dimension of user-visible service behaviour, expressed as a ratio of "good" events to total events. Example: the proportion of order-API HTTP requests that return a non-5xx status code within 800 ms, measured at the load balancer.

Service Level Objective (SLO): the target value for an SLI over a rolling time window. Example: 99.5 % of order-API requests must satisfy the SLI criterion over any trailing 28-day window.

Error budget: the complement of the SLO. At an SLO of 99.5 %, the budget is 0.5 %—equivalent to approximately 3.6 hours of complete unavailability over 30 days, or a proportionally longer period of partial degradation. The budget is shared between unplanned outages and planned releases that risk stability. When the budget is more than 50 % consumed, the team's first priority shifts to reliability work. When it is exhausted, new feature releases stop until the window rolls forward or reliability improves.

SLA (Service Level Agreement): a contractual commitment to a customer with a financial or reputational consequence for breach. An SLA must always be less ambitious than the corresponding SLO, so that an SLO breach does not automatically become a contractual breach.

SLOs replace opinion with evidence in prioritisation debates.

The four golden signals

Defined by Google SRE; applicable to any request-serving service:

SignalWhat it measuresMetric type
LatencyTime to serve a request. Distinguish successful latency from error latency—fast errors mask slow service.Histogram (p50, p95, p99)
TrafficDemand on the system: requests per second, bytes per second, messages per minute.Counter + rate()
ErrorsRate of failed requests—explicit HTTP 5xx, implicit wrong answer, SLO-violating slow response.Counter, labelled by status code and error class
SaturationHow "full" the service is: CPU, memory, connection pool, thread pool, queue depth, disk.Gauge

Collect all four at every layer: application, container, node, and network. If a service has only four dashboard panels, these are the four.

Alert fatigue and burn-rate alerting

Alert fatigue occurs when alerts fire so frequently—or so non-urgently—that engineers begin ignoring or silencing them. The causes: alerting on raw metrics that are not yet user-visible (CPU > 70 %), thresholds chosen by guesswork rather than SLO arithmetic, and transient spikes that self-resolve before the page reaches an engineer. The result is that real incidents are missed.

Error-budget burn rate alerting solves this. Instead of comparing a metric to a static threshold, it measures the rate at which the error budget is being consumed relative to the rate needed to exhaust it over the SLO window.

At an SLO of 99.5 % over 30 days:

Alert at two rates with two complementary windows to balance detection speed against false-positive rate:

This produces far fewer alerts, all actionable, all tied to a concrete SLO impact. Every suppressed non-critical alert reduces the noise that causes engineers to dismiss real ones.

Synthetic monitoring

Synthetic checks (external probing) issue scripted requests to the service from a managed network outside the cluster on a schedule, and record whether the service responds correctly and within the target latency. They detect failures that internal metrics cannot: DNS misconfiguration, TLS certificate expiry, load-balancer path routing errors, and CDN edge-cache failures.

Types:

Synthetic alerts must fire from outside the cluster. A probe running inside the cluster that is itself down cannot detect the outage.

Dashboards

A dashboard is a tool for one audience answering one question. Build three tiers:

TierAudienceContent
Business / executiveVP Engineering, product ownersSLO compliance %, incidents last 30 days, error budget consumed, orders per hour
Service healthOn-call teamFour golden signals, SLO gauge, burn-rate chart, top-5 error classes, link to runbook
DebugEngineer during an incidentPer-endpoint latency histograms, dependency health, queue depth, resource per pod, trace samples

Rules: every panel has a title, a unit, a time range, and a link to the runbook section. Panels without a defined action are not dashboards—they are wallpaper.

Privacy, retention and compliance

Telemetry typePII riskRetention policyKey rule
Metrics (no PII labels)Low15 days full resolution, then downsampled to 90 daysDrop high-cardinality labels that identify individuals
Application INFO logs (structured)Medium30 daysScrub at emission
Audit and security logsLow (if pseudonymised)90 days–1 yearNever shorten; archive to cold storage
Full request tracesHigh (headers, paths, query params may carry PII)14 daysScrub PII attributes before ingestion
Sampled slow/error tracesMedium30 daysSame scrubbing rules

Never disable logging or tracing for performance. Fix the logging code, use asynchronous appenders, or reduce verbosity in non-production environments.

Root cause analysis and runbooks

Root cause analysis (RCA) identifies the underlying systemic cause of an incident, not just the proximate trigger. The five-whys technique iterates: "The service returned 500s → the database connection pool was exhausted → a slow query held connections for 45 s → the index was dropped during a migration → the migration ran without review against the production schema." The root cause is organisational (no migration review gate), not merely technical.

A runbook is a documented step-by-step response procedure for a specific alert. A useful runbook entry contains:

Runbooks rot when no one owns them. Assign an owner per runbook section and a "last validated" date. During an incident, if a step is wrong, update the runbook before closing the ticket.

Teacher walkthrough

Build the observability design for the Northline order-processing service step by step.

  1. Identify user-visible behaviours. The order-processing service receives order submissions, validates inventory, calls the payment gateway, and emits a confirmation. User-visible outcomes: order accepted with a confirmation ID within 2 s, or a clear rejection (not an opaque 500). Every other internal detail is infrastructure. Write SLIs only for user-visible outcomes.
  1. Define SLIs at the boundary. Measure at the load balancer or API gateway—not from within the application—so that infrastructure failures (pod restart, DNS lookup failure) are included in the measurement.

- Availability SLI: proportion of non-health-check requests completing with HTTP 2xx or 4xx (not 5xx).

- Latency SLI: proportion of successful requests completing in under 800 ms.

- Payment-path SLI: proportion of payment-gateway calls completing with a non-error response within 3 s.

  1. Set SLOs. Availability: 99.5 % over 30 days (budget: 0.5 % ≈ 3.6 hours full outage). Latency: 99 % of request-minutes meeting the criterion over 30 days. Payment: 99.9 % over 30 days (higher because payment is synchronous and revenue-critical).
  1. Add application instrumentation. Add northline_orders_requests_total{status,endpoint} (counter) and northline_orders_request_duration_seconds{endpoint} (histogram) at the application layer. Wrap the payment-gateway call in an OpenTelemetry span. Propagate traceparent in every downstream HTTP call and message-queue attribute.
  1. Instrument logging. A request-scoped middleware injects trace_id, span_id, service, version, and environment into every log line. The middleware also scrubs card_number, cvv, password, and Authorization header values before the line is emitted. Log INFO for every completed request, ERROR for every 5xx, WARN for retries.
  1. Configure retention. Application logs: 30 days in warm storage. Payment and authentication audit logs: 90 days in warm storage, then archived for 1 year in cold storage. Traces: 14 days full resolution, 30 days for sampled error and slow traces.
  1. Build the three dashboard tiers. Service-health dashboard carries the four golden signals, the SLO gauge, a burn-rate chart, and a runbook link. Executive dashboard shows "Orders available this month" vs. last month and open incidents. Debug dashboard shows per-endpoint histograms, pod-level memory and CPU, connection-pool utilisation, and trace samples for slow requests.
  1. Write burn-rate alert rules. One alert pair per golden signal: a fast window at burn rate ≥ 14.4 for immediate page, a slow window at burn rate ≥ 6 for pending page. Add a synthetic HTTP probe (external) and a certificate-expiry probe (alert at < 14 days remaining).
  1. Write runbook entries. Three entries: HighErrorBurnRate (payment gateway failure or database connection exhaustion), HighLatencyBurnRate (slow query or slow dependency), PodRestartLoop (OOMKilled or liveness-probe misconfiguration). Each entry: impact, diagnosis steps, two likely root causes with distinguishing diagnostics, remediation, escalation path.
  1. Validate with synthetic traffic. Inject synthetic requests from the CI pipeline's post-deploy smoke-test job. Confirm metrics appear in the service-health dashboard within one scrape interval (60 s) before promoting to the next environment. Include one deliberate error request and confirm it appears in both the error counter and the trace store.

Worked example

The script below implements three observability primitives for the Northline order-processing service: availability SLI calculation, error-budget burn-rate computation, and runbook lookup. All request data is synthetic and deterministic. The script uses only the Python standard library and runs without modification.

# devops9_observability.py
# Synthetic observability primitives for the Northline order-processing service.
# All data is illustrative. Burn-rate thresholds follow the Google SRE Workbook pattern.

SLO_AVAILABILITY = 0.995   # 99.5 % availability SLO
SLO_LATENCY_MS   = 800     # latency SLI threshold in milliseconds
WINDOW_LABEL     = "last 10 min (synthetic)"

# Synthetic request log: (minutes_ago, http_status, duration_ms)
# 4 errors out of 20 requests gives an error rate of 20 %,
# which at a 0.5 % budget means a burn rate of 40× (burn all budget in < 45 min).
REQUESTS = [
    (0.5, 200, 210), (1.0, 200, 195), (1.5, 500,  45), (2.0, 200, 820),
    (2.5, 200, 310), (3.0, 200, 290), (3.5, 500,  30), (4.0, 200, 410),
    (4.5, 200, 190), (5.0, 200, 250), (5.5, 500,  40), (6.0, 200, 600),
    (6.5, 200, 310), (7.0, 200, 280), (7.5, 200, 370), (8.0, 200, 420),
    (8.5, 500,  55), (9.0, 200, 200), (9.5, 200, 215), (10.0, 200, 340),
]

RUNBOOK = {
    "HighErrorBurnRate": (
        "Impact: orders may be failing for customers.\n"
        "1. Open dashboard: order-service / Errors.\n"
        "2. Check payment gateway health endpoint: GET /health on pay.internal.northline.com.\n"
        "3. Filter logs: level=ERROR, trace_id=<from alert>.\n"
        "4. If gateway timeouts: escalate to payments-oncall.\n"
        "5. If DB connection pool exhausted (WARN 'pool timeout'): scale pool or restart."
    ),
    "HighLatencyBurnRate": (
        "Impact: orders are slow; customers see spinner beyond 2 s.\n"
        "1. Open dashboard: order-service / Latency histogram.\n"
        "2. Identify spike onset time and cross-reference with deployment events.\n"
        "3. Run EXPLAIN on slow_query_log for queries > 500 ms.\n"
        "4. Check connection pool utilisation gauge.\n"
        "5. If correlated with deploy: initiate rollback."
    ),
    "PodRestartLoop": (
        "Impact: reduced capacity; requests may fail during restart window.\n"
        "1. kubectl describe pod <name> -n orders.\n"
        "2. Check Last State: OOMKilled -> increase memory limit in values.yaml.\n"
        "3. Check liveness probe failure -> confirm /health path and timeout setting.\n"
        "4. If repeated after fix: escalate to platform-oncall."
    ),
}


def availability_sli(requests):
    """Proportion of requests not returning a 5xx status code."""
    if not requests:
        return None, 0
    good = sum(1 for _, status, _ in requests if status < 500)
    return good / len(requests), len(requests)


def latency_sli(requests, threshold_ms=SLO_LATENCY_MS):
    """Proportion of successful requests completing within the latency threshold."""
    successful = [(m, s, d) for m, s, d in requests if s < 500]
    if not successful:
        return None, 0
    good = sum(1 for _, _, d in successful if d < threshold_ms)
    return good / len(successful), len(successful)


def burn_rate(sli_value, slo=SLO_AVAILABILITY):
    """
    Burn rate = observed error rate / allowed error rate.
    Rate 1.0  → consuming budget at the sustainable pace (30 days to exhaust).
    Rate 14.4 → budget exhausted in ~2 hours (30 days / 14.4 / 24 ≈ 2 h).
    Rate 40.0 → budget exhausted in < 45 minutes.
    """
    allowed_error_rate = 1.0 - slo          # 0.005
    observed_error_rate = 1.0 - sli_value   # 1.0 - 0.80 = 0.20
    return observed_error_rate / allowed_error_rate


def alert_level(rate):
    if rate >= 14.4:
        return "PAGE NOW  — budget exhausts in < 2 h; wake on-call immediately"
    if rate >= 6.0:
        return "WARN      — budget exhausts in < 5 h; investigate without delay"
    if rate >= 1.0:
        return "MONITOR   — consuming faster than sustainable; plan reliability work"
    return "OK        — within error budget"


def correlation_id_example():
    """Demonstrate what a structured log line looks like with a correlation ID."""
    return {
        "timestamp":   "2026-10-01T15:42:00.123Z",
        "level":       "ERROR",
        "service":     "order-processing",
        "version":     "2.7.1",
        "environment": "production",
        "trace_id":    "4bf92f3577b34da6a3ce929d0e0e4736",
        "span_id":     "00f067aa0ba902b7",
        "message":     "payment gateway timeout after 3001 ms",
        "order_id":    "ORD-8821",
        # card_number intentionally absent — scrubbed at emission
    }


# --- Run ---
avail, n_total = availability_sli(REQUESTS)
lat, n_success  = latency_sli(REQUESTS)
br              = burn_rate(avail)

print("=== Northline Order-Processing — Observability Report ===")
print(f"Window             : {WINDOW_LABEL} ({n_total} requests)")
print(f"Availability SLI   : {avail:.4f}   (SLO target: {SLO_AVAILABILITY})")
print(f"Latency SLI        : {lat:.4f}   ({n_success} successful requests, threshold {SLO_LATENCY_MS} ms)")
print(f"Error rate         : {1-avail:.4f}   (allowed: {1-SLO_AVAILABILITY:.4f})")
print(f"Burn rate          : {br:.1f}×")
print(f"Alert level        : {alert_level(br)}")
print()
print("--- Structured log example (correlation ID propagated) ---")
import json
print(json.dumps(correlation_id_example(), indent=2))
print()
print("--- Runbook: HighErrorBurnRate ---")
print(RUNBOOK["HighErrorBurnRate"])

Expected output (deterministic with the synthetic data above):

=== Northline Order-Processing — Observability Report ===
Window             : last 10 min (synthetic) (20 requests)
Availability SLI   : 0.8000   (SLO target: 0.995)
Latency SLI        : 0.9375   (16 successful requests, threshold 800 ms)
Error rate         : 0.2000   (allowed: 0.0050)
Burn rate          : 40.0×
Alert level        : PAGE NOW  — budget exhausts in < 2 h; wake on-call immediately

The 40× burn rate in this synthetic window reflects 4 errors in 20 requests (20 % error rate against a 0.5 % budget). In the real Prometheus alert, the query evaluates a rate() over 1 hour and 6 hours, not a small synthetic batch, which smooths transient spikes.

Check your understanding

  1. A service returns HTTP 200 for every request but takes 4 s for 15 % of them. Which SLI is breached, and how would you express it as a ratio?
  2. A team adds a Datadog dashboard that shows average CPU across all pods. Which golden signal does it partially represent, and what is wrong with using the average rather than a per-pod gauge with a saturation threshold?
  3. Your SLO is 99.9 % over 30 days. The error rate over the last hour is 0.5 %. What is the burn rate, and should the on-call engineer be paged?
  4. A developer proposes disabling DEBUG-level trace logging in production because it "doubles log ingestion cost". What is the correct response, and what should be done instead?
  5. A log line contains "user_email": "priya.k@northline.com". Why is this a privacy problem, and what should the structured log contain instead?
  6. A runbook entry says "Check if something is wrong with the database." Why is this not a useful runbook entry, and what would a good one say?

Summary

ConceptOne-line definition
ObservabilityProperty of a system: internal state understandable from external outputs without new instrumentation.
MetricsNumeric time-series measurements; cheap to store; answer "how much?"
LogsTimestamped event records; answer "what happened?"
TracesDistributed-request timelines composed of spans; answer "where did time go?"
Correlation IDUnique identifier propagated across all services for one request; enables cross-pillar search.
SLIRatio of good events to total events, measured at the service boundary.
SLOTarget value for an SLI over a rolling time window.
Error budgetComplement of the SLO; shared between outages and feature releases.
Burn rateCurrent error rate divided by allowed error rate; drives calibrated alerting.
Alert fatigueEngineers silencing pages because alerts are too frequent or not actionable; cured by burn-rate alerting.
Synthetic checkExternal scripted probe; detects failures invisible to internal metrics.
RunbookPer-alert procedure linking symptom → diagnosis → remediation.

The chain continues: Reliability Engineering & Incident Management uses the SLOs, burn rates, alerts, and runbooks built here as the inputs to incident command, error-budget policy, and blameless post-incident review.