Metrics, Tracing and Health Checks

Metrics, Tracing and Health Checks in Flask: --- In the operations center of a container shipping port, three very different instruments hang side by side.


The Analogy: The Container Shipping Port Operations Center

In the operations center of a container shipping port, three very different instruments hang side by side. A wall of live dashboards shows aggregate numbers -- containers moved per hour, the average time a box waits on the quay, the percentage of cranes currently working. A tracking system lets a clerk type one container's unique number and see every scan it received: gate-in at 06:12, quay crane at 07:40, yard block D at 07:55, truck gate-out at 14:20. And a readiness board, lit green or red per berth, tells the harbor master whether a berth can accept the next ship at all -- is the crane powered, is there yard space, is customs online. The dashboards are your metrics; the per-container tracking is distributed tracing; the readiness board is your health checks.

The three exist because they answer different questions, and none of them can answer the others. The dashboards answer "is the port as a whole keeping up, and since when did it stop?" -- cheap aggregate numbers you watch continuously. The container tracker answers "where did this specific box spend its time?" -- expensive to record for every box, so it is sampled or kept only briefly, but priceless when one shipment is late. The readiness board answers "should this berth receive traffic right now?" -- a simple yes or no a dispatcher can act on without understanding the details. Ask the dashboard where one container is and it cannot say; ask the tracker whether the port is healthy overall and it drowns you in detail.

What makes the tracker powerful is that every handoff writes a timestamped scan under the same container number, so the box's journey reads as an ordered series of legs, each with a start and a duration -- 88 minutes on the quay, six hours in the yard. A late shipment is diagnosed in seconds: you see which single leg swallowed the time. The digital form is a trace: one request carries a trace id, and each unit of work it triggers -- a database query, a cache lookup, a call to another service -- is a span with its own start and duration, all stitched under that id, so a slow request shows you exactly which span was slow.

The failure that guts the operations center is trusting the aggregate dashboard alone and wiring the readiness board to nothing real. The dashboard shows healthy average throughput all week, so no one worries -- while a single refrigerated container sits forgotten in a far yard block for three days, its spoilage invisible because one lost box barely moves an average taken over thousands. Meanwhile a berth's readiness light was long ago taped to green because the sensor was "flaky," so ships keep being sent to a berth whose crane is dead, and each only learns the truth after it has tied up. The port had numbers and lights and still could not see the one late box or the one dead berth -- exactly what happens when metrics carry no per-request tracing to expose outliers and a health check reports OK no matter the real state.


Syntax or Core Structure

Metrics, logs, and traces are the three pillars of observability, and the discipline is to reach for the right one. Each answers a different question at a different cost.

SignalAnswersTypical cost
Metrics"Is it broken, and since when?"Cheap: pre-aggregated, low cardinality
Logs"What exactly happened in this request?"Moderate: grows with traffic
Traces"Which step made this request slow?"Higher: usually sampled

The Prometheus model of metrics is delightfully simple: your app exposes a /metrics endpoint that renders its current numbers as plain text, and a scraper reads that endpoint on an interval and stores the values over time. A counter is a number that only ever goes up (requests served, errors seen); the scraper computes rates from successive reads. Here we keep the counters in a plain dict and render them by hand, so the mechanics are visible and the output is deterministic.

from flask import Flask, Response, request, jsonify

app = Flask(__name__)
METRICS = {"http_requests_total": 0, "errors_total": 0}


@app.before_request
def count():
    if request.path != "/metrics":          # do not count the scrape itself
        METRICS["http_requests_total"] += 1


@app.get("/hello")
def hello():
    return jsonify(msg="hi")


@app.get("/metrics")
def metrics():
    lines = []
    for name, value in METRICS.items():
        lines.append("# TYPE " + name + " counter")
        lines.append(name + " " + str(value))
    return Response("\n".join(lines) + "\n", mimetype="text/plain")


client = app.test_client()
client.get("/hello")
client.get("/hello")
print(client.get("/metrics").get_data(as_text=True), end="")

Output:

# TYPE http_requests_total counter
http_requests_total 2
# TYPE errors_total counter
errors_total 0

