Skip to main content

Observability & SLOs

Learning objectives
  • Choose between logs, metrics and traces for a question, and keep each affordable (cardinality, sampling, retention)
  • Apply the RED and USE methods to services and resources
  • Instrument Go services with OpenTelemetry and propagate trace context across HTTP, gRPC and Kafka
  • Define SLIs and SLOs for a payment service, compute error budgets and design multi-window burn-rate alerts
  • Separate audit logging from observability logging and meet compliance expectations for each

TL;DR​

  • Metrics tell you that something is wrong (cheap, aggregated, alertable). Traces tell you where (one request across services). Logs tell you why (detailed events). Correlate them with a shared trace_id.
  • RED for every request-driven service: Rate, Errors, Duration. USE for every resource: Utilization, Saturation, Errors. Together they cover most dashboards.
  • OpenTelemetry is the vendor-neutral standard for instrumentation; W3C Trace Context (traceparent) carries trace IDs across HTTP, gRPC and message headers.
  • An SLI is a ratio of good events to valid events; an SLO is a target for it over a window; an SLA is a contract with penalties, set looser than the SLO. The error budget is 1 − SLO.
  • Alert on burn rate — how fast you're consuming the error budget — using multiple windows (fast burn pages, slow burn tickets), not on raw thresholds like "CPU above 80%".
  • Audit logs are a compliance record: complete, immutable, long-retained, access-controlled. Observability logs are a debugging aid: sampled, short-lived, droppable. Never use one as the other.

Why it matters​

At 20:05 during a sale, card approval rate drops from 92% to 70%. Is it your code, one PSP, one issuer, a BIN range, a fraud rule deployed at 20:00, or a network path? Without per-PSP and per-issuer metrics, traces across checkout → payment → PSP, and logs keyed by payment_id, you will spend the first hour guessing while revenue leaks. With them, you see within minutes that one PSP's p99 jumped and its timeouts trip your circuit breaker.

Banks add a second dimension: regulators and card schemes expect you to prove who did what to customer data and money — every limit change, every manual ledger adjustment, every access to card data. That is audit logging, and it has completely different requirements from debugging logs. And reliability itself becomes measurable and negotiable through SLOs: "payments must be 99.95% available" is meaningless until you define what counts as a good request and what happens when the budget runs out.

Core concepts​

The three signals (and friends)​

SignalAnswersCost driverRetention (typical)
MetricsIs it broken? How much? Trend?Number of time series (label cardinality)Months to years (downsampled)
TracesWhere is the time spent? Which hop failed?Number of spans stored (sampling)Days to weeks
LogsWhat exactly happened in this request?Volume (bytes/s)Days to weeks (hot), longer cold
ProfilesWhich code burns CPU or allocates?Sampling rateDays

Cardinality is the classic metrics trap: a label like payment_id or user_id creates one time series per value and can take down your metrics backend. Put high-cardinality identifiers in traces and logs; keep metric labels to bounded sets (psp, endpoint, status_class, region).

Structured logging​

  • Log events as key-value records (JSON), not prose. Consistent field names across services: trace_id, span_id, service, env, payment_id, merchant_id, outcome, duration_ms, err.
  • Use levels deliberately: ERROR means someone may need to act; most successful requests need no log line at all if you have metrics and traces.
  • Never log secrets or sensitive data: full card numbers (PAN), CVV, PINs, passwords, tokens, full national IDs. Mask PAN to first six/last four at most. Sensitive authentication data must never be stored after authorization under PCI DSS (see Compliance).
  • In Go, log/slog (standard library since Go 1.21) gives structured, leveled logging with context-aware handlers.

RED and USE​

  • RED (Tom Wilkie), per service and endpoint: Rate (requests/s), Errors (failed requests/s or ratio), Duration (latency distribution — histograms, look at p50/p95/p99, never just averages).
  • USE (Brendan Gregg), per resource — CPU, memory, disk, network, connection pools, thread/goroutine pools, queues: Utilization (% busy), Saturation (queued work: run-queue length, pool wait time, consumer lag), Errors.
  • Google's four golden signals — latency, traffic, errors, saturation — combine both views.

OpenTelemetry​

OpenTelemetry (OTel) provides APIs and SDKs for traces, metrics and logs, automatic instrumentation for common libraries, semantic conventions for attribute names (http.request.method, db.system, …), and the OTLP protocol. The Collector receives telemetry, processes it (batching, redaction, tail sampling) and exports to backends.

Running redaction in the Collector is a useful second line of defence: even if a developer accidentally attaches a card number to a span attribute, a processor can drop or hash it before it leaves your network.

Trace context propagation​

A trace is a tree of spans sharing a trace_id. To connect spans across processes, each hop forwards the context. The W3C Trace Context traceparent header looks like:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
version-trace_id (16 bytes hex)-parent span_id (8 bytes hex)-flags (01 = sampled)

