Skip to content
Search

Last updated

OpenTelemetry Collector for PHP: keep the PHP process light

Let's say our shop sends its traces straight to a monitoring service on the other side of the internet. It works, until that service has a slow afternoon. Then every request of the shop waits for it too.

These scripts need a collector, so they run only on your machine, not in the playground.

Send traces from PHP straight to the backend

This is where most of us start: the exporter gets the address of the service.

$exporter = otlp_exporter(otlp_curl_transport(
    endpoint: 'https://otlp.example.com:4318',
    options: otlp_curl_options()->withHeader('Authorization', 'Bearer ' . $_ENV['OTLP_TOKEN']),
));

It needs nothing else to run, and that's why it's the first thing we try.

Why PHP is the wrong place for the heavy work

A PHP process lives for one request. Everything telemetry does inside it, the visitor waits for.

  • The export. A request to another continent with TLS takes time on a good day. On a bad day the request of the visitor waits for the timeout.
  • Retries. When the service is down, somebody has to keep the data and try again. A PHP process that ends in 50ms can't.
  • Batching. One request makes a few spans. A real batch needs the spans of many requests, and they live in different processes.
  • Sampling. To keep only the slow and the failed requests, somebody has to see the whole trace first. The PHP process decides at the start, when it knows nothing yet.

An OpenTelemetry Collector is a small program that runs next to PHP and never ends. It takes everything PHP sends, and it has all the time PHP doesn't have.

Send everything from PHP to a collector on the same host

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

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

declare(strict_types=1);

use function Flow\Bridge\Telemetry\OTLP\DSL\{otlp_curl_options, otlp_curl_transport, otlp_exporter};
use function Flow\ETL\DSL\clock;
use function Flow\Telemetry\DSL\{
    always_on_sampler,
    batching_span_processor,
    memory_context_storage,
    resource,
    telemetry,
    tracer_provider,
};

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

$exporter = otlp_exporter(otlp_curl_transport(
    endpoint: 'http://localhost:4318',
    options: otlp_curl_options()->withTimeout(200)->withConnectTimeout(50),
));

$telemetry = telemetry(
    resource(['service.name' => 'shop']),
    tracer_provider(
        batching_span_processor($exporter),
        clock(),
        memory_context_storage(),
        sampler: always_on_sampler(),
    ),
)->registerShutdownFunction();

$tracer = $telemetry->tracer('http');

$requests = [
    'GET /products' => 10_000,
    'GET /cart' => 15_000,
    'GET /search' => 400_000,
    'POST /checkout' => null,
];

foreach ($requests as $name => $microseconds) {
    try {
        $tracer->trace($name, static function () use ($microseconds): void {
            if ($microseconds === null) {
                throw new RuntimeException('Payment provider did not answer');
            }

            usleep($microseconds);
        });
    } catch (RuntimeException) {
    }
}

The script plays four requests: two fast ones, a slow search and a checkout that fails.

On the PHP side there is nothing clever, and that's the point:

  • The address is localhost. No TLS, no token, no trip over the internet.
  • The timeouts are 50ms to connect and 200ms for the request. A collector that doesn't answer costs a request at most that.
  • always_on_sampler keeps every span. PHP doesn't decide what is interesting.
  • The token of the monitoring service is not in the PHP application anymore. The collector has it.

Tail sampling in the OpenTelemetry Collector

Now the collector. It's one program and one file. We use the contrib build, because tail sampling is a part of it.

receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318

processors:
  memory_limiter:
    check_interval: 1s
    limit_mib: 256
  tail_sampling:
    decision_wait: 5s
    policies:
      - name: errors
        type: status_code
        status_code:
          status_codes: [ERROR]
      - name: slow
        type: latency
        latency:
          threshold_ms: 300
      - name: one-in-ten
        type: probabilistic
        probabilistic:
          sampling_percentage: 10
  batch:
    timeout: 5s
    send_batch_size: 1024

exporters:
  debug:
    verbosity: normal

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, tail_sampling, batch]
      exporters: [debug]

Run the OpenTelemetry Collector in Docker

We save that file as collector.yaml and start the collector next to it. One command is enough to try it, and the Compose service is what stays in the project.

docker run

docker run --rm -p 4318:4318 \
    -v "$PWD/collector.yaml:/etc/otelcol-contrib/config.yaml:ro" \
    otel/opentelemetry-collector-contrib:0.153.0

Docker Compose

services:
  otel-collector:
    image: otel/opentelemetry-collector-contrib:0.153.0
    volumes:
      - ./collector.yaml:/etc/otelcol-contrib/config.yaml:ro
    ports:
      - "4318:4318"

With Compose we start it with docker compose up -d and read its output with docker compose logs -f otel-collector. When PHP runs in a container of the same Compose file, the address in the script is http://otel-collector:4318, not localhost.

We run the PHP script, and a few seconds later the collector prints what it kept:

ScopeTraces #0 http
GET /search 47edec50aa6189bc6b4488c644fb4d45 1684acc2fe006947
ResourceTraces #1 service.name=shop
ScopeTraces #1 http
POST /checkout 3d76b1b2ae1695e7a0a900a179a678fc 04fd71faef9b77db error.type=RuntimeException

Four requests went in, two came out: the slow search and the failed checkout.

tail_sampling waits five seconds for all spans of a trace and then asks its three policies. A trace with an error stays. A trace longer than 300ms stays. From the rest, one in ten stays, so we still see what a normal request looks like. In this run both fast requests were dropped. In another run one of them can stay.

PHP couldn't make this choice. When GET /search started, nobody knew it would be slow.

What else moves to the collector

  • Batching and compression. batch collects the spans of all PHP processes for five seconds and sends them in one request.
  • Retries. The exporter of the collector keeps the data in a queue and tries again when the service is back. With a queue on disk it also survives a restart.
  • The address and the token. To send the data to a real service, replace debug with an otlp_http exporter. PHP doesn't change and doesn't restart.
  • Protection. memory_limiter makes the collector refuse data before it runs out of memory, so a flood of spans doesn't take the server down.

No network at all: write to a file

There is one step lighter. PHP appends the spans to a file, and the collector reads the file.

use function Flow\Bridge\Telemetry\OTLP\DSL\{otlp_exporter, otlp_stream_transport};

$exporter = otlp_exporter(otlp_stream_transport('/var/otel/traces.jsonl'));

Every batch is one line of JSON in the OTLP format. The collector picks it up with the otlpjsonfile receiver:

receivers:
  otlpjsonfile:
    include:
      - /var/otel/*.jsonl

Now a collector that is down costs PHP nothing, and it reads what it missed when it starts again. It needs no curl extension either. Somebody has to rotate the file.

When to sample in PHP

Tail sampling sees everything, so PHP sends everything. On a very busy application that is a lot of spans, even to localhost. Then PHP can drop a part of the traces at the start, and the collector chooses among the rest:

use function Flow\Telemetry\DSL\trace_id_ratio_based_sampler;

tracer_provider(
    batching_span_processor($exporter),
    clock(),
    memory_context_storage(),
    sampler: trace_id_ratio_based_sampler(0.25),
);

One trace in four leaves PHP. The price is that three of four slow requests and errors are gone before the collector can see them. Start without it.

Where to go from here

The spans themselves are in the guide about tracing in PHP. The ports, the timeouts and gRPC are in send PHP traces over OTLP. The same collector can show only the slow tests of a suite: see find slow PHPUnit tests.

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

scroll back to top