Two /hello calls incremented the counter to 2, and the scrape of /metrics did not count itself because we excluded that path. A real scraper hitting this endpoint every fifteen seconds would see the number climb, and Prometheus would derive "requests per second" from the difference between reads -- you store the raw total, the query engine computes the rate.


Technical Depth: Metric Types, Labels, and Spans

The metric types

Prometheus has a small vocabulary of metric types, and picking the right one is most of the skill. A counter and a gauge look similar but mean opposite things: reading a counter of 5 tells you nothing without a second read, while reading a gauge of 5 is meaningful on its own.

TypeMeaningExampleMovement
CounterMonotonic total that only rises (resets to 0 on restart)requests_total, errors_totalUp only
GaugeA point-in-time value that rises and fallsin-flight requests, queue depthUp and down
HistogramObservations sorted into cumulative bucketsrequest latency bucketsBucketed
SummaryClient-side quantiles of observationsp95 latencyQuantiles

Counters, gauges, and labels

A single number per metric is rarely enough; you want to slice it by dimension -- per route, per status code, per method. Prometheus does this with labels, which turn one metric name into a family of time series. The trap is cardinality: each distinct combination of label values is a separate stored series, so labelling by something unbounded (a user id, a raw URL with ids in it) can explode into millions of series and overwhelm the store. Label by bounded things -- route templates and status codes -- never by identity.

from flask import Flask, request, jsonify, abort

app = Flask(__name__)
counts = {}


@app.after_request
def record(resp):
    key = (request.path, resp.status_code)
    counts[key] = counts.get(key, 0) + 1
    return resp


@app.get("/a")
def a():
    return jsonify(ok=True)


@app.get("/b")
def b():
    abort(404)


c = app.test_client()
c.get("/a")
c.get("/a")
c.get("/b")
for (path, status), n in sorted(counts.items()):
    print('http_requests_total{path="' + path + '",status="' + str(status) + '"} ' + str(n))

Output:

http_requests_total{path="/a",status="200"} 2
http_requests_total{path="/b",status="404"} 1

One metric name, two series, split by the path and status labels. Note that the after_request hook recorded the 404 from abort(404) too, because Flask turns the abort into a real response that still flows through after_request. In production you would label by the route rule (/order/<int:oid>) rather than the concrete path (/order/7), so that a million distinct order ids collapse into one series instead of a million.


Tracing one request across spans

A trace follows a single request through every unit of work it triggers. Each unit is a span with a start time and a duration, and every span shares one trace id, so the request reads as a tree of timed legs. Below we model a tracer with an integer clock (no wall-clock, so the output is exact) and a context manager that records each span's duration on exit -- exactly how real tracing libraries wrap a block of work.

clock = {"t": 0}


def now():
    return clock["t"]


spans = []


class Span:
    def __init__(self, name, trace_id):
        self.name = name
        self.trace_id = trace_id
        self.start = now()

    def __enter__(self):
        return self

    def __exit__(self, *a):
        spans.append((self.trace_id, self.name, now() - self.start))


clock["t"] = 100
with Span("GET /checkout", "t-1"):
    clock["t"] += 5                 # view setup work
    with Span("db.query", "t-1"):
        clock["t"] += 8
    with Span("cache.get", "t-1"):
        clock["t"] += 2
    clock["t"] += 1                 # serialise the response

for tid, name, dur in spans:
    print(tid, name, str(dur) + "ms")

Output:

t-1 db.query 8ms
t-1 cache.get 2ms
t-1 GET /checkout 16ms

The child spans close first and record their own durations (8ms, 2ms); the parent GET /checkout span closes last and its 16ms covers the whole request -- the two children plus the 6ms of its own setup and serialisation. All three carry trace id t-1, so a tracing backend can draw them as one waterfall and you can see at a glance that db.query dominated. That is the question a trace answers and a metric cannot: which step was slow, for this request.

Instrumenting in production (illustrative)

You would not hand-roll any of this. In production you use prometheus-client to expose real metric objects and generate_latest to render the exposition format, and a tracing library like OpenTelemetry to create spans automatically for every request and outbound call. The two snippets below are illustrative -- they need packages that are not installed here -- but they show the shape of the real thing.

