X

Monitoring Application Performance with OpenTelemetry Metrics

OpenTelemetry Metrics give you a way to measure application behavior over time: request volume, errors, latency, and resource use. The measurements can help you spot a change or set an alert, but collecting metrics does not optimize an application by itself. You still need to investigate the evidence, find the cause, and test a change.

This guide uses Python to show the current Metrics API and SDK workflow. For a broader introduction to metric concepts, see Checkly's OpenTelemetry Metrics overview.

What OpenTelemetry Metrics measure

OpenTelemetry metrics are one of its signals, alongside traces and logs. A metric is an aggregated measurement with a time and associated attributes. Use metrics to understand patterns across requests; use traces or logs when you need the details of an individual request. This complements the practical error monitoring and structured logging guide for small web apps.

Choose an instrument that matches the value you are recording:

Instrument Use it for Example
Counter A total that only increases Requests completed or jobs processed
UpDownCounter A value that can increase or decrease Active jobs or items waiting in a queue
Histogram A distribution of recorded values Request duration or response size
Gauge A current sampled value A current temperature or pool measurement

Use an asynchronous gauge when a value is collected by a callback, as with many process or host measurements. Do not model a value that goes up and down as a Counter, or record periodic snapshots as an UpDownCounter. See the OpenTelemetry metrics concepts and Metrics API specification for instrument details.

Set up the Python SDK

Install the API and SDK in your application's virtual environment:

pip install opentelemetry-api opentelemetry-sdk

For a local example, configure a console exporter and create a meter provider once during application startup:

from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import (
    ConsoleMetricExporter,
    PeriodicExportingMetricReader,
)
from opentelemetry.sdk.resources import SERVICE_NAME, Resource

reader = PeriodicExportingMetricReader(
    ConsoleMetricExporter(),
    export_interval_millis=10_000,
)
provider = MeterProvider(
    resource=Resource.create(attributes={SERVICE_NAME: "checkout-api"}),
    metric_readers=[reader],
)
metrics.set_meter_provider(provider)
meter = metrics.get_meter("example.checkout")

The resource identifies the service producing the measurements. Create instruments once at startup, then record measurements from application code. The OpenTelemetry Python instrumentation guide documents this setup. If your framework's OpenTelemetry instrumentation already records HTTP metrics, check what it emits before adding manual instruments so you do not count the same requests twice.

Record requests, errors, and latency

A Counter can track completed requests and server errors; a Histogram records the distribution of request durations. This helper expects the final response status and a duration measured in seconds:

request_count = meter.create_counter(
    "app.server.request.count",
    unit="{request}",
    description="Completed HTTP requests",
)
server_errors = meter.create_counter(
    "app.server.request.errors",
    unit="{request}",
    description="HTTP requests that ended with a server error",
)
request_duration = meter.create_histogram(
    "app.server.request.duration",
    unit="s",
    description="HTTP server request duration",
)

def record_completed_request(method, route, status_code, duration_seconds):
    attributes = {
        "http.request.method": method,
        "http.route": route,
        "http.response.status_code": status_code,
    }
    request_count.add(1, attributes)
    request_duration.record(duration_seconds, attributes)

    if status_code >= 500:
        server_errors.add(1, attributes)

Call the helper once from framework middleware after you know the completed response status. Measure elapsed time with a monotonic timer such as Python's time.perf_counter(). If a request raises an exception, record the outcome in the middleware's exception-handling path as well. The example treats HTTP 5xx responses as server errors; applications may also need a separate metric for failed jobs or business operations that return a successful HTTP response.

The HTTP semantic conventions define a request-duration Histogram and common attributes such as method, route template, and response status. Follow the OpenTelemetry HTTP metrics conventions when instrumenting HTTP code. A route should be a template such as /orders/{order_id}, not a raw path containing a different ID for every request.

Keep metric cardinality under control

Every distinct combination of metric attributes creates another time series or aggregation point. Avoid unbounded values such as user IDs, email addresses, request IDs, full URLs, and query strings. Prefer a small set of useful dimensions, such as a normalized route, HTTP method, and status code. These limits also reduce memory use and telemetry storage, and help avoid sending private data to a monitoring backend.

SDKs apply cardinality limits to protect applications from unbounded attribute combinations. When a limit is reached, measurements can be aggregated without their original attributes, so queries grouped by those attributes may no longer tell the whole story. Start with only dimensions you need for a decision, then review their number of possible combinations as the application grows.

Export metrics to a monitoring backend

Console output is useful while developing. For a backend that accepts OTLP, install the HTTP/protobuf exporter:

pip install opentelemetry-exporter-otlp-proto-http

Then replace the console reader with an OTLP reader that points to a running Collector or compatible backend:

from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
    OTLPMetricExporter,
)

reader = PeriodicExportingMetricReader(
    OTLPMetricExporter(endpoint="http://localhost:4318/v1/metrics")
)

The endpoint must be reachable from the application, and the receiving Collector or backend must be configured to accept OTLP on that address. In containers, localhost usually means the application container itself, not another service. The Python exporter guide shows the supported setup, and the OpenTelemetry Collector can receive, process, and route telemetry. Direct export can be enough for a small development setup; a Collector is useful when you need shared routing, retries, filtering, or multiple destinations.

Prometheus and Grafana are common choices for storing, querying, and visualizing metrics. Choose a Prometheus scrape or OTLP path supported by the versions and components you operate; the OpenTelemetry SDK does not expose the PrometheusMetricsExporter class shown in older examples. Start with the Prometheus overview and the current OpenTelemetry exporter registry rather than copying an unverified exporter snippet.

CloudWatch is another possible monitoring backend. Use an AWS-supported OpenTelemetry integration for the actual export; the old AWSMetricExporter example is not a valid general-purpose Python SDK setup. The CloudWatch introduction provides background on that service. AWS X-Ray is for traces, a separate signal from metrics.

Use metrics to guide an investigation

For a small API or web app, begin with a few questions:

  1. Is request volume changing?
  2. Are server errors increasing, and which route templates are affected?
  3. Are typical and slow requests getting slower?
  4. Is a constrained resource, such as a queue or connection pool, approaching its limit?

A Histogram preserves a distribution that can be queried for latency percentiles when the backend and aggregation are configured to support them. Do not rely on an average alone: it can hide a slow tail. Choose bucket boundaries or other aggregation settings that reflect the latency thresholds you care about, and alert on a sustained user-impacting condition rather than every brief fluctuation.

Metrics narrow down when and where to investigate; they do not explain every individual failure. Correlate a spike with traces and structured logs, then profile or test a suspected bottleneck before changing code or capacity. Never add sensitive identifiers as metric attributes just to make a chart more specific.

Cover Photo by fauxels

Categories: Development
Related Post