A user reports that a page is slow. You open logs/error.log and find nothing, because nothing failed. The server graph is calm. The time is going somewhere between your controller, the database and a background worker, and a log file cannot tell you where.
This is the problem distributed tracing solves. In this article we add OpenTelemetry to a CakePHP 5 application, first with almost no code, then with the two pieces that no package gives you out of the box: finding an N+1 query in a trace, and following a request into a queue worker.
Everything here was run on CakePHP 5.4.3, PHP 8.4 and PostgreSQL 16, with DDEV. Every snippet you need is in the article, so you can follow along in any CakePHP 5 application.
What we are building
A CakePHP app with a few demo endpoints, a queue worker and Jaeger to look at the result. Every box below sends spans to Jaeger over OTLP:
browser --> CakePHP (HTTP request) --> queue (filesystem) --> queue worker
| |
+------------- spans over OTLP/HTTP -------------+
|
v
Jaeger (UI on :16686)
The log file in this story is innocent: nothing failed, it was just slow. A trace is how you find out where the time went.
1. Logs, metrics and traces in one minute
- Logs tell you what happened at a point in time.
- Metrics tell you how much of something happened, such as requests per second.
- Traces tell you where the time went for one request.
A trace is one request from start to finish. It is made of spans: one for the HTTP request, one for each middleware, one for the controller, one for each SQL query. Spans nest, so you read a trace as a waterfall.
OpenTelemetry (OTel) is the vendor-neutral standard for producing this data. Your app emits spans over OTLP, and any compatible backend can display them. We will use Jaeger locally.
2. Running it
The example uses DDEV. Two small additions to the project give us everything.
The PHP extension ext-opentelemetry is what lets the auto-instrumentation packages hook into framework code. It is not in the default DDEV image, so we build it in .ddev/web-build/Dockerfile:
ARG BASE_IMAGE
FROM $BASE_IMAGE
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends php8.4-dev php-pear build-essential \
&& (printf '\n' | pecl install opentelemetry) \
&& echo "extension=opentelemetry.so" > /etc/php/8.4/mods-available/opentelemetry.ini \
&& phpenmod opentelemetry
Jaeger runs as an extra DDEV service, .ddev/docker-compose.jaeger.yaml:
services:
jaeger:
container_name: ddev-${DDEV_SITENAME}-jaeger
image: jaegertracing/all-in-one:1.76.0
expose:
- "16686"
- "4318"
labels:
com.ddev.site-name: ${DDEV_SITENAME}
com.ddev.approot: ${DDEV_APPROOT}
environment:
- COLLECTOR_OTLP_ENABLED=true
- VIRTUAL_HOST=jaeger.${DDEV_SITENAME}.ddev.site
- HTTP_EXPOSE=16687:16686
- HTTPS_EXPOSE=16686:16686
Run ddev restart, and the Jaeger UI is available at https://jaeger.<your-project>.ddev.site:16686.
We pinned Jaeger to 1.76.0, the version we tested. Its startup log warns that Jaeger v1 is deprecated, so check the current recommended image before you copy this into a long-lived setup. The OTLP endpoint and the UI are what matter here. Other OTLP-compatible backends should work the same way, but we only ran Jaeger.
3. The first trace with no application code
Install the SDK, the OTLP exporter and the instrumentation packages:
ddev composer require \
open-telemetry/sdk \
open-telemetry/exporter-otlp \
open-telemetry/opentelemetry-auto-psr15 \
open-telemetry/opentelemetry-auto-cakephp \
open-telemetry/opentelemetry-auto-pdo \
guzzlehttp/guzzle php-http/guzzle7-adapter nyholm/psr7
Then configure everything through environment variables. In DDEV that is one command:
ddev config --web-environment-add="OTEL_PHP_AUTOLOAD_ENABLED=true,OTEL_SERVICE_NAME=cakephp-demo,OTEL_TRACES_EXPORTER=otlp,OTEL_METRICS_EXPORTER=none,OTEL_LOGS_EXPORTER=none,OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf,OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318"
Restart, open any page, and a trace appears in Jaeger. We wrote no instrumentation code. What did each package give us?
| Package | What you get |
|---|---|
opentelemetry-auto-psr15 |
One span per middleware, so you see the whole CakePHP middleware queue |
opentelemetry-auto-pdo |
One span for each PDO::prepare, PDOStatement::execute and fetchAll, so every ORM query is traced |
opentelemetry-auto-cakephp |
A span for the controller invocation |
A word of caution about the last one. At the time of writing opentelemetry-auto-cakephp is at version 0.1.0 and instruments the controller invocation only. It is useful, but the PSR-15 and PDO packages carry most of the value for a CakePHP app. Their versions in our test were 1.3.1 and 0.6.0.
One thing that surprises people: in a fresh CakePHP app DebugKit is enabled in debug mode, and it stores its own data in SQLite. Those queries show up as extra PDO spans (31 extra queries per request in our test). Filter on the db.system.name attribute, or disable DebugKit while you explore. We disabled it for the measurements below.
Exceptions come for free as well. A request to a URL with no matching controller shows up with the MissingControllerException recorded on the span, which is more than a 404 in an access log will ever tell you.
4. Finding an N+1 query in a waterfall
The demo uses three tables: customers, orders (with a customer_id) and order_items (with an order_id). Any application with a few related tables will do. We seeded 50 customers, 200 orders and 600 items. A fresh CakePHP 5 app does not guess table classes, so create CustomersTable, OrdersTable and OrderItemsTable (with bake or by hand). The associations are the usual ones:
// OrdersTable::initialize()
$this->belongsTo('Customers');
$this->hasMany('OrderItems');
Here is an endpoint that lists the 50 latest orders with the customer name and the number of items. It is the classic mistake: one query for the orders, then two more per row.
public function slow(): Response
{
$orders = $this->fetchTable('Orders')->find()->orderByDesc('id')->limit(50)->all();
$result = [];
foreach ($orders as $order) {
$customer = $this->fetchTable('Customers')->get($order->customer_id);
$items = $this->fetchTable('OrderItems')->find()->where(['order_id' => $order->id])->all();
$result[] = ['id' => $order->id, 'customer' => $customer->name, 'items' => $items->count()];
}
return $this->response->withType('application/json')->withStringBody(json_encode($result));
}
The fix is eager loading, and the rest of the action stays the same, reading $order->customer->name and count($order->order_items):
$orders = $this->fetchTable('Orders')->find()
->contain(['Customers', 'OrderItems'])
->orderByDesc('Orders.id')
->limit(50)
->all();
Both versions return the same JSON. The traces do not look alike. In Jaeger, open a trace and switch the view from "Trace Timeline" to "Trace Statistics", group by operation name and sort by count.
The slow request produced a trace with 348 spans and took 199 ms. The three PDO operations each appear 109 times: 50 customer lookups, 50 item lookups, the orders query, and 8 schema-reflection queries. PDOStatement::execute alone accounts for 60 ms, 30% of the request:

The eager-loaded request has 27 spans, 2 queries and takes 33 ms. The 3 PDO::exec calls are connection setup:
)
No log line would have shown this, and no query was individually slow. There were just a lot of them. A trace makes that visible in seconds.
5. Following a request into the queue
This is the part that auto-instrumentation does not do for you. When a controller pushes a job with cakephp/queue, the work continues in a separate worker process. By default the trace stops at the push, and the worker starts a new, unrelated one.
OpenTelemetry solves this with context propagation: the producer writes the trace context, the W3C traceparent value, into the message, and the consumer reads it and continues the same trace. Two small classes do it, and the job classes need no changes.
The queue setup
If you already use cakephp/queue, skip ahead. For the example we used the filesystem transport, which needs no extra service:
ddev composer require cakephp/queue enqueue/fs
mkdir -p tmp/queue
Composer registers the plugin in config/plugins.php for you. Until the queue is configured, every bin/cake command fails with "Missing Queue configuration key", so add the configuration next. A fresh app already has a config/app_local.php that returns an array, so add the Queue key to that array, using an absolute path inside the container:
// config/app_local.php: add this key to the returned array
'Queue' => [
'default' => [
'url' => 'file:///var/www/html/tmp/queue',
],
],
The job does a few queries and sleeps to simulate slow work. A negative customer id makes it throw, so we can test the failure path later. This version is simplified:
class ReportJob implements JobInterface
{
public function execute(Message $message): ?string
{
$customerId = (int)$message->getArgument('customer_id');
if ($customerId < 0) {
throw new \RuntimeException('Report generation failed (demo)');
}
FactoryLocator::get('Table')->get('Orders')->find()
->where(['customer_id' => $customerId])
->count();
usleep(150000);
return Processor::ACK;
}
}
Start a worker in a second terminal with ddev exec bin/cake queue worker.
Context propagation
The code excerpts that follow leave out the use statements. The classes come from these namespaces: OpenTelemetry\API\Trace\{SpanKind, StatusCode, SpanInterface, TracerProviderInterface}, OpenTelemetry\API\Trace\Propagation\TraceContextPropagator, OpenTelemetry\Context\ScopeInterface, and OpenTelemetry\SDK\Trace\TracerProviderInterface (imported as SdkTracerProviderInterface, because the API interface has the same name), plus Cake\Queue\QueueManager and Cake\Event\{EventInterface, EventListenerInterface}. src/Application.php also needs OpenTelemetry\API\Globals, Cake\Core\ContainerInterface and Cake\Event\EventManagerInterface. We put the two classes in src/Queue/TracedQueue.php and src/Listener/QueueTracingListener.php. The job uses Cake\Queue\Job\{JobInterface, Message}, Cake\Datasource\FactoryLocator and Interop\Queue\Processor.
A fresh application already contains empty services() and events() methods in src/Application.php, so fill in their bodies.
Both classes receive the tracer provider through their constructor, so they follow the dependency injection style CakePHP 5.3 encourages and are easy to test with a fake provider. Only one place in the application reads the OpenTelemetry global state, the container registration in src/Application.php. The auto-instrumentation packages configure the SDK globally, so we register that global provider once and inject it everywhere else:
public function services(ContainerInterface $container): void
{
// The only place that touches the OpenTelemetry global state.
$container->addShared(TracerProviderInterface::class, fn () => Globals::tracerProvider());
$container->addShared(TracedQueue::class)->addArgument(TracerProviderInterface::class);
$container->addShared(QueueTracingListener::class)->addArgument(TracerProviderInterface::class);
}
public function events(EventManagerInterface $eventManager): EventManagerInterface
{
$eventManager->on($this->getContainer()->get(QueueTracingListener::class));
return $eventManager;
}
The producer wraps QueueManager::push() in a span and injects the context into the payload:
class TracedQueue
{
public const CARRIER_KEY = '_otel';
public function __construct(private TracerProviderInterface $tracerProvider)
{
}
public function push(string $className, array $data = [], array $options = []): void
{
$tracer = $this->tracerProvider->getTracer('app.queue');
$span = $tracer->spanBuilder('queue publish ' . $className)
->setSpanKind(SpanKind::KIND_PRODUCER)
->setAttribute('messaging.operation.type', 'publish')
->startSpan();
$scope = $span->activate();
try {
$carrier = [];
TraceContextPropagator::getInstance()->inject($carrier);
$data[self::CARRIER_KEY] = $carrier;
QueueManager::push($className, $data, $options);
} finally {
$scope->detach();
$span->end();
}
}
}
Controllers receive it as an action argument, and CakePHP resolves it from the container:
public function report(TracedQueue $queue): Response
{
$queue->push(ReportJob::class, ['customer_id' => $this->request->getQuery('fail') ? -1 : 7]);
return $this->response->withType('application/json')->withStringBody(json_encode(['queued' => true]));
}
The consumer side is an event listener. cakephp/queue dispatches Processor.message.* events around every message. We open a span when processing starts, and close it on success, failure, rejection or exception:
class QueueTracingListener implements EventListenerInterface
{
private ?SpanInterface $span = null;
private ?ScopeInterface $scope = null;
public function __construct(private TracerProviderInterface $tracerProvider)
{
}
public function implementedEvents(): array
{
return [
'Processor.message.start' => 'start',
'Processor.message.exception' => 'exception',
'Processor.message.success' => 'finish',
'Processor.message.failure' => 'finish',
'Processor.message.reject' => 'finish',
];
}
public function start(EventInterface $event): void
{
/** @var \Cake\Queue\Job\Message $message */
$message = $event->getData('message');
$carrier = (array)$message->getArgument(TracedQueue::CARRIER_KEY, []);
$parent = TraceContextPropagator::getInstance()->extract($carrier);
$span = $this->tracerProvider->getTracer('app.queue')
->spanBuilder('queue process ' . $message->getTarget()[0])
->setParent($parent)
->setSpanKind(SpanKind::KIND_CONSUMER)
->setAttribute('messaging.operation.type', 'process')
->startSpan();
$this->span = $span;
$this->scope = $span->activate();
}
public function exception(EventInterface $event): void
{
/** @var \Throwable $exception */
$exception = $event->getData('exception');
$this->span?->recordException($exception);
$this->span?->setStatus(StatusCode::STATUS_ERROR, $exception->getMessage());
$this->finish($event);
}
public function finish(EventInterface $event): void
{
$this->scope?->detach();
$this->span?->end();
$this->scope = null;
$this->span = null;
// A worker never reaches shutdown between jobs, so flush or spans stay in memory.
if ($this->tracerProvider instanceof SdkTracerProviderInterface) {
$this->tracerProvider->forceFlush();
}
}
}
The exception() method is the important one for asynchronous failures. The exception never reaches a browser or a log of the request, so recording it on the span is how it shows up in the trace, next to the request that queued the job.
The result is one trace with both halves. The HTTP request finishes in about 8 ms, and the worker span, a child of the publish span, starts about 100 ms later and runs for 262 ms:

