Skip to main content

Data and monitoring · Advanced · 30 min

Send OpenTelemetry metrics to Prometheus with native OTLP

By Padding · Updated 27 Nov 2026
Ubuntu 26.04 · Python 3.14 · opentelemetry-sdk 1.45.2 · Prometheus 3.16.0 · OpenTelemetry Collector contrib 0.166.0

You will push OpenTelemetry metrics from a Python app into Prometheus 3.16's built-in OTLP receiver, directly and through the Collector, and query them back with the right names, labels and temporality.

On this page

The Prometheus client library gives you a page of metrics for Prometheus to scrape. OpenTelemetry works the other way round: the app's SDK pushes metrics over OTLP, the OpenTelemetry protocol, to whatever backend you point it at. Prometheus can be that backend. It has an OTLP receiver built in (experimental from 2.47, an ordinary flag since 3.0), so an app instrumented with OpenTelemetry can send metrics to it with no exporter, sidecar or scrape job.

The receiver is not a drop-in pipe, though. OpenTelemetry and Prometheus disagree about names, about where attributes such as the service version live, and about how counters report their values. In this tutorial you send the same small set of metrics four times and watch what each difference does:

  • straight from a Python app, to see how names and units are translated;
  • again, after promoting chosen resource attributes to labels;
  • with delta temporality, which Prometheus rejects by default;
  • through the OpenTelemetry Collector, which converts delta to cumulative before Prometheus sees it.

At the end you compare push with the classic scrape, so you can choose per service. Everything runs on one machine, in a folder you delete at the end.

Step 1 · Download Prometheus and set up the demo folder

In your third terminal, install the tools, make a demo folder and download Prometheus 3.16.0 for your CPU. The checksum check catches a damaged download. Later steps use ARCH, so stay in this terminal for commands:

Bash
sudo apt update
sudo apt install -y python3-venv curl jq tar
mkdir -p ~/otlp-demo
cd ~/otlp-demo
PROM_VERSION=3.16.0
ARCH="$(dpkg --print-architecture)"
BASE="https://github.com/prometheus/prometheus/releases/download/v${PROM_VERSION}"
curl -fsSLO "${BASE}/prometheus-${PROM_VERSION}.linux-${ARCH}.tar.gz"
curl -fsSL -o prometheus-sha256sums.txt "${BASE}/sha256sums.txt"
sha256sum --ignore-missing -c prometheus-sha256sums.txt
tar -xzf "prometheus-${PROM_VERSION}.linux-${ARCH}.tar.gz"
mv "prometheus-${PROM_VERSION}.linux-${ARCH}" prometheus

This copy of Prometheus lives in ~/otlp-demo and listens on port 9095, so it does not clash with a Prometheus service you may already run on 9090. A hand-downloaded binary gets no apt updates; for a long-lived install, follow the service and upgrade steps in the Prometheus and Node Exporter tutorial.

Check it worked

Bash
prometheus/prometheus --version | head -n 1

sha256sum printed the archive name followed by OK, and this line starts with prometheus, version 3.16.0.

Step 2 · Turn on the OTLP receiver

The receiver is off by default. One command-line flag, --web.enable-otlp-receiver, turns it on, and the configuration file gains two sections that matter for pushed data. Write the file:

Bash
cat > prometheus.yml <<'YAML'
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["127.0.0.1:9095"]

storage:
  tsdb:
    out_of_order_time_window: 30m

otlp:
  translation_strategy: UnderscoreEscapingWithSuffixes
YAML
prometheus/promtool check config prometheus.yml
  • out_of_order_time_window lets Prometheus accept samples that arrive a little late or out of order. With scraping, Prometheus sets the timestamps itself. With push, each sender stamps its own data, and a retry after a network hiccup or a Collector in between can deliver an older sample after a newer one. Without the window those samples are rejected. Thirty minutes is the value the Prometheus OpenTelemetry guide suggests as a start.
  • translation_strategy decides how OpenTelemetry names become Prometheus names. UnderscoreEscapingWithSuffixes is the default; it is written out here so you can see it. The next step shows what it does.

promtool prints SUCCESS: prometheus.yml is valid prometheus config file syntax. Start Prometheus in your first terminal and leave it running:

Bash
cd ~/otlp-demo
prometheus/prometheus --config.file=prometheus.yml --storage.tsdb.path=data \
  --web.listen-address=127.0.0.1:9095 --web.enable-otlp-receiver

The receiver has no authentication. Anyone who can reach the port can write any metric they like, which is why Prometheus listens on 127.0.0.1 here. When apps on other machines need to push, put the Collector or a reverse proxy with authentication in front of it rather than opening the port.

Check it worked

In your third terminal, ask Prometheus which flags it is running with:

Bash
cd ~/otlp-demo
curl -s http://127.0.0.1:9095/api/v1/status/flags | jq -r '.data."web.enable-otlp-receiver"'

The answer is true. OTLP over HTTP now has an address: http://127.0.0.1:9095/api/v1/otlp/v1/metrics.

Step 3 · Write a Python app that pushes metrics

Create a virtual environment with the OpenTelemetry SDK and its OTLP over HTTP exporter, pinned to 1.45.2:

Bash
python3 -m venv .venv
.venv/bin/pip install "opentelemetry-sdk==1.45.2" "opentelemetry-exporter-otlp-proto-http==1.45.2"

The app is a checkout worker cut down to its metrics. It records three instruments, each a different kind:

  • shop.orders, a counter of orders, with a payment.method attribute;
  • shop.checkout.duration, a histogram of checkout times in seconds;
  • shop.baskets.open, an up-down counter of baskets not yet paid for.

It uses a fixed list of six orders instead of real traffic, so the numbers you query back are known in advance. The attributes that describe the process as a whole, such as the service name and version, go on the resource, not on each measurement. The instance ID comes from the command line, so that every run in this tutorial appears as its own instance. Create shop.py:

Bash
cat > shop.py <<'PY'
import sys

from opentelemetry import metrics
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource

resource = Resource.create(
    {
        "service.name": "checkout",
        "service.namespace": "shop",
        "service.instance.id": sys.argv[1],
        "service.version": "1.4.0",
        "deployment.environment.name": "staging",
    }
)
reader = PeriodicExportingMetricReader(OTLPMetricExporter())
provider = MeterProvider(resource=resource, metric_readers=[reader])
metrics.set_meter_provider(provider)
meter = metrics.get_meter("shop.checkout")

orders = meter.create_counter("shop.orders", unit="{order}", description="Orders placed.")
duration = meter.create_histogram(
    "shop.checkout.duration",
    unit="s",
    description="Time taken to complete a checkout.",
    explicit_bucket_boundaries_advisory=[0.1, 0.25, 0.5, 1.0],
)
baskets = meter.create_up_down_counter(
    "shop.baskets.open", unit="{basket}", description="Baskets not yet paid for."
)

# (payment method, checkout time in seconds) for six orders
ORDERS = [
    ("mobile_money", 0.18),
    ("card", 0.32),
    ("mobile_money", 0.09),
    ("mobile_money", 0.41),
    ("card", 0.27),
    ("mobile_money", 0.12),
]

baskets.add(8)
for method, seconds in ORDERS:
    orders.add(1, {"payment.method": method})
    duration.record(seconds, {"payment.method": method})
    baskets.add(-1)

provider.shutdown()  # sends what is left before the process exits
print(f"sent {len(ORDERS)} orders as {sys.argv[1]}")
PY

Some notes on the code:

  • OTLPMetricExporter() takes its address from OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, so the same code can push to Prometheus now and to the Collector later. That variable is used exactly as written, so it holds the full path ending in /v1/metrics.
  • PeriodicExportingMetricReader pushes every 60 seconds by default. OTEL_METRIC_EXPORT_INTERVAL changes that, in milliseconds. Each push costs a request, so a phone or a small office on prepaid data pays for a short interval; a long-running service on a server is usually fine at 15 to 60 seconds.
  • explicit_bucket_boundaries_advisory sets histogram buckets that suit checkout times. The SDK's default buckets run from 0 to 10,000 and suit milliseconds, not seconds.
  • provider.shutdown() makes a final export. Without it a short script would exit before its first push.
  • mobile_money stands in for the mobile wallet payments that are a large share of checkouts in many African markets. Attribute values like this have a short, fixed list; never put order or customer IDs in attributes, because each value becomes a separate series in Prometheus.

Check it worked

Bash
.venv/bin/python -c "from importlib.metadata import version; print(version('opentelemetry-sdk'), version('opentelemetry-exporter-otlp-proto-http'))"

The command prints 1.45.2 1.45.2.

Step 4 · Push straight to Prometheus and read the translated names

Run the app once as instance checkout-1, pushing to the receiver:

Bash
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://127.0.0.1:9095/api/v1/otlp/v1/metrics \
OTEL_METRIC_EXPORT_INTERVAL=5000 \
  .venv/bin/python shop.py checkout-1

It prints sent 6 orders as checkout-1. Now list the metric names Prometheus holds that start with shop_:

Bash
curl -s http://127.0.0.1:9095/api/v1/label/__name__/values | jq -r '.data[]' | grep '^shop_'

You get five names:

Text
shop_baskets_open
shop_checkout_duration_seconds_bucket
shop_checkout_duration_seconds_count
shop_checkout_duration_seconds_sum
shop_orders_total

Each name follows a rule of the default translation strategy:

  • Dots become underscores, because classic Prometheus names allow only letters, digits, underscores and colons. Attribute names are treated the same way: payment.method becomes the label payment_method.
  • A monotonic counter gets _total, as Prometheus expects of counters.
  • The unit becomes a suffix: s turns into _seconds. Units in curly braces, such as {order} and {basket}, are annotations for people and are dropped.
  • An up-down counter can go down, so Prometheus stores it as a gauge, with no _total.
  • A histogram becomes the familiar _bucket, _count and _sum series.

The other strategies change this. NoUTF8EscapingWithSuffixes keeps the dots, since Prometheus 3 supports UTF-8 names, but every query then has to quote them, as in {"shop.orders_total"}. Dashboards and alerts written for one strategy break under another, so choose once, before you build on the names.

Two labels come from the resource. job is service.namespace and service.name joined with a slash, and instance is service.instance.id:

Bash
curl -s http://127.0.0.1:9095/api/v1/query \
  --data-urlencode 'query=shop_orders_total{instance="checkout-1"}' \
  | jq -r '.data.result[] | "\(.metric.job) \(.metric.instance) \(.metric.payment_method) \(.value[1])"' | sort

Check it worked

The counts match the six orders in the script:

Text
shop/checkout checkout-1 card 2
shop/checkout checkout-1 mobile_money 4

Check one histogram bucket too. Three of the checkouts took 0.25 seconds or less:

Bash
curl -s http://127.0.0.1:9095/api/v1/query \
  --data-urlencode 'query=sum(shop_checkout_duration_seconds_bucket{instance="checkout-1", le="0.25"})' \
  | jq -r '.data.result[0].value[1]'

The answer is 3. If a query returns nothing, check the Prometheus terminal for errors and confirm the endpoint in the command ends in /api/v1/otlp/v1/metrics.

Step 5 · Promote resource attributes to labels

The service version and environment are not on shop_orders_total. Prometheus puts the rest of the resource on a separate series called target_info, one per instance:

Bash
curl -s http://127.0.0.1:9095/api/v1/query \
  --data-urlencode 'query=target_info{instance="checkout-1"}' \
  | jq '.data.result[0].metric'

You see labels including deployment_environment_name: "staging", service_version: "1.4.0", job, instance and the telemetry_sdk_* labels the SDK adds for itself.

Keeping them apart saves storage, but every query that needs the version has to join on job and instance:

Bash
curl -s http://127.0.0.1:9095/api/v1/query \
  --data-urlencode 'query=sum by (service_version, payment_method) (shop_orders_total{instance="checkout-1"} * on (job, instance) group_left (service_version) target_info)' \
  | jq -r '.data.result[] | "\(.metric.service_version) \(.metric.payment_method) \(.value[1])"' | sort

That prints 1.4.0 card 2 and 1.4.0 mobile_money 4. For the one or two attributes you filter on all the time, promote them instead, so they are copied onto every series. Pick attributes with few values: the version and the environment are good choices, a pod name that changes on every deploy is not. Replace the configuration:

Bash
cat > prometheus.yml <<'YAML'
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["127.0.0.1:9095"]

storage:
  tsdb:
    out_of_order_time_window: 30m

otlp:
  translation_strategy: UnderscoreEscapingWithSuffixes
  promote_resource_attributes:
    - service.version
    - deployment.environment.name
YAML
prometheus/promtool check config prometheus.yml

Stop Prometheus with Ctrl+C in the first terminal and start it again with the same command. The data folder keeps what it has collected.

Push a second run, as instance checkout-2:

Bash
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://127.0.0.1:9095/api/v1/otlp/v1/metrics \
OTEL_METRIC_EXPORT_INTERVAL=5000 \
  .venv/bin/python shop.py checkout-2

Check it worked

Filter on the version directly, with no join:

Bash
curl -s http://127.0.0.1:9095/api/v1/query \
  --data-urlencode 'query=sum by (instance, deployment_environment_name) (shop_orders_total{service_version="1.4.0"})' \
  | jq -r '.data.result[] | "\(.metric.instance) \(.metric.deployment_environment_name) \(.value[1])"'

Only checkout-2 staging 6 comes back. Promotion applies to data received after the change, so checkout-1's series still have no service_version label. Expect a break like this in dashboards whenever you change the promoted list.

Step 6 · See what happens to delta temporality

OpenTelemetry counters can report in two ways. Cumulative, the SDK's default, sends the running total each time: 6, then 9, then 15. Delta sends only the change since the last push: 6, then 3, then 6. Prometheus is built on cumulative counters, and rate() and increase() assume them. Some backends prefer delta, so teams often set it globally with OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE. Push a run like that, as checkout-3:

Bash
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://127.0.0.1:9095/api/v1/otlp/v1/metrics \
OTEL_METRIC_EXPORT_INTERVAL=5000 \
OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta \
  .venv/bin/python shop.py checkout-3

The script still prints its usual line, but above it the exporter logs Failed to export metrics batch code: 500, reason: Internal Server Error. Now look for the orders:

Bash
curl -s http://127.0.0.1:9095/api/v1/query \
  --data-urlencode 'query=shop_orders_total{instance="checkout-3"}' \
  | jq '.data.result | length'

Check it worked

The answer is 0. Under the delta preference the SDK still sends the up-down counter as cumulative, since a running total is the only meaningful form for it, so ask for the open baskets from the same run too:

Bash
curl -s http://127.0.0.1:9095/api/v1/query \
  --data-urlencode 'query={instance="checkout-3"}' \
  | jq '.data.result | length'

That is 0 as well: nothing from checkout-3 was stored, not even the baskets or target_info. The Prometheus terminal shows why, with an error along the lines of invalid temporality and type combination for metric "shop.orders", and the same for shop.checkout.duration. By default Prometheus refuses delta counters and histograms instead of storing numbers that rate() would misread, and it refuses the whole push that carries them. The app keeps running and its exit code is still 0, so the only signs are the export error in the app's log and a service missing from Prometheus. If a service sends nothing at all, check its temporality first.

You have three ways out. The simplest is to leave apps that send to Prometheus on the cumulative default. Prometheus also has an experimental feature flag, --enable-feature=otlp-deltatocumulative, that converts delta to cumulative inside Prometheus; it keeps its running totals in memory and starts from zero after a restart. The third, in the next step, is to convert in the Collector, which keeps Prometheus on stable features only.

Step 7 · Send through the Collector and convert delta there

The Collector sits between apps and backends. Here it receives OTLP from the app, converts delta to cumulative with the delta_to_cumulative processor, and forwards the result to Prometheus's receiver. Download the contrib build, which includes that processor, and check it against its published checksum:

Bash
cd ~/otlp-demo
COL_VERSION=0.166.0
ARCH="$(dpkg --print-architecture)"
FILE="otelcol-contrib_${COL_VERSION}_linux_${ARCH}.tar.gz"
BASE="https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v${COL_VERSION}"
curl -fsSLO "${BASE}/${FILE}"
curl -fsSLO "${BASE}/${FILE}.sha256"
echo "$(cat "${FILE}.sha256")  ${FILE}" | sha256sum -c
mkdir -p otelcol
tar -xzf "${FILE}" -C otelcol
otelcol/otelcol-contrib --version

The check prints the file name and OK, and the version line ends in 0.166.0. The Collector publishes one .sha256 file per archive holding the hash alone, which is why the command adds the file name before checking.

Write its configuration:

Bash
cat > collector.yaml <<'YAML'
receivers:
  otlp:
    protocols:
      http:
        endpoint: 127.0.0.1:4318

processors:
  delta_to_cumulative: {}

exporters:
  otlp_http/prometheus:
    endpoint: http://127.0.0.1:9095/api/v1/otlp

service:
  pipelines:
    metrics:
      receivers: [otlp]
      processors: [delta_to_cumulative]
      exporters: [otlp_http/prometheus]
YAML
otelcol/otelcol-contrib validate --config=collector.yaml
  • The receiver listens on 4318, the standard OTLP over HTTP port, on the loopback address only.
  • delta_to_cumulative keeps a running total per series in the Collector's memory. Like the Prometheus flag, it restarts from zero when the Collector restarts, but a Collector restart does not touch Prometheus's data.
  • The exporter's endpoint is a base address; the exporter adds /v1/metrics itself. These component names are new: older guides spell them otlphttp and deltatocumulative, which 0.166 still accepts as deprecated aliases.

validate exits without an error when the file is correct, and names the bad key or component when it is not. Start the Collector in your second terminal and leave it running:

Bash
cd ~/otlp-demo
otelcol/otelcol-contrib --config=collector.yaml

The Collector also queues and retries exports when Prometheus is briefly unreachable. Where the link from an app to central monitoring drops out, a Collector next to the app holds data through short outages. Those late deliveries are what the out-of-order window lets Prometheus accept.

Push the same delta run through the Collector, as checkout-4. Only the endpoint changes:

Bash
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://127.0.0.1:4318/v1/metrics \
OTEL_METRIC_EXPORT_INTERVAL=5000 \
OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta \
  .venv/bin/python shop.py checkout-4

Check it worked

Bash
curl -s http://127.0.0.1:9095/api/v1/query \
  --data-urlencode 'query=shop_orders_total{instance="checkout-4"}' \
  | jq -r '.data.result[] | "\(.metric.payment_method) \(.value[1])"' | sort

The orders are back: card 2 and mobile_money 4, stored as an ordinary cumulative counter with the promoted labels. Delta from the app, cumulative in Prometheus. If nothing comes back after a few seconds, read the Collector's terminal for export errors.

Step 8 · Compare push with the classic scrape

Prometheus has run one scrape job the whole time, for itself. Ask which jobs have an up series:

Bash
curl -s http://127.0.0.1:9095/api/v1/query --data-urlencode 'query=up' \
  | jq -r '.data.result[] | "\(.metric.job) \(.value[1])"'

Check it worked

Only prometheus 1 comes back. shop/checkout has sent data four times, but there is no up series for it, and that is the heart of the difference:

  • Knowing a target is down. A scraped target that stops answering gets up 0, and its series are marked stale at once. A pushing app that dies just stops sending; its last values stay visible for the five-minute lookback, then vanish. Alert on absence instead, for example absent_over_time(target_info{job="shop/checkout"}[10m]).
  • Who needs to reach whom. Scraping needs Prometheus to reach every target, which is hard for apps behind NAT, on short-lived jobs or on devices. Push needs every app to reach the receiver, so that is the one address to protect.
  • Who sets the pace. With scraping, Prometheus picks the interval and the timestamps. With push, each app does, which is why the out-of-order window matters.
  • What the app depends on. A Prometheus client library ties the app to Prometheus. The OpenTelemetry SDK lets you change the backend, or send traces and logs on the same path, by changing configuration.

A reasonable rule: keep scraping for long-running services that Prometheus can reach, and use OTLP push for code already instrumented with OpenTelemetry, short-lived jobs and anything Prometheus cannot reach.

Step 9 · Remove the demo

Stop the Collector and Prometheus with Ctrl+C in their terminals. Then delete the demo folder, which holds both downloads, the virtual environment and the collected data:

Bash
rm -rf ~/otlp-demo

Check it worked

Bash
ls ~/otlp-demo 2>/dev/null || echo "removed"

The command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.