tracestate carries vendor-specific data; baggage carries application key-values (e.g., merchant_tier=enterprise) to downstream services — keep it small and never put sensitive data in it.

Across asynchronous boundaries, put traceparent in message headers (the outbox row's headers column carries it — see Transactional Outbox & CDC). Consumers processing a batch of messages from many traces use span links rather than a single parent.

Sampling: head sampling decides at the start of the trace (cheap, but you might drop the interesting ones); tail sampling in the Collector decides after seeing the whole trace, so you can keep 100% of errors and slow traces and a small percentage of the rest.

SLI, SLO, SLA​

  • SLI (indicator): good events / valid events. Examples:
    • Availability: proportion of authorization requests that received a definitive answer (approved or declined) — a legitimate decline is a good event; a timeout or 5xx is bad.
    • Latency: proportion of authorizations answered within 2 s.
    • Freshness: proportion of minutes in which outbox lag is under 30 s.
    • Correctness: proportion of ledger transactions that balance (should be 100%; treat any miss as an incident, not budget).
  • SLO (objective): the target, over a window: "99.9% of authorization requests over a rolling 30 days".
  • SLA (agreement): a contract with consequences (service credits) — set looser than the internal SLO so you breach the SLO first and have time to react.
  • Measure where the user is: at the load balancer or gateway, or with synthetic probes, not only inside the service (which can't see requests it never received).

Error budgets​

The error budget is the allowed unreliability: 1 − SLO.

SLOBudget (30 days, time-based equivalent)Budget (requests, at 10M/month)
99%≈ 7.2 hours100,000 failed
99.9%≈ 43.2 minutes10,000 failed
99.95%≈ 21.6 minutes5,000 failed
99.99%≈ 4.3 minutes1,000 failed

Budgets make reliability a shared decision: while budget remains, ship features; when it's exhausted, an error budget policy shifts the team to reliability work (release freeze for risky changes, postmortem actions first). Each extra nine costs roughly an order of magnitude more effort — don't promise 99.99% for a service whose dependency (a PSP, a core-banking host) is only 99.9%.

Burn-rate alerting​

Burn rate = observed error ratio ÷ budgeted error ratio. A burn rate of 1 consumes exactly the whole budget over the SLO window; 14.4 consumes a 30-day budget in about two days.

The Google SRE Workbook recommends multi-window, multi-burn-rate alerts. For a 30-day SLO, a common set is:

SeverityLong windowShort windowBurn rateBudget consumed when it fires
Page1 h5 min14.42%
Page6 h30 min65%
Ticket3 days6 h110%

The long window gives significance (no paging on one bad minute); the short window makes the alert reset quickly once the problem is fixed. This replaces dozens of brittle threshold alerts with a few that track user pain.

groups:
- name: payments-slo
rules:
- alert: PaymentAuthFastBurn
expr: |
(
sum(rate(payment_authorize_requests_total{result="error"}[1h]))
/ sum(rate(payment_authorize_requests_total[1h]))
) > (14.4 * 0.001)
and
(
sum(rate(payment_authorize_requests_total{result="error"}[5m]))
/ sum(rate(payment_authorize_requests_total[5m]))
) > (14.4 * 0.001)
labels:
severity: page
annotations:
summary: "Payment authorization is burning its 30-day error budget at over 14x"

Dashboards for a payment service​

Build top-down, so on-call can go from "something is wrong" to "this PSP, this endpoint" in a few clicks:

  1. SLO row: authorization availability and latency SLIs, remaining error budget, current burn rates.
  2. Business health: approval rate overall and by PSP, card scheme, issuer country and BIN range; payment volume vs the same time last week; refund and chargeback rates. A sudden approval-rate drop is often the first sign of an integration problem.
  3. RED per endpoint: authorize, capture, refund, webhook ingestion.
  4. Dependencies: latency and error rate per PSP, circuit breaker state, retry rate vs budget, timeouts.
  5. Async health: outbox lag, Kafka consumer lag per group, age of the oldest PENDING payment, sagas by state and age.
  6. Correctness: reconciliation mismatches by type, transit/suspense account balance (should trend to zero), ledger balance check.
  7. USE for resources: DB connection pool utilization and wait time, CPU, memory, goroutines, GC pauses.

Audit logging vs observability logging​

AspectAudit logObservability log
PurposeAccountability, compliance, forensics, disputesDebugging, operations
AudienceAuditors, security, risk, legalEngineers, on-call
CompletenessEvery relevant action, no sampling, no dropsSampled or filtered; may drop under pressure
ContentWho (authenticated actor), what action, which resource, when, from where, outcome, before/after where relevantWhatever helps debugging, without sensitive data
IntegrityAppend-only, tamper-evident (WORM storage, hash chaining), restricted accessMutable pipelines are acceptable
RetentionYears, per regulation and internal policyDays to weeks
Write pathTransactional with the action (same DB tx or outbox to the audit store)Asynchronous, best-effort

PCI DSS Requirement 10 ("log and monitor all access to system components and cardholder data") is one concrete driver for banks and payment companies; data-protection laws and banking regulators add their own requirements. A manual ledger adjustment by an operator, a change to a customer's transfer limit, or viewing a full card number must produce an audit record that can't be silently lost or edited — which is why audit events belong in the same transaction as the action, not in a log line that a full disk can drop.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Metrics-firstCheap, fast queries, reliable alertingLow detail; cardinality limitsAlerting, SLOs, capacity trends
Traces with tail samplingKeeps every error and slow request; shows cross-service causalityCollector memory and complexityMicroservices with deep call chains
Head-sampled tracesSimple, cheapMay drop rare failuresHigh-volume, low-risk paths
Verbose logs everywhereMaximum detailCost, noise, PII riskShort-term debugging of a specific issue
Threshold alerts (CPU, error count)Easy to writeNoisy, miss slow burns, page for non-issuesResource safety nets only
Burn-rate SLO alertsPage only for user-visible pain; fast resetRequires good SLIs and some maturityPrimary paging strategy for user-facing services
Vendor-neutral OTelPortability, one instrumentationSome features lag vendor agentsDefault choice for new services

In practice​

Go: traces, metrics and logs that share a trace ID.

package payments

import (
"context"
"log/slog"
"time"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)

var (
tracer = otel.Tracer("payments")
authDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "payment_authorize_duration_seconds",
Help: "PSP authorization latency.",
Buckets: []float64{0.05, 0.1, 0.25, 0.5, 1, 2, 5},
}, []string{"psp", "outcome"}) // bounded labels only
)