# metrics.py -- prometheus_client instrumentation (illustrative; needs prometheus-client)
from prometheus_client import Counter, Histogram, generate_latest
from flask import Flask, Response

app = Flask(__name__)
REQUESTS = Counter("http_requests_total", "Total HTTP requests", ["method", "path", "status"])
LATENCY = Histogram("http_request_seconds", "Request latency", ["path"])


@app.get("/metrics")
def metrics():
    return Response(generate_latest(), mimetype="text/plain")
# tracing.py -- OpenTelemetry auto-instrumentation (illustrative; needs opentelemetry packages)
from opentelemetry import trace
from opentelemetry.instrumentation.flask import FlaskInstrumentor

FlaskInstrumentor().instrument_app(app)      # every request now starts a span
tracer = trace.get_tracer(__name__)


@app.get("/checkout")
def checkout():
    with tracer.start_as_current_span("db.query"):
        rows = run_query()                    # child span, timed automatically
    return {"ok": True}

With metrics for the aggregate view, traces for the per-request view, and the health checks we turn to next, you have the full operations center: the dashboards, the container tracker, and the readiness board.


Real World Example: Liveness, Readiness, and a Probe on the Wrong Endpoint

A load balancer or an orchestrator like Kubernetes decides whether to send an instance traffic by polling a health endpoint. The subtlety is that there are two different questions: "is this process alive at all?" (liveness -- if not, restart it) and "can this process serve requests right now?" (readiness -- if not, stop sending traffic but do not restart). The app below exposes both, plus a real endpoint that needs the database, and then we knock the database out to see what each reports.

from flask import Flask, jsonify

app = Flask(__name__)
deps = {"db_up": True}


@app.get("/healthz")                 # liveness: is the process running at all?
def healthz():
    return jsonify(status="ok")      # always 200 -- says nothing about deps


@app.get("/readyz")                  # readiness: can we actually serve traffic?
def readyz():
    if not deps["db_up"]:
        return jsonify(status="degraded", db=False), 503
    return jsonify(status="ready", db=True)


@app.get("/order/<int:oid>")
def get_order(oid):
    if not deps["db_up"]:
        return jsonify(error="db unavailable"), 500
    return jsonify(id=oid, total=42)


client = app.test_client()
deps["db_up"] = False                # the database goes down
print("healthz:", client.get("/healthz").status_code)   # LB probe -> still 200
print("readyz :", client.get("/readyz").status_code)    # true state -> 503
print("order  :", client.get("/order/7").status_code)   # real traffic -> 500

Output:

healthz: 200
readyz : 503
order  : 500

With the database down, the three endpoints disagree -- exactly as they should. /healthz returns 200 because the process itself is fine; nothing is wrong with the Python. /readyz returns 503 because it actually checks the database and finds it gone. And a genuine request, /order/7, returns 500 because it truly cannot do its job. Three endpoints, three different truths.

Each status is meant to drive a different automated decision. A 503 from /readyz should make the load balancer quietly stop routing new traffic to this instance -- drain it -- while leaving the process running, because a database outage is not fixed by restarting the web server. A failing liveness probe, by contrast, means the process is wedged and should be killed and replaced. Conflating the two is how a transient dependency blip turns into a restart storm.

Notice that /readyz performs a real dependency check, which is what makes it useful. A good readiness probe verifies the things a request actually needs -- the database, a cache, a downstream service -- but it must stay cheap and fast, because it runs every few seconds on every instance. The temptation to make it exhaustive collides with reality: a slow probe under load can itself time out and eject a perfectly healthy instance, so keep it a shallow, bounded check with a short timeout.

The design flaw is the one that bites in production: the traffic probe is pointed at /healthz. Because /healthz returns 200 whatever the state of the database -- it only proves the Python is running -- the load balancer keeps this instance in rotation while every real request 500s, and users see errors that no dashboard flagged as an instance being unhealthy. The truthful signal exists at /readyz, but nothing is wired to it; the readiness light was effectively taped to green. The fix is to point the traffic probe at /readyz (the endpoint that checks dependencies), reserve /healthz for the restart decision, and let a dependency failure drain traffic rather than trigger restarts. A health check that can never fail is not a health check -- it is the port's taped-over sensor, still reporting a berth ready long after the crane has died.


