TExcelTAD
Home › System Design › Observability

Observability

A system you can't see into is a system you can't operate. Observability is the ability to answer "what is happening, and why?" from the outside, using the data the system emits. It rests on three pillars:

Signal What it is Answers Tools
Metrics Numbers aggregated over time (counters, gauges, histograms) Is something wrong? How much, since when? Prometheus, Datadog, CloudWatch
Logs Timestamped records of discrete events What exactly happened to this request? ELK/OpenSearch, Loki, Splunk
Traces The path of one request across services, as a tree of timed spans Where did the time go, which service failed? Jaeger, Zipkin, Tempo, OpenTelemetry

Metrics are cheap and great for alerts and dashboards; logs and traces are detailed and great for debugging. OpenTelemetry is the vendor-neutral standard for emitting all three.

What to measure: RED and USE

Two checklists cover most needs:

  • RED for every service: Rate (requests/s), Errors (failed requests/s), Duration (latency histogram).
  • USE for every resource (CPU, disk, connection pool): Utilisation, Saturation (queue length), Errors.

Latency must be recorded as a histogram (counts per latency bucket), not an average, so that percentiles can be computed later and aggregated across servers.

python · try it yourself
import bisect
import random

BUCKETS_MS = [5, 10, 25, 50, 100, 250, 500, 1000, float("inf")]

class Histogram:
    def __init__(self):
        self.counts = [0] * len(BUCKETS_MS)
        self.total = 0

    def observe(self, ms):
        self.counts[bisect.bisect_left(BUCKETS_MS, ms)] += 1
        self.total += 1

    def percentile(self, p):                    # upper bound of the bucket holding p
        target, running = p / 100 * self.total, 0
        for bound, count in zip(BUCKETS_MS, self.counts):
            running += count
            if running >= target:
                return bound

rng = random.Random(42)
h = Histogram()
errors = 0
for _ in range(10_000):
    slow = rng.random() < 0.03                  # 3% of requests hit a slow dependency
    h.observe(rng.uniform(300, 900) if slow else rng.lognormvariate(3, 0.4))
    errors += rng.random() < 0.002

print("rate: 10,000 requests in the window")
print(f"errors: {errors} ({errors / 10_000:.2%})")
for p in [50, 90, 99]:
    print(f"p{p} <= {h.percentile(p)} ms")
print("bucket counts:", dict(zip([str(b) for b in BUCKETS_MS], h.counts)))
rate: 10,000 requests in the window
errors: 21 (0.21%)
p50 <= 25 ms
p90 <= 50 ms
p99 <= 1000 ms
bucket counts: {'5': 1, '10': 367, '25': 6460, '50': 2741, '100': 120, '250': 0, '500': 102, '1000': 209, 'inf': 0}

The median is fine, but the p99 reveals the slow dependency affecting 3% of requests.

Structured logs

Write logs as structured key-value records (usually JSON), not free text, so they can be filtered and aggregated. Always include a request/trace id, so all lines from one request can be found together.

python · try it yourself
import json

def log(level, msg, **fields):
    print(json.dumps({"level": level, "msg": msg, **fields}, sort_keys=True))

trace_id = "4bf92f3577b34da6"
log("info", "request received", trace_id=trace_id, method="POST", path="/checkout", user_id=42)
log("warn", "payment retry", trace_id=trace_id, attempt=2, provider="cardco", latency_ms=1200)
log("error", "payment failed", trace_id=trace_id, error_code="card_declined", user_id=42)
{"level": "info", "method": "POST", "msg": "request received", "path": "/checkout", "trace_id": "4bf92f3577b34da6", "user_id": 42}
{"attempt": 2, "latency_ms": 1200, "level": "warn", "msg": "payment retry", "provider": "cardco", "trace_id": "4bf92f3577b34da6"}
{"error_code": "card_declined", "level": "error", "msg": "payment failed", "trace_id": "4bf92f3577b34da6", "user_id": 42}