func (s *Service) Authorize(ctx context.Context, req AuthRequest) (AuthResult, error) {
ctx, span := tracer.Start(ctx, "payments.authorize", trace.WithAttributes(
attribute.String("payment.id", req.PaymentID), // fine on spans, never as a metric label
attribute.String("payment.psp", req.PSP),
))
defer span.End()

start := time.Now()
res, err := s.psp.Authorize(ctx, req)
authDuration.WithLabelValues(req.PSP, outcomeOf(res, err)).Observe(time.Since(start).Seconds())

if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "psp authorize failed")
s.log.ErrorContext(ctx, "authorize failed",
"payment_id", req.PaymentID, "psp", req.PSP, "err", err)
return AuthResult{}, err
}
span.SetAttributes(attribute.String("payment.outcome", res.Outcome))
return res, nil
}

// TraceHandler adds trace and span IDs to every log record written with a context.
type TraceHandler struct{ slog.Handler }

func (h TraceHandler) Handle(ctx context.Context, r slog.Record) error {
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
r.AddAttrs(
slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()),
)
}
return h.Handler.Handle(ctx, r)
}

func (h TraceHandler) WithAttrs(as []slog.Attr) slog.Handler {
return TraceHandler{h.Handler.WithAttrs(as)}
}

func (h TraceHandler) WithGroup(name string) slog.Handler {
return TraceHandler{h.Handler.WithGroup(name)}
}

Use otelhttp / otelgrpc instrumentation (or a service mesh) for inbound and outbound propagation, and inject/extract traceparent into Kafka headers with the OTel propagator in your producer and consumer wrappers.

Practical rules:

  • Histograms with buckets around your SLO threshold (if the SLO is "under 2 s", have buckets at 1 s, 2 s, 5 s), so the SLI can be computed exactly.
  • One dashboard per service following the top-down layout above; link alerts to the dashboard and a runbook.
  • Exemplars (trace IDs attached to histogram samples) let you jump from a latency spike straight to an example trace.
  • Budget for telemetry: it is common for observability to become a noticeable share of infrastructure cost; sampling and retention policies are architecture decisions.

Common pitfalls​

  • Averages instead of percentiles. Symptom: "latency is fine" while 1% of customers wait 10 s.
  • High-cardinality labels. Symptom: metrics backend memory explodes after someone adds customer_id as a label.
  • Counting declines as errors. Symptom: availability SLO "breached" because customers had insufficient funds; real outages hide in the noise.
  • Broken propagation at async hops. Symptom: every trace ends at the Kafka producer; consumer work appears as unrelated traces.
  • Logging card data or tokens. Symptom: PCI scope suddenly includes your entire log platform; incident and audit finding.
  • Alerting on causes, not symptoms. Symptom: on-call paged for high CPU at 3 a.m. while customers are fine, and not paged for a slow, steady error increase.
  • Audit events written as log lines. Symptom: an auditor asks who changed a customer's limit last March and the logs rolled over after 14 days.
  • SLO without a policy. The budget is exhausted every month and nothing changes.