Common Mistakes

  1. Labelling metrics with unbounded values. Putting a user id, order id, or raw URL into a label creates a new stored time series for every distinct value, which explodes cardinality and can take down your metrics store. Label only by bounded dimensions like route rule and status code.
  1. Choosing the wrong metric type. A counter models a total that only rises; using one for a value that also falls (queue depth, in-flight requests) is meaningless. Those are gauges. Reading a counter without a second read tells you nothing.
  1. Exposing /metrics to the public internet. The endpoint reveals internal structure, route names, and volumes. Keep it on an internal interface or behind authentication; it is for your scraper, not your users.
  1. Making the readiness probe expensive. A probe that runs a heavy query every few seconds becomes load in its own right, and under stress it times out and ejects healthy instances. Keep it shallow and bounded.
  1. Health checks that always return 200. A check that cannot fail tells the load balancer nothing. If the endpoint does not actually verify the dependencies a request needs, it will happily keep a broken instance in rotation.
  1. Restarting on a dependency failure. If the liveness probe checks the database, a brief database blip makes the orchestrator kill and restart every instance at once -- a self-inflicted outage. Dependency failures belong to readiness, not liveness.
  1. Averaging latency instead of using percentiles. A mean hides the tail: p50 can look healthy while p99 is dreadful and a slice of users suffers. Record a histogram and alert on p95/p99.
  1. Tracing every request at full sampling. Traces are the expensive signal; recording 100% in production drowns the backend and the bill. Sample a fraction, but always keep traces for errors and slow requests.
  1. Treating the three signals as interchangeable. Trying to find why a request was slow from a metric, or whether the service is up from raw logs, fights each tool's shape. Metrics aggregate, traces localise, logs detail -- reach for the one that fits the question.

Best Practices

  • Instrument with a real client library. Expose /metrics via prometheus-client rather than hand-rolling counters; you get correct types, escaping, and the exposition format for free, and the hand-rolled dict was only ever a teaching device.
  • Label by bounded dimensions. Method, route rule, and status code make useful, low-cardinality labels. Identity (user, order, raw path) does not -- collapse ids into the route template so /order/7 and /order/8 share one series.
  • Use histograms for latency and query percentiles. Record durations into a histogram and alert on p95 or p99, not the mean, so the slow tail that users actually feel is visible.
  • Separate liveness from readiness. Wire the traffic and load-balancer probe to a readiness endpoint that checks dependencies, and the restart decision to a liveness endpoint that only proves the process runs. They drive opposite actions.
  • Keep health checks shallow, fast, and time-boxed. Verify only what a request genuinely needs, with a short timeout, so the probe never becomes the thing that takes you down under load.
  • Propagate a trace id across boundaries. Pass the id in a header to every downstream call so one trace spans services, and reuse it as the log correlation id from the previous lesson to tie all three signals together.
  • Sample traces, but never sample errors. Keep a small fraction of normal traffic to bound cost, and force-keep traces for failed and slow requests -- those are the ones you will actually open.
  • Alert on symptoms, define SLOs. Page on what users experience -- error rate and latency budget burn -- rather than on every internal gauge, so alerts mean "someone is hurting," not "a number moved."

Practice Exercises

  1. Extend the Syntax metrics app with an errors_total counter that increments in an after_request whenever the status code is >= 500. Add a route that raises, call it once, and show that the /metrics output now reports errors_total 1 while http_requests_total reflects every non-metrics request.
  1. Rework the labelled counter so it labels by the route rule (request.url_rule.rule) instead of the concrete path. Register /order/<int:oid>, call it with two different ids, and prove the output is a single series with count 2 rather than two separate series.
  1. Add a second child span (serialize) to the tracer and assert that the parent span's duration equals the sum of all child durations plus the parent's own recorded overhead, using the integer clock so the arithmetic is exact.
  1. Fix the health-check flaw. Write a test that flips deps["db_up"] to False, then asserts /readyz returns 503 (traffic should drain) while /healthz stays 200 (do not restart). State in a comment which probe the load balancer should be configured to poll and why.