Log levels need discipline: an error should mean someone may need to act. Never log secrets, passwords, full card numbers or tokens; mask personal data.

Distributed tracing

A trace follows one request through every service. Each unit of work is a span with a start time, a duration and a parent. The trace id travels in a header (W3C traceparent) on every call. Rendering the spans as a timeline shows the critical path at a glance:

python · try it yourself
spans = [   # (span id, parent, service/operation, start ms, duration ms)
    ("a", None, "gateway  POST /checkout",   0, 182),
    ("b", "a",  "orders   create_order",     3, 175),
    ("c", "b",  "users    get_user",         5,  12),
    ("d", "b",  "stock    reserve",         18,  25),
    ("e", "b",  "payment  charge",          44, 130),
    ("f", "e",  "cardco   external API",    50, 118),
    ("g", "b",  "orders   db insert",      175,   3),
]

children = {}
for s in spans:
    children.setdefault(s[1], []).append(s)

SCALE = 4   # ms per character
def render(parent=None, depth=0):
    for span_id, _, name, start, dur in children.get(parent, []):
        bar = " " * (start // SCALE) + "#" * max(1, dur // SCALE)
        print(f"{'  ' * depth + name:<30} {dur:4} ms |{bar}")
        render(span_id, depth + 1)

render()
gateway  POST /checkout         182 ms |#############################################
  orders   create_order         175 ms |###########################################
    users    get_user            12 ms | ###
    stock    reserve             25 ms |    ######
    payment  charge             130 ms |           ################################
      cardco   external API     118 ms |            #############################
    orders   db insert            3 ms |                                           #

The trace makes the culprit obvious: 118 of the 182 ms are spent waiting for an external card API inside the payment call. No amount of tuning the orders service would help.

SLOs and alerting

Alert on symptoms users feel (error rate, latency SLO burn), not on every cause (CPU at 80%). A good pattern is error-budget burn-rate alerts: page someone only when the budget is being consumed fast enough to run out soon.

python · try it yourself
SLO = 0.999                         # 99.9% of requests succeed over 30 days
budget = 1 - SLO                    # 0.1% may fail

def burn_rate(error_ratio):
    return error_ratio / budget

windows = {"last 5 min": 0.0005, "last 1 h": 0.016, "last 6 h": 0.0062}
for window, error_ratio in windows.items():
    rate = burn_rate(error_ratio)
    days_left = 30 / rate if rate else float("inf")
    print(f"{window:<10} errors {error_ratio:.2%}  burn rate {rate:5.1f}x  budget gone in {days_left:5.1f} days")

fast = burn_rate(windows["last 1 h"]) > 14.4    # Google SRE's 1-hour page threshold
print("page on-call:", fast)
last 5 min errors 0.05%  burn rate   0.5x  budget gone in  60.0 days
last 1 h   errors 1.60%  burn rate  16.0x  budget gone in   1.9 days
last 6 h   errors 0.62%  burn rate   6.2x  budget gone in   4.8 days
page on-call: True

A burn rate of 1 means the budget lasts exactly the 30-day window; 16x means it would be gone in under two days, which deserves a page.

Tip: Every alert should be actionable and link to a runbook. Alerts that fire often and need no action train people to ignore pages, which is how real incidents get missed.

Test yourself

Which signal is best for finding which service made one specific request slow?

  1. A CPU metric
  2. A distributed trace
  3. The number of log lines
  4. An uptime check

Why record latency as a histogram instead of an average?

  1. Histograms use less memory than one number
  2. Percentiles can be computed and aggregated across servers, and tails stay visible
  3. Averages can't be graphed
  4. Histograms are required by HTTP

What does a burn rate of 10x for a 30-day SLO mean?

  1. 10 errors per second
  2. At this error rate the error budget would be used up in 3 days
  3. The service is 10x faster
  4. 10% of requests fail