Interview angle​

  • Typical prompts: "How would you monitor a payment system?" "Define an SLO for checkout." "How do you trace a request across async services?" "What's the difference between audit and application logs?"
  • Strong answer: SLIs defined from the user's perspective (with declines counted as good responses), SLOs with error budgets and a policy, multi-window burn-rate paging; RED/USE dashboards plus business metrics (approval rate by PSP/issuer); OTel with W3C trace context including Kafka headers and tail sampling; audit trail written transactionally, immutable and long-retained; PII/PAN redaction.
  • Follow-ups: "How do you pick the SLO number?" (user expectations, dependency SLOs, historical performance, cost of nines). "What's a burn rate of 14.4?" "How do you keep tracing affordable at 50k req/s?"
  • Red flags: "we alert when CPU > 80%"; no distinction between SLA and SLO; logging full request bodies in a payment service; treating audit as just another log index.

Self-check​

1. When do you reach for metrics, traces and logs respectively?

Metrics to detect and quantify problems and drive alerts (cheap aggregates, long retention). Traces to locate where time or errors occur across services for a specific request. Logs for detailed event context explaining why a specific operation failed. A shared trace ID lets you pivot between them.

2. Define an availability SLI for card authorization. What counts as good and what is excluded?

Good events: authorization requests that received a definitive response (approved or declined) within the latency bound. Valid events: all well-formed authorization requests from authenticated clients. Declines due to the card or funds are good — the system worked. Timeouts, 5xx and "unknown outcome" responses are bad. Malformed requests (4xx caused by the client) are usually excluded from valid events.

3. Compute the error budget for a 99.95% monthly SLO on 20 million requests, and what burn rate 6 means.

Budget = 0.05% of 20 million = 10,000 failed requests (≈ 21.6 minutes of full outage over 30 days). A burn rate of 6 means errors are occurring six times faster than the budget allows; sustained, the whole monthly budget would be gone in about five days — over 6 hours it consumes 5% of the budget, which is the slower paging tier.

4. Why use both a long and a short window in burn-rate alerts?

The long window ensures the problem is significant (enough budget consumed) and avoids paging on brief blips. The short window ensures the problem is still happening, so the alert stops firing soon after recovery instead of staying active for the rest of the long window.

5. How do you keep a trace connected across a Kafka hop through an outbox?

At write time, inject the current traceparent into the outbox row's headers; the relay copies headers onto the Kafka message; the consumer extracts the context with the OTel propagator and starts its span as a child (or with a span link when processing batches from many traces).

6. Scenario: an auditor asks who raised customer 8812's daily transfer limit on 3 March and from which device. What must your audit design guarantee?

That the limit change produced an audit record atomically with the change itself (same transaction or a transactional outbox), containing the authenticated actor, action, resource, old and new values, timestamp, source IP/device and outcome; that the record is append-only and tamper-evident with restricted access; and that it is retained for the regulatory period — not in a debug log with two weeks of retention.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Instrument and define SLOs for a payment service:

  1. Take a Go payment service (or the one from the idempotency exercise). Add OTel tracing with otelhttp, a Collector in Docker exporting to Jaeger or Tempo and Prometheus, and the TraceHandler for slog.
  2. Propagate trace context through an outbox row and a Kafka consumer; verify a single trace spans API → DB → Kafka → consumer.
  3. Write SLIs and SLOs for authorization availability and latency, with an error budget policy (one paragraph).
  4. Implement the three-tier burn-rate alert rules and test them by injecting 2% and then 0.2% errors with a fault flag.
  5. Build the dashboard layout described above, at least rows 1, 3, 4 and 7.
  6. Add an audit table for limit changes written in the same transaction as the change.

Done when: the fast-burn alert fires within minutes of the 2% fault and clears within ≈ 5 minutes of removing it, the slow fault opens only a ticket, and an end-to-end trace shows the consumer span under the API span.

Further reading​

  • Betsy Beyer et al., Site Reliability Engineering (Google) — "Service Level Objectives" and "Monitoring Distributed Systems".
  • Betsy Beyer et al., The Site Reliability Workbook — "Implementing SLOs" and "Alerting on SLOs".
  • Alex Hidalgo, Implementing Service Level Objectives (O'Reilly).
  • Charity Majors, Liz Fong-Jones & George Miranda, Observability Engineering (O'Reilly).
  • Brendan Gregg, "The USE Method" (brendangregg.com).
  • Tom Wilkie, "The RED Method: How to Instrument Your Services" (Grafana Labs blog / talk).
  • OpenTelemetry documentation and the W3C Trace Context recommendation.
  • PCI Security Standards Council, PCI DSS v4.0 — Requirement 10.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).