Instrumenting applications

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Scraping only works once something exposes a /metrics endpoint in a format Prometheus understands. This page covers the official client libraries used to instrument application code, the text-based exposition format those libraries emit (and its standardization as OpenMetrics), how a scraper and a target negotiate which of the two to speak, and the naming conventions that keep metrics and labels usable as an application grows.

Client libraries

Prometheus maintains official client libraries for Go, Java/Scala, Python, Ruby, and Rust, plus a longer list of community libraries for other languages. Each implements the same core model — registries, the four metric types, and an HTTP handler that serves the current state in the exposition format — with idioms native to its language. The full list, with install instructions per language, is Client libraries; a library not yet covered there, or one you write for an unsupported language, should follow Writing client libraries so it stays compatible with the format and conventions below.

Go (client_golang)

client_golang is the reference implementation and the library Prometheus’s own server and exporters use internally. A Counter is registered once, at startup, and incremented from request-handling code; promhttp.Handler() wires the default registry to an HTTP endpoint (the Go language is covered in the Go Reference):

package main

import (
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var httpRequestsTotal = promauto.NewCounterVec(
	prometheus.CounterOpts{
		Name: "http_requests_total",
		Help: "Total number of HTTP requests processed.",
	},
	[]string{"method", "code"},
)

func handler(w http.ResponseWriter, r *http.Request) {
	httpRequestsTotal.WithLabelValues(r.Method, "200").Inc()
	w.Write([]byte("ok"))
}

func main() {
	http.HandleFunc("/", handler)
	http.Handle("/metrics", promhttp.Handler())
	http.ListenAndServe(":8080", nil)
}
// https://prometheus.io/docs/instrumenting/clientlibs/

promauto registers the metric with the default registry as it is created, so there is no separate Register call to forget. WithLabelValues must be called with label values in the same order the label names were declared.

Java/Scala (simpleclient / client_java)

The Java ecosystem has two generations of official client: the older simpleclient modules (io.prometheus:simpleclient) and the newer client_java (io.prometheus:prometheus-metrics-core), which follows the OpenMetrics data model natively. Both register metrics against a CollectorRegistry and expose it over HTTP with a small embedded server or a servlet filter:

import io.prometheus.client.Counter;
import io.prometheus.client.exporter.HTTPServer;

public class App {
  static final Counter httpRequestsTotal = Counter.build()
      .name("http_requests_total")
      .help("Total number of HTTP requests processed.")
      .labelNames("method", "code")
      .register();

  public static void main(String[] args) throws Exception {
    HTTPServer server = new HTTPServer.Builder()
        .withPort(8080)
        .build();

    httpRequestsTotal.labels("GET", "200").inc();
  }
}
// https://prometheus.io/docs/instrumenting/clientlibs/

HTTPServer serves the default registry’s content on /metrics on the given port. Spring Boot applications typically go through Micrometer’s Prometheus registry instead of calling this library directly; that integration is out of scope for this page.

Python, Ruby, and Rust

prometheus_client (Python) and prometheus-client (Ruby) follow the same registry-and-decorator shape as the libraries above — a Counter/Gauge/Histogram/Summary object is created once and updated inline with request handling, then served via a small built-in HTTP server or WSGI/Rack middleware (for the Ruby language itself, see the Ruby Reference). The Rust client (prometheus) mirrors the same four types with an explicit Registry and a TextEncoder that a web framework’s own handler calls to produce the response body. For an axum service built with the metrics facade and metrics-exporter-prometheus instead, see Axum: Metrics & SLOs. Installation and a minimal example for each are on the client libraries page linked above; the patterns — instrument business logic directly, expose /metrics for scraping, avoid per-request metric creation — are the same across all five official languages, and are spelled out in more depth in Instrumentation. What each metric type actually means and when to reach for a Histogram versus a Summary is covered in Data Model & Metric Types and Histograms and summaries.

The running example: an instrumented Python service

Reading about a client library only goes so far, so the rest of this section uses one small, complete service as its running example: orders-api, a Python HTTP server with an /orders handler that takes a variable amount of time and fails about one request in ten, and a /health handler that always succeeds. It uses the official prometheus_client package (pip install prometheus_client) and exposes four metrics, one of each type, plus an info metric:

import random
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from prometheus_client import Counter, Gauge, Histogram, Info, Summary, start_http_server

REQUESTS = Counter(
    "http_requests",
    "Total HTTP requests processed.",
    ["method", "handler", "status"],
)
LATENCY = Histogram(
    "http_request_duration_seconds",
    "HTTP request latency in seconds.",
    ["handler"],
    buckets=(0.05, 0.1, 0.25, 0.5, 1.0, 2.5),
)
IN_PROGRESS = Gauge("orders_in_progress", "Orders currently being processed.")
PAYLOAD = Summary("order_payload_bytes", "Size of submitted order payloads.")

BUILD = Info("orders_build", "Build information about the orders service.")
BUILD.info({"version": "1.4.2", "region": "eu-west-1"})

random.seed(42)


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def do_GET(self):
        handler = "/orders" if self.path.startswith("/orders") else "/health"
        started = time.perf_counter()
        status = "200"
        IN_PROGRESS.inc()
        try:
            if handler == "/orders":
                time.sleep(random.choice([0.02, 0.04, 0.08, 0.15, 0.3, 0.6]))
                PAYLOAD.observe(random.randint(200, 4000))
                if random.random() < 0.1:
                    status = "500"
        finally:
            IN_PROGRESS.dec()
            LATENCY.labels(handler).observe(time.perf_counter() - started)
            REQUESTS.labels("GET", handler, status).inc()
        self.send_response(int(status))
        self.end_headers()
        self.wfile.write(b"ok\n")


if __name__ == "__main__":
    metrics_port = int(sys.argv[1])
    app_port = int(sys.argv[2])
    start_http_server(metrics_port)  # serves /metrics on its own port
    ThreadingHTTPServer(("0.0.0.0", app_port), Handler).serve_forever()

A few things in this listing are worth reading closely:

  • The metrics are module-level objects created once. Creating a Counter inside the request handler would raise a duplicate-registration error on the second request, and caching a child with labels(...) is only an optimisation, not a requirement.

  • The Counter is declared as http_requests, and the library appends _total itself, so the exposed name is http_requests_total. Declaring http_requests_total is accepted too; the suffix is never doubled.

  • try/finally makes sure the in-progress Gauge is decremented and the latency observed even when the handler raises.

  • start_http_server(port) runs a second, tiny HTTP server in a daemon thread that serves /metrics. Keeping metrics on their own port separates operational traffic from application traffic, which makes it simple to firewall the scrape endpoint.

  • The histogram buckets are chosen to straddle the latencies the service is expected to have (50 ms to 2.5 s), not left at the library defaults.

Run it in a virtual environment and generate some traffic, then look at what a scrape returns:

python3 -m venv venv && venv/bin/pip install prometheus_client
venv/bin/python orders_api.py 28101 28102 &     # metrics on :28101, app on :28102
for i in $(seq 1 20); do curl -s localhost:28102/orders >/dev/null; done
curl -s localhost:28101/metrics | grep -v '^# ' | grep -E 'http_requests|orders_in_progress|orders_build|order_payload'
http_requests_total{handler="/orders",method="GET",status="500"} 3.0
http_requests_total{handler="/health",method="GET",status="200"} 4.0
http_requests_total{handler="/orders",method="GET",status="200"} 12.0
http_requests_created{handler="/orders",method="GET",status="500"} 1.794317415645625e+09
orders_in_progress 1.0
orders_build_info{region="eu-west-1",version="1.4.2"} 1.0
order_payload_bytes_count 15.0
order_payload_bytes_sum 21575.0

Besides the series the code declared, the library adds a _created series per labeled child (the Unix time the child was first used, which lets a server detect resets precisely) and a set of python_* runtime metrics. On Linux it also exposes process_* metrics (CPU, memory, open file descriptors); the macOS host used to capture this output does not, which is why they are absent above. The per-type mechanics — why a Counter is queried with rate(), what the le label means — are in Data Model & Metric Types.

The convenience API for each type

Beyond inc(), set() and observe() the Python client has helpers that remove most of the bookkeeping from the handler code:

@LATENCY.labels("/orders").time()          # observes the duration of every call
def create_order(): ...

with IN_PROGRESS.track_inprogress():       # inc on entry, dec on exit, even on exceptions
    process()

LAST_SUCCESS.set_to_current_time()         # for batch jobs: "when did it last succeed"
ERRORS.labels("/orders").count_exceptions()  # increments when the wrapped block raises

The same operations exist in every official library under that language’s naming; the model does not change.

Label patterns: Info and Enum

Two recurring needs do not fit a plain Counter or Gauge, and both are solved with a Gauge-shaped pattern that the Python client wraps in a helper class:

  • Info — constant facts about a process (version, build, region). A Gauge with value 1 whose labels carry the data, such as orders_build_info{version="1.4.2",region="eu-west-1"} above. PromQL joins it onto other series with group_left (see PromQL: Operators & Aggregation).

  • Enum — a state machine with a few mutually exclusive states. One series per state, with value 1 for the current one and 0 for the rest, so an alert can say "worker has been failed for 5 minutes".

state = Enum("orders_worker_state", "State of the order worker.", states=["idle", "busy", "failed"])
state.state("busy")
orders_worker_state{orders_worker_state="idle"} 0.0
orders_worker_state{orders_worker_state="busy"} 1.0
orders_worker_state{orders_worker_state="failed"} 0.0

Unit testing instrumentation

Metrics are part of an application’s public contract, so they deserve tests. Each client library lets a test read a registry directly instead of scraping HTTP. In Python the trick is to give every test its own CollectorRegistry, so metrics from one test never leak into another, and to read samples with get_sample_value():

import unittest

from prometheus_client import CollectorRegistry, Counter, Enum, Gauge, Histogram


def make_metrics(registry):
    requests = Counter(
        "http_requests", "Total HTTP requests.", ["handler", "status"], registry=registry
    )
    latency = Histogram(
        "http_request_duration_seconds", "Latency.", buckets=(0.1, 0.5, 1.0), registry=registry
    )
    return requests, latency


class InstrumentationTest(unittest.TestCase):
    def setUp(self):
        self.registry = CollectorRegistry()
        self.requests, self.latency = make_metrics(self.registry)

    def test_counter_increments_per_label_set(self):
        self.requests.labels("/orders", "500").inc()
        self.requests.labels("/orders", "500").inc()
        value = self.registry.get_sample_value(
            "http_requests_total", {"handler": "/orders", "status": "500"}
        )
        self.assertEqual(value, 2.0)

    def test_histogram_buckets_are_cumulative(self):
        for seconds in (0.05, 0.3, 0.3, 2.0):
            self.latency.observe(seconds)
        sample = self.registry.get_sample_value
        self.assertEqual(sample("http_request_duration_seconds_bucket", {"le": "0.1"}), 1.0)
        self.assertEqual(sample("http_request_duration_seconds_bucket", {"le": "0.5"}), 3.0)
        self.assertEqual(sample("http_request_duration_seconds_bucket", {"le": "+Inf"}), 4.0)
        self.assertEqual(sample("http_request_duration_seconds_count"), 4.0)


if __name__ == "__main__":
    unittest.main(verbosity=2)
test_counter_increments_per_label_set (__main__.InstrumentationTest) ... ok
test_histogram_buckets_are_cumulative (__main__.InstrumentationTest) ... ok

Ran 2 tests in 0.001s

OK

Note that the sample name includes the _total suffix and that a histogram bucket is addressed by its le label; the test asserts the cumulative property described in the data-model page.

Reading the format programmatically

The exposition format is simple enough to parse by hand, but the client library ships a parser, which is handy in tests and in small scripts that need a number out of a /metrics page:

import urllib.request

from prometheus_client.parser import text_string_to_metric_families

body = urllib.request.urlopen("http://localhost:28101/metrics").read().decode()
for family in text_string_to_metric_families(body):
    if family.name in ("http_requests", "orders_in_progress"):
        for s in family.samples:
            print(family.type, s.name, s.labels, s.value)
counter http_requests_total {'handler': '/orders', 'method': 'GET', 'status': '200'} 1906.0
counter http_requests_total {'handler': '/health', 'method': 'GET', 'status': '200'} 676.0
counter http_requests_total {'handler': '/orders', 'method': 'GET', 'status': '500'} 196.0
gauge orders_in_progress {} 3.0

The parser reports the Counter family under the name without _total and the individual sample with it, exactly mirroring what the OpenMetrics format does (next section).

What to instrument

A common failure is instrumenting too little (nothing to debug with) or too much (thousands of unused series). Three questions cover most services (the RED and USE methods are discussed in RED, USE and Golden Signals):

flowchart LR R["Request-driven service"] --> RR["Rate: requests per second"] R --> RE["Errors: failed requests"] R --> RD["Duration: latency distribution"] J["Batch job"] --> JL["Last success time and duration"] J --> JR["Records processed"] X["Resources: queue, pool, cache"] --> XU["Utilization"] X --> XS["Saturation, such as queue length"] X --> XE["Errors"]
  • Online-serving systems (an HTTP API): requests, errors and duration, per handler. http_requests_total and http_request_duration_seconds in the example cover all three, since the Histogram’s _count is the request count and status separates errors.

  • Offline or batch systems: a Gauge with the time of the last success and one for the duration, pushed or exposed so an alert can fire when the job has not succeeded recently (see Exporters & the Pushgateway).

  • Resources — thread pools, queues, caches, connection pools: utilization, saturation (queue length) and errors.

Count failures as a separate label value (or a second Counter) rather than a separate unit, and always count both the successes and the failures, so a ratio of the two is a single division at query time. Instrument at the boundaries — the incoming request, each outgoing call to a dependency — rather than inside every function, and prefer a few well-labeled metrics to many one-off ones.

The exposition format and OpenMetrics

Whatever library produces it, /metrics returns plain text: one line per sample, plus # HELP and # TYPE comment lines that document each metric once. This is what a scraper actually parses:

curl -s http://localhost:8080/metrics
# HELP http_requests_total Total number of HTTP requests processed.
# TYPE http_requests_total counter
http_requests_total{method="GET",code="200"} 1027
http_requests_total{method="POST",code="500"} 3

# HELP process_resident_memory_bytes Resident memory size in bytes.
# TYPE process_resident_memory_bytes gauge
process_resident_memory_bytes 3.5346432e+07
# https://prometheus.io/docs/instrumenting/exposition_formats/

This line-oriented layout is Prometheus’s own text-based exposition format, defined at Exposition formats. It was later submitted to, and standardized by, the CNCF as OpenMetrics — a vendor-neutral spec for the same wire format, with a stricter grammar (for example, every counter’s name must end in _total, and an explicit # EOF line closes the payload) so that other systems can produce or consume it without depending on Prometheus itself. Every current official client library can emit either format from the same registry; which one a given scrape actually gets is decided per request, not per client, as described next.

Content negotiation

A scrape target does not hard-code which format it returns. The Prometheus server sends an Accept header on every scrape request listing the formats it is willing to receive, in preference order, and the client library’s HTTP handler picks the best match:

# Ask explicitly for the OpenMetrics text format instead of the Prometheus legacy format.
curl -s -H 'Accept: application/openmetrics-text; version=1.0.0; charset=utf-8' \
  http://localhost:8080/metrics

If no Accept header is sent, or none of the offered types are recognized, a client library falls back to its own default (the legacy Prometheus text format, for most current libraries). A real exchange with the example service shows both formats. Without an Accept header the response carries the classic type; asking for OpenMetrics changes the Content-Type, the family naming and appends an # EOF terminator:

curl -s -D - -o /dev/null http://localhost:28101/metrics | grep -i content-type
curl -s -H 'Accept: application/openmetrics-text; version=1.0.0; charset=utf-8' \
  http://localhost:28101/metrics | grep -E '^# (HELP|TYPE) http_requests|^http_requests_total'
Content-Type: text/plain; version=0.0.4; charset=utf-8

Content-Type: application/openmetrics-text; version=1.0.0; charset=utf-8; escaping=underscores
# HELP http_requests Total HTTP requests processed.
# TYPE http_requests counter
http_requests_total{handler="/orders",method="GET",status="200"} 1079.0
...

In OpenMetrics the # TYPE line names the family (http_requests) and the samples carry the _total suffix, which is also why the client library lets you declare a counter without it. The Prometheus server advertises both formats in its Accept header and weights OpenMetrics higher. Capturing the header a Prometheus 3.5 server actually sent to a dummy target gave (line breaks added):

application/openmetrics-text;version=1.0.0;escaping=allow-utf-8;q=0.6,
application/openmetrics-text;version=0.0.1;q=0.5,
text/plain;version=1.0.0;escaping=allow-utf-8;q=0.4,
text/plain;version=0.0.4;q=0.3,
*/*;q=0.2

A modern client library therefore serves OpenMetrics to Prometheus, while curl without a header still gets the classic text. The escaping parameter belongs to UTF-8 metric-name support in Prometheus 3: it tells the target how names that are not legal classic identifiers should be written.

Because both formats describe the same underlying samples, this negotiation is invisible to application code — instrumentation is written once against the client library’s API, and the wire format served for any given scrape is a detail between the Prometheus server and that library’s HTTP handler. The exact media types, parameters, and fallback rules are defined in Content negotiation.

Other ways in: bridges and OpenTelemetry

Not every system is instrumented with a Prometheus client library. Two routes exist for the rest:

  • Bridges translate another monitoring library’s counters into the Prometheus registry, for example the Micrometer registry for Spring Boot or a StatsD or Graphite bridge. The application keeps its existing instrumentation API; a bridge exposes the same values at /metrics.

  • OpenTelemetry. Prometheus 3 can receive OTLP metrics directly: starting the server with --web.enable-otlp-receiver adds the endpoint /api/v1/otlp/v1/metrics (it appears in the server’s route list), so an OpenTelemetry SDK or collector can push metrics without a Prometheus client library. OTLP resource attributes and metric names are translated into Prometheus labels and names, and the exponential histogram type maps onto native histograms. This is the push-based exception discussed in Architecture & Ecosystem; for ordinary services, scraping a library-provided /metrics endpoint remains the simpler and more robust choice.

Metric and label naming

Names are part of a metric’s public API: they get baked into dashboards, alerting rules, and other teams' PromQL queries, so getting them right at instrumentation time avoids a breaking rename later. The full guidance is Metric and label naming; the rules that matter most day to day:

  • Namespace with an underscore-separated prefix that identifies the owning system or application, e.g. http_requests_total, process_cpu_seconds_total — not a dotted or camelCase name.

  • Suffix the unit, in base units. Use _seconds (not milliseconds), _bytes (not kilobytes or megabytes), _total for a monotonically increasing count. Prometheus and PromQL assume base units throughout (rate(), histogram bucket boundaries, and so on), so a metric in non-base units silently breaks any query written against the convention.

  • Every counter ends in _total. This is required by OpenMetrics and conventional even when only emitting the legacy format; it is also how a reader distinguishes a counter (meant to be wrapped in rate()/increase()) from a gauge at a glance.

  • Put varying dimensions in labels, not in the metric name. http_requests_total{method="GET"} is one metric with a method label, not a family of http_requests_get_total, http_requests_post_total metrics — the label form is what makes aggregation across dimensions (sum by (method) (...)) possible at all.

  • Keep label cardinality bounded. Each distinct combination of label values creates a new time series, stored and indexed independently. A label drawn from a small, closed set (method, status_code, region) is safe; a label drawn from an effectively unbounded set (a raw user ID, a full request path with path parameters, a UUID, a timestamp) is not — it causes cardinality explosion, inflating memory and query latency on the server for every application that mislabels this way. Bucket or normalize high-cardinality values (a route template like /users/:id instead of /users/1042) before attaching them as a label.

These conventions apply equally to metrics defined by hand and to ones a exporter derives from some other system; they also set the vocabulary that PromQL selects against and that recording and alerting rules build on.

Continue with Exporters & the Pushgateway for instrumenting systems you cannot modify directly, or Data Model & Metric Types for the underlying Counter/Gauge/Histogram/Summary model these libraries implement.