Two things that bit us
Workers must flush explicitly. A PHP worker is a long-running process, and the batch span processor does not export on a timer. In our first test, a job only appeared in Jaeger after the worker exited. The forceFlush() call at the end of finish() fixes it, and spans then appear within seconds.
A failing job can flood your traces. When a job throws, cakephp/queue requeues it. Without a limit, our deliberately failing job was retried in a tight loop and one trace reached 12,772 spans in about 15 seconds. Tracing made the problem visible, but it also shows why you should always cap attempts:
class ReportJob implements JobInterface
{
public static ?int $maxAttempts = 3;
// execute() as before
}
To trigger the failure, call /otel-demo/report?fail=1, which pushes the job with a negative customer id.
With the cap, the same failing job produced exactly three queue process spans, one per attempt, each marked as an error with the exception message recorded. In Jaeger each span carries error=true, otel.status_code=ERROR and a log entry with the exception message and stack trace:

Jaeger also shows a warning on these spans, "clock skew adjustment disabled". It appears because a worker span starts after its parent publish span has already ended, which is normal for asynchronous queues, and it can be ignored.
6. Production notes and what we did not test
This is a development setup. Before you run it elsewhere, consider the following, and note where we stopped testing.
- Sampling. Recording every request is fine on a laptop. In production, set a sampler so you export a fraction of traces. We checked the environment variables with a small script that creates 400 spans against the PHP SDK: with no sampler all 400 were sampled, and with
OTEL_TRACES_SAMPLER=parentbased_traceidratioandOTEL_TRACES_SAMPLER_ARG=0.142 were sampled. We did not run the CakePHP example itself with a sampler. - Overhead. Auto-instrumentation wraps every middleware and every PDO call. A trace with 348 spans costs something to build and export. We counted spans but did not benchmark the cost, so measure it on your own workload.
- Sensitive data. The PDO spans carry the SQL text in the
db.query.textattribute, and spans can carry request details too. Check what attributes your backend actually receives before you send production traffic to a hosted service. - A real backend. Jaeger's all-in-one image keeps traces in memory and loses them on restart. Use a persistent store or a hosted OTLP backend for anything beyond development.
- Queue transports. The example uses the filesystem transport (
enqueue/fs). The context travels inside the message payload, so other transports should behave the same, but we did not run them. - CakePHP versions. Everything ran on CakePHP 5.4.3. The instrumentation packages declare support for CakePHP 4 and 5, but we only tested 5.4.3.
- Traces only. The example exports traces. The metrics and logs exporters are switched off.
- Pin your versions. We tested with
open-telemetry/sdk1.15.0,exporter-otlp1.4.0,ext-opentelemetry1.4.2 andcakephp/queue2.3.1. The CakePHP instrumentation package is still pre-1.0.
Next steps
- Add custom spans around business logic, such as a payment call, using the same tracer API shown above.
- Trace outgoing HTTP calls to external services so they appear inside the waterfall.
- Send metrics and logs through OTLP as well, so the three signals sit in one place.
- Try a sampler and measure the overhead on your own workload.
Further reading
- OpenTelemetry PHP documentation
- W3C Trace Context specification, the
traceparentformat used to carry the trace through the queue - CakePHP Queue plugin
- Jaeger documentation
Need help with this in your own CakePHP app?
Talk to a CakePHP expertGet the CakeDC newsletter
One email a month: releases, security advisories and one article worth reading.