#Distributed tracing in PHP: pass traceparent from one service to the next
Let's say our checkout calls a second service to ask if a product is in stock. Both services have tracing. A customer complains about a slow checkout, and we find two traces: one in each service, with no way to tell that they belong together.
Doesn't look like a complicated task, right?
#Trace two PHP services separately
The first idea is always to trace each service on its own. The script plays both of them: stock() stands for the second service, and the array is the HTTP headers that travel between them.
<?php
declare(strict_types=1);
use Flow\Telemetry\Telemetry;
use function Flow\ETL\DSL\clock;
use function Flow\Telemetry\DSL\{memory_context_storage, resource, telemetry, tracer_provider, void_span_processor};
require __DIR__ . '/vendor/autoload.php';
function service(string $name): Telemetry
{
return telemetry(
resource(['service.name' => $name]),
tracer_provider(void_span_processor(), clock(), memory_context_storage()),
);
}
function stock(array $headers): string
{
$span = service('stock')->tracer('http')->span('GET /stock');
return 'stock trace ' . $span->context()->traceId->toHex();
}
$span = service('checkout')->tracer('http')->span('POST /checkout');
echo 'checkout trace ', $span->context()->traceId->toHex(), "\n";
echo stock(headers: []), "\n";
checkout trace c670645b3589cf4d76c06f05f8703630
stock trace a0f647c13833ac7278f1e9022dc5752c
It works, and each service sees its own part.
#Why two traces are not enough
The two ids have nothing in common. A trace id is made when the first span of a process starts, and the stock service doesn't know that somebody already made one.
To find the stock request of one slow checkout, we compare timestamps by hand. With ten checkouts a second that stops working.
The services have to agree on one id. The W3C standard for that is one HTTP header, traceparent:
00-faedc55bb8bcc470f0813f7f9522bfd7-5bbe8a0c8e3d45a7-01
It has four parts: a version, the trace id, the id of the span that makes the call, and a flag that says the trace is sampled.
#Pass the trace context with traceparent
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 Flow\Telemetry\Context\Context;
use Flow\Telemetry\Telemetry;
use Flow\Telemetry\Tracer\SpanKind;
use function Flow\ETL\DSL\clock;
use function Flow\Telemetry\DSL\{
array_carrier,
memory_context_storage,
propagation_context,
resource,
telemetry,
tracer_provider,
void_span_processor,
w3c_trace_context,
};
require __DIR__ . '/vendor/autoload.php';
function service(string $name): Telemetry
{
return telemetry(
resource(['service.name' => $name]),
tracer_provider(void_span_processor(), clock(), memory_context_storage()),
);
}
function stock(array $headers): string
{
$caller = w3c_trace_context()->extract(array_carrier($headers))->spanContext;
$span = service('stock')->tracer('http')->span(
'GET /stock',
SpanKind::SERVER,
parent: $caller === null ? null : Context::root()->withActiveSpan($caller),
);
return 'stock trace ' . $span->context()->traceId->toHex() . ' parent ' . $span->context()->parentSpanId?->toHex();
}
$span = service('checkout')->tracer('http')->span('POST /checkout', SpanKind::CLIENT);
$headers = array_carrier();
w3c_trace_context()->inject(propagation_context($span->context()), $headers);
echo 'checkout trace ', $span->context()->traceId->toHex(), ' span ', $span->context()->spanId->toHex(), "\n";
echo 'header ', $headers->unwrap()['traceparent'], "\n";
echo stock($headers->unwrap()), "\n";
checkout trace faedc55bb8bcc470f0813f7f9522bfd7 span 5bbe8a0c8e3d45a7
header 00-faedc55bb8bcc470f0813f7f9522bfd7-5bbe8a0c8e3d45a7-01
stock trace faedc55bb8bcc470f0813f7f9522bfd7 parent 5bbe8a0c8e3d45a7
Now both services have the same trace id, and the span of the stock service is a child of the checkout span.
Two calls do the work:
w3c_trace_context()->inject()writes the header on the side that calls.extract()reads it on the side that answers, and the new span gets it as itsparent. Without a headerextractgives no span context, and the service starts its own trace as before.
#The same with real HTTP requests
These two scripts need two web servers and a collector, so they run only on your machine, not in the playground.
In a real service the array is the HTTP request. The checkout adds the header to its call, with any HTTP client:
$tracer = $telemetry->tracer('http');
echo $tracer->trace('POST /checkout', static function () use ($tracer): string {
return $tracer->trace('GET stock', static function () use ($tracer): string {
$headers = array_carrier();
w3c_trace_context()->inject(propagation_context($tracer->activeSpan()), $headers);
return (string) file_get_contents('http://localhost:8002/', context: stream_context_create([
'http' => ['header' => 'traceparent: ' . $headers->unwrap()['traceparent']],
]));
}, SpanKind::CLIENT);
}, SpanKind::SERVER);
The stock service reads the header from the request. superglobal_carrier finds it in $_SERVER:
$caller = w3c_trace_context()->extract(superglobal_carrier())->spanContext;
echo $telemetry->tracer('http')->trace(
'GET /stock',
static fn (): string => "3 in stock\n",
SpanKind::SERVER,
$caller === null ? null : Context::root()->withActiveSpan($caller),
);
Both services send their spans to the same collector, and it shows one trace from two services:
service.name=stock
GET /stock 28094e1b42436657d5912fa3b1d373c6 cd9fcb66ae4e8983
service.name=checkout
GET stock 28094e1b42436657d5912fa3b1d373c6 c4e19ff8b5eb8a3d
POST /checkout 28094e1b42436657d5912fa3b1d373c6 935c0c2f0c27a3cd
Three spans, one trace id. A monitoring tool draws them as one timeline, and the slow part of the checkout is visible, whichever service it is in.
#What to know before you trust a traceparent
- The header comes from outside. A stranger can send one too, and then our spans join a trace we don't know. On a public endpoint, read it only from callers we trust.
- The last part of the header says if the caller keeps the trace. The default sampler follows that choice, so one checkout is kept or dropped in both services together.
- A queue works the same way. The header goes into the message, and the worker reads it from there.
#Where to go from here
The spans themselves are in the guide about tracing in PHP.
How the spans of both services reach one place is in send PHP traces over OTLP.
In Symfony the bundle reads the header of every request for us, with flow-php/symfony-http-foundation-telemetry-bridge installed: see Symfony monitoring with OpenTelemetry.
The log lines of both services get the same id too: see PHP logs with a trace id.