Instrumenting Apps
RED and USE, naming, and label design
Exporters can tell you about databases and machines. Only your own code can tell you about your own business logic: how many orders failed, how long payment calls take, how deep the retry queue is. Direct instrumentation with a client library is the most valuable metric work you'll do.
What to measure: RED and USE
You can't measure everything, so start with one of two checklists.
RED, for anything that serves requests (services, APIs, queue consumers):
| Signal | Question | Metric |
|---|---|---|
| Rate | How much traffic? | http_requests_total (counter) |
| Errors | How much of it is failing? | same counter, status label |
| Duration | How long does it take? | http_request_duration_seconds (histogram) |
USE, for resources (CPU, disks, connection pools, thread pools):
| Signal | Question | Example |
|---|---|---|
| Utilisation | How busy is it? | CPU busy %, pool connections in use / max |
| Saturation | How much work is waiting? | Load average, queue length, pool wait time |
| Errors | Is it failing? | Disk I/O errors, pool timeouts |
Google's SRE book adds saturation to RED to get the "four golden
signals": latency, traffic, errors, saturation. The demo app's
http_requests_in_flight gauge is a simple saturation signal.
RED tells you whether your users are having a bad time. USE tells you why. Alert on RED (symptoms); use USE dashboards to diagnose. A CPU at 95% with every request fast is not an incident.
A walk through the demo app
prometheus/demo-app/app.py uses the official Python client. The
pattern is the same in every language: define metrics once at module
level, then update them in your code paths.
REQUESTS = Counter("http_requests", "HTTP requests handled, by route and status code.",
["method", "route", "status"])
LATENCY = Histogram("http_request_duration_seconds", "HTTP request latency.",
["method", "route"],
buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5))
IN_FLIGHT = Gauge("http_requests_in_flight", "Requests currently being served.")
ROUTES = {"/", "/api/orders", "/api/search", "/healthz"}
def do_GET(self):
route = path if path in ROUTES else "other" # bounded label values
start = time.perf_counter()
IN_FLIGHT.inc()
try:
status, body = self._handle(route)
finally:
IN_FLIGHT.dec()
LATENCY.labels("GET", route).observe(time.perf_counter() - start)
REQUESTS.labels("GET", route, str(status)).inc()Notice what it does right:
- Metrics are recorded in
finally, so failed requests are counted and timed too. Instrumenting only the happy path hides exactly the requests you care about. - The route label is bounded. Unknown paths become
"other". - Errors aren't a separate metric. They're the same counter with a
statuslabel, soerrors / totalis one selector. /metricsitself isn't instrumented, so scrapes don't count as traffic.- Duration uses a monotonic clock (
perf_counter), not wall time, which can jump.
In a real framework you'd use middleware (Flask, FastAPI, Express, Go's
promhttp.InstrumentHandler*) to get this for every route at once.
Label design
Labels are the most consequential decision in instrumentation.
Good labels are bounded and useful for slicing during an incident:
route(the template, not the URL),method,statusorstatus_classoperation(get,put,delete) on a storage clientqueue,topic,table, when there's a fixed, small number of themresult(success,timeout,rejected)
Bad labels are unbounded, high-cardinality, or redundant:
- user IDs, emails, IPs, request IDs, trace IDs, full URLs, error messages
hostnameorpod, when Prometheus already addsinstancefrom service discovery- a label whose value is constant for the process. Put it on an
_infometric instead.
Labels with no value yet don't exist yet. A counter for errors with a
reason label won't have any series until the first error happens, so
rate(errors_total[5m]) returns nothing, not 0, on a healthy
system. Dashboards show "No data" and ratios disappear. Fix it by
initialising known label combinations at startup:
ERRORS.labels(reason="timeout") with no .inc() creates the series at 0.
What else to instrument
Beyond RED for inbound requests, the metrics that pay off most:
- Every outbound call: database queries, HTTP clients, cache lookups.
Same RED pattern, labelled by dependency:
db_query_duration_seconds{query="get_order"}. - Queues and pools: depth (gauge), wait time (histogram), rejections (counter).
- Business events:
orders_placed_total,payments_failed_total{reason}. These catch bugs that leave every technical metric green. - Batch jobs: last success timestamp, duration, items processed. See the Pushgateway.
- Build info: an
_infometric with version and commit. Lets you correlate every graph with deploys.
Libraries
| Language | Library |
|---|---|
| Go | github.com/prometheus/client_golang (reference implementation) |
| Java/JVM | io.prometheus:prometheus-metrics-*, or Micrometer |
| Python | prometheus-client |
| Node.js | prom-client |
| Rust | prometheus-client |
| .NET | prometheus-net, or OpenTelemetry |
OpenTelemetry is the alternative: instrument once with the vendor-neutral OTel SDK and export to Prometheus (scrape endpoint or OTLP push, which Prometheus 3 can receive natively). For a new multi-language codebase, OTel is worth considering. The concepts in this lesson apply to both.
Lab: add a metric
- In
demo-app/app.py, add a counterorders_placed_totaland increment it next toORDER_VALUE.observe(...)in the/api/ordershandler. - Add a histogram
payment_provider_duration_secondsand time thetime.sleep(...)in that handler withwith HIST.time():. - Rebuild:
docker compose -f compose_prod.yaml up -d --build demo-app. curl -s localhost:8080/metrics | grep orders_placed.- In Prometheus:
rate(orders_placed_total[1m]). Compare it withrate(http_requests_total{route="/api/orders", status="200"}[1m]). They should match. If they don't, one of them is instrumented in the wrong place.