Learn Labs
Instrumentation & Exporters

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):

SignalQuestionMetric
RateHow much traffic?http_requests_total (counter)
ErrorsHow much of it is failing?same counter, status label
DurationHow long does it take?http_request_duration_seconds (histogram)

USE, for resources (CPU, disks, connection pools, thread pools):

SignalQuestionExample
UtilisationHow busy is it?CPU busy %, pool connections in use / max
SaturationHow much work is waiting?Load average, queue length, pool wait time
ErrorsIs 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.

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 status label, so errors / total is one selector.
  • /metrics itself 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, status or status_class
  • operation (get, put, delete) on a storage client
  • queue, topic, table, when there's a fixed, small number of them
  • result (success, timeout, rejected)

Bad labels are unbounded, high-cardinality, or redundant:

  • user IDs, emails, IPs, request IDs, trace IDs, full URLs, error messages
  • hostname or pod, when Prometheus already adds instance from service discovery
  • a label whose value is constant for the process. Put it on an _info metric instead.

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 _info metric with version and commit. Lets you correlate every graph with deploys.

Libraries

LanguageLibrary
Gogithub.com/prometheus/client_golang (reference implementation)
Java/JVMio.prometheus:prometheus-metrics-*, or Micrometer
Pythonprometheus-client
Node.jsprom-client
Rustprometheus-client
.NETprometheus-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

  1. In demo-app/app.py, add a counter orders_placed_total and increment it next to ORDER_VALUE.observe(...) in the /api/orders handler.
  2. Add a histogram payment_provider_duration_seconds and time the time.sleep(...) in that handler with with HIST.time():.
  3. Rebuild: docker compose -f compose_prod.yaml up -d --build demo-app.
  4. curl -s localhost:8080/metrics | grep orders_placed.
  5. In Prometheus: rate(orders_placed_total[1m]). Compare it with rate(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.

On this page