Skip to content
Search

Last updated

PHP metrics with OpenTelemetry: counters, histograms and cardinality

Let's say the nightly import of orders works, and now somebody asks two questions. How many orders did we import per country last night? And how long does it take to save one?

Doesn't look like a complicated task, right?

Count things in PHP with a log line

The first idea is always a log line for every order.

<?php

declare(strict_types=1);

foreach (['PL' => [12, 18, 15], 'US' => [22, 140], 'DE' => [9]] as $country => $timings) {
    foreach ($timings as $milliseconds) {
        echo "order saved country={$country} duration={$milliseconds}ms\n";
    }
}
order saved country=PL duration=12ms
order saved country=PL duration=18ms
order saved country=PL duration=15ms
order saved country=US duration=22ms
order saved country=US duration=140ms
order saved country=DE duration=9ms

It works, and the answer to both questions is in there somewhere.

Why log lines are not metrics

To get "three orders from Poland" we have to read every line and count. With six orders that's fine. With a million orders a night it's a million lines that somebody stores, parses and pays for, only to get a few numbers.

A metric is the number itself. The script adds to it while it runs, and at the end it sends one value per country, not one line per order. OpenTelemetry has four kinds of them:

Instrument What it holds Example
Counter A number that only grows Orders imported
Up-down counter A number that grows and shrinks Messages in a queue
Gauge The value right now Memory in use
Histogram How many values fell into each range Time to save one order

Count and time things with OpenTelemetry metrics

flow-php/telemetry is an independent implementation of OpenTelemetry, written in PHP. It needs PHP 8.3 or newer, no extension, and it is not a wrapper around the official SDK.

composer require flow-php/telemetry flow-php/etl
<?php

declare(strict_types=1);

use function Flow\ETL\DSL\clock;
use function Flow\Telemetry\DSL\{console_exporter, memory_metric_processor, meter_provider, resource, telemetry};

require __DIR__ . '/vendor/autoload.php';

$telemetry = telemetry(
    resource(['service.name' => 'nightly-import']),
    meterProvider: meter_provider(memory_metric_processor(console_exporter(colors: false)), clock()),
);

$meter = $telemetry->meter('import');

$processed = $meter->createCounter('orders.processed', 'orders', 'Orders saved by the import');
$duration = $meter->createHistogram('orders.save.duration', 'ms', 'Time to save one order');

foreach (['PL' => [12, 18, 15], 'US' => [22, 140], 'DE' => [9]] as $country => $timings) {
    foreach ($timings as $milliseconds) {
        $processed->add(1, ['country' => $country]);
        $duration->record($milliseconds, ['country' => $country]);
    }
}

$telemetry->flush();

The output, with the long histogram lines cut:

| ^ orders.processed      3       [orders]  // Orders saved by the import  {country=PL}
| ^ orders.processed      2       [orders]  // Orders saved by the import  {country=US}
| ^ orders.processed      1       [orders]  // Orders saved by the import  {country=DE}
| # orders.save.duration  45.00   [ms]  // Time to save one order  {country=PL, histogram.count=3, histogram.sum=45, histogram.min=12, histogram.max=18, ...
| # orders.save.duration  162.00  [ms]  // Time to save one order  {country=US, histogram.count=2, histogram.sum=162, histogram.min=22, histogram.max=140, ...
| # orders.save.duration  9.00    [ms]  // Time to save one order  {country=DE, histogram.count=1, histogram.sum=9, histogram.min=9, histogram.max=9, ...

Six orders became six numbers, and a million orders would become the same six.

The counter answers the first question: three, two and one. The histogram answers the second one. For every country it keeps the count, the sum, the smallest and the biggest value, and how many values fell into each range. A slow save of 140ms in the US is visible as max=140, and an average would hide it.

flush sends what the script collected. console_exporter prints it, and it's the only line that changes when the numbers go to a real tool.

Why a metric with an id in it explodes

Every different set of attributes is its own number. Three countries are three numbers. That's the whole idea, and it's also the trap.

Let's say we add the order id, to find a single order later.

<?php

declare(strict_types=1);

use function Flow\ETL\DSL\clock;
use function Flow\Telemetry\DSL\{
    console_exporter,
    memory_metric_processor,
    meter_provider,
    metric_limits,
    resource,
    telemetry,
};

require __DIR__ . '/vendor/autoload.php';

$telemetry = telemetry(
    resource(['service.name' => 'nightly-import']),
    meterProvider: meter_provider(
        memory_metric_processor(console_exporter(colors: false)),
        clock(),
        limits: metric_limits(cardinalityLimit: 3),
    ),
);

$processed = $telemetry->meter('import')->createCounter('orders.processed', 'orders');

for ($orderId = 1; $orderId <= 500; $orderId++) {
    $processed->add(1, ['order.id' => $orderId]);
}

$telemetry->flush();
+-------------------------------------------------------------+
| METRICS                                                     |
+-------------------------------------------------------------+
| Resource:                                                   |
|   service.name = nightly-import                             |
| Scope: import unknown                                       |
+-------------------------------------------------------------+
| ^ orders.processed  1    [orders]  {order.id=1}             |
| ^ orders.processed  1    [orders]  {order.id=2}             |
| ^ orders.processed  1    [orders]  {order.id=3}             |
| ^ orders.processed  497  [orders]  {otel.metric.overflow=1} |
+-------------------------------------------------------------+

Five hundred ids would be five hundred numbers, each of them 1. That's the log line again, only more expensive: a monitoring tool stores every one of them as its own series.

The number of different attribute sets of one metric is its cardinality. metric_limits sets how many one instrument can have. We set three to see it happen, and the default is 2000. Past the limit nothing is lost: the other 497 orders are counted in one number with otel.metric.overflow. The total is still 500.

Which attributes to put on a metric

  • Values from a short, fixed list: a country, a status, a queue name, an HTTP method.
  • Never an id, an email, a full URL or a timestamp. Those belong to a span or a log line.
  • If a metric shows otel.metric.overflow, it has an attribute with too many values. Remove the attribute, don't raise the limit.

Where to go from here

The console is for our machine. On a server the same numbers go to a collector or a monitoring tool over OTLP, the protocol of OpenTelemetry. Only the exporter changes, and it comes from flow-php/telemetry-otlp-bridge.

The guide about tracing in PHP shows the other half: where the time of one run goes.

Found a typo or an outdated section? Edit this guide on GitHub

scroll back to top