Understanding OpenTelemetry Tracing
Contents
When a backend calls multiple APIs, I think it can get hard to isolate which API is failing, for example when an incident happens.
This post is a record of researching and running an environment that can trace a [Next.js → PHP (BFF) → multiple API calls] setup.

I want to check the following 👇
- Connect the trace from the frontend to the APIs with the
traceparentheader - Browser → BFF → API show up in Jaeger under a single Trace ID
OpenTelemetry (OTel) is an open-source observability framework. It lets you collect and send telemetry data without depending on a vendor.
OTel defines the following signals. This post focuses on Traces.
| Signal | What it records | Example |
|---|---|---|
| Traces | The flow of a request | The call path BFF → API-A |
| Metrics | Aggregated numbers | Requests per second, response time |
| Logs | Individual events | "User 123 created an order" |
| Term | Description |
|---|---|
| Span | One unit of work. "Called an API" or "queried the DB" each become one Span |
| Span ID | An identifier unique to each Span. A new one is generated every time a Span is created |
| Parent ID | Indicates which Span is this Span's parent. It holds the ID of the Span that was active when this Span was created |
| Trace ID | An identifier for the whole request. Once generated, it is shared by all APIs |
| Context Propagation | The mechanism that carries the Trace ID across services |
| Collector | A relay server that receives, processes, and forwards telemetry. It runs independently, outside the PHP process |
Context Propagation is the mechanism that carries the Trace ID across services without breaking it. As the concrete way to propagate it, we use the traceparent header standardized by W3C Trace Context.
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
│ │ │ │
│ trace-id (32 hex) parent-id (16 hex) trace-flags
version * span-id of the Span active when sending
- parent-id: holds the Span ID of the Span that was active when the request was sent. The receiver creates its own Span with this value as its parent
This header is used in the HTTP requests between frontend → BFF and BFF → API.
This time, I combined the following packages to keep changes to the app code small.
| Package | Role |
|---|---|
@opentelemetry/sdk-trace-web |
The core of Span creation (WebTracerProvider) |
@opentelemetry/instrumentation-fetch |
Hooks fetch() to create Spans + adds traceparent |
@opentelemetry/exporter-trace-otlp-http |
Sends Spans to the Collector |
@opentelemetry/context-zone |
Tracks context across async operations |
| Package | Role |
|---|---|
| kaz29/cakephp-otel-plugin | Creates Controller Spans automatically |
| opentelemetry-auto-psr15 | Extracts traceparent from incoming requests (extract) |
| opentelemetry-auto-guzzle | Injects traceparent into outgoing requests (inject) |
| ext-opentelemetry | The PECL extension the packages above need in order to hook PHP methods |
The browser's OTel JS SDK creates a Span and automatically adds the traceparent header to fetch().
POST /api/dashboard.json HTTP/1.1
Host: localhost:8080
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-aabb001122334455-01
Frontend Span:
traceId: 4bf92f3577b34da6a3ce929d0e0e4736 (newly generated)
spanId: aabb001122334455 (newly generated)
parentId: none (root)
name: HTTP POST
When the request reaches the BFF, opentelemetry-auto-psr15 automatically extracts the Context from the traceparent header and creates a server span. The same Trace ID as the frontend carries over.
Next, cakephp-otel-plugin automatically creates the Controller's Span.
https://github.com/kaz29/cakephp-otel-plugin
BFF Span (server span):
traceId: 4bf92f3577b34da6a3ce929d0e0e4736 ← same as the frontend (carried over)
spanId: 00f067aa0ba902b7 (newly generated)
parentId: aabb001122334455 ← the frontend's spanId (from traceparent)
name: RequestHandlerInterface::handle
└─ BFF Span (internal span):
traceId: 4bf92f3577b34da6a3ce929d0e0e4736
spanId: 1122334455667788 (newly generated)
parentId: 00f067aa0ba902b7 ← handle's spanId (the active spanId)
name: DashboardController::index
The Controller calls the downstream APIs. (This is not good practice, but this time I wrote it directly in the Controller to make the trace flow easier to follow.)
public function index(): void
{
$apiA = new ApiClient(env('API_A_URL', 'http://api-a'));
$apiB = new ApiClient(env('API_B_URL', 'http://api-b'));
// API calls
$promises = [
'user' => $apiA->getAsync('/users/me.json'),
'products' => $apiB->getAsync('/products.json'),
];
$results = Utils::unwrap($promises);
$this->set('dashboard', [
'user' => json_decode((string)$results['user']->getBody(), true),
'products' => json_decode((string)$results['products']->getBody(), true),
]);
$this->viewBuilder()->setOption('serialize', ['dashboard']);
}
When calling a downstream API, opentelemetry-auto-guzzle hooks the Guzzle request, generates a Span ID, and writes that Span ID into the HTTP request as the traceparent header.
BFF Span (client span):
traceId: 4bf92f3577b34da6a3ce929d0e0e4736
spanId: aabbccdd11223344 (newly generated)
parentId: 1122334455667788 ← the Controller's spanId
name: GET
The Span ID of this CLIENT span is sent to API-A as the parent-id in traceparent.
GET /users/me.json HTTP/1.1
Host: api-a
Accept: application/json
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-aabbccdd11223344-01
A traceparent with the same Trace ID is sent to API-B too.
On the API side as well, opentelemetry-auto-psr15 creates a server span with the parent-id from traceparent as its parent. Then cakephp-otel-plugin creates the Controller span.
API-A Span (server span):
traceId: 4bf92f3577b34da6a3ce929d0e0e4736 ← same as the BFF (carried over)
spanId: 1a2b3c4d5e6f7890 (newly generated)
parentId: aabbccdd11223344 ← spanId of the BFF's CLIENT span (from traceparent)
name: RequestHandlerInterface::handle
└─ API-A Span (internal span):
spanId: 5566778899aabbcc (newly generated)
parentId: 1a2b3c4d5e6f7890 ← handle's spanId (because it was active)
name: UsersController::me
The SDKs in the frontend and in each PHP service send Span data to the Collector. Jaeger gathers the Spans that share a Trace ID and builds the tree from parentId.

The OTel SDKs in the frontend and in each backend send Span data to the Collector over OTLP (OpenTelemetry Protocol).
So even if you change the destination from Jaeger to another service such as Azure Monitor, you only rewrite the Collector's config file and don't have to touch the app code.
Dockerfile
FROM php:8.3-apache
# System dependency packages
RUN apt-get update && apt-get install -y \
git \
unzip \
libzip-dev \
libicu-dev \
libonig-dev \
&& rm -rf /var/lib/apt/lists/*
# PHP extensions
RUN docker-php-ext-install \
intl \
pdo_mysql \
zip \
mbstring
# ext-opentelemetry (PECL extension required for auto-instrumentation)
RUN pecl install opentelemetry \
&& docker-php-ext-enable opentelemetry
# ext-protobuf (faster protobuf serialization)
RUN pecl install protobuf \
&& docker-php-ext-enable protobuf
# Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Apache mod_rewrite (required for CakePHP routing)
RUN a2enmod rewrite
# Change Apache's DocumentRoot to CakePHP's webroot
ENV APACHE_DOCUMENT_ROOT=/var/www/html/webroot
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' \
/etc/apache2/sites-available/*.conf \
&& sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' \
/etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf
# AllowOverride All (enables .htaccess)
RUN sed -ri -e 's/AllowOverride None/AllowOverride All/g' \
/etc/apache2/apache2.conf
WORKDIR /var/www/html
OTel Collector config (otel-collector-config.yml)
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
cors:
allowed_origins:
- "http://localhost:3000"
allowed_headers:
- "*"
processors:
batch: {}
exporters:
otlphttp/jaeger:
endpoint: http://jaeger:4318
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlphttp/jaeger]
docker-compose.yml (excerpt)
services:
otel-collector:
image: otel/opentelemetry-collector-contrib:latest
volumes:
- ./otel-collector-config.yml:/etc/otelcol-contrib/config.yaml
ports:
- "4318:4318"
jaeger:
image: jaegertracing/all-in-one:latest
ports:
- "16686:16686"
bff:
build: ./php
volumes:
- ./php/bff:/var/www/html
ports:
- "8080:80"
environment:
OTEL_PHP_AUTOLOAD_ENABLED: "true"
OTEL_SERVICE_NAME: bff
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_PROPAGATORS: tracecontext,baggage
API_A_URL: http://api-a
API_B_URL: http://api-b
API_C_URL: http://api-c
api-a:
build: ./php
volumes:
- ./php/api-a:/var/www/html
environment:
OTEL_PHP_AUTOLOAD_ENABLED: "true"
OTEL_SERVICE_NAME: api-a-user # ← change per service
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_PROPAGATORS: tracecontext,baggage
# api-b and api-c are the same (only OTEL_SERVICE_NAME changes)
frontend:
image: node:20-alpine
working_dir: /app
volumes:
- ./frontend:/app
ports:
- "3000:3000"
command: sh -c "npm install && npm run dev"
environment:
NEXT_PUBLIC_BFF_URL: http://localhost:8080
NEXT_PUBLIC_OTEL_COLLECTOR_URL: http://localhost:4318
API-A/B/C reuse the same Docker image and only change OTEL_SERVICE_NAME.
lib/tracing.ts
const COLLECTOR_URL =
process.env.NEXT_PUBLIC_OTEL_COLLECTOR_URL ?? "http://localhost:4318";
let initialized = false;
export function initTracing(): void {
if (initialized || typeof window === "undefined") {
return;
}
initialized = true;
const resource = new Resource({
[ATTR_SERVICE_NAME]: "frontend",
});
const exporter = new OTLPTraceExporter({
url: `${COLLECTOR_URL}/v1/traces`,
});
const provider = new WebTracerProvider({
resource,
spanProcessors: [new BatchSpanProcessor(exporter)],
});
provider.register({
contextManager: new ZoneContextManager(),
});
registerInstrumentations({
instrumentations: [
new FetchInstrumentation({
// Automatically add traceparent to fetches to the BFF (localhost:8080)
propagateTraceHeaderCorsUrls: [/localhost:8080/],
// Don't instrument the sends to the Collector themselves (prevents recursion)
ignoreUrls: [/localhost:4318/],
}),
],
});
}
pages/_app.tsx
import { initTracing } from "@/lib/tracing";
initTracing();
export default function App({ Component, pageProps }: AppProps) {
// ...
}
Initial setup
composer require kaz29/cakephp-otel-plugin
composer require open-telemetry/opentelemetry-auto-psr15
composer require open-telemetry/opentelemetry-auto-guzzle
// bootstrap() in src/Application.php
$this->addPlugin('OtelInstrumentation');

Starting from the frontend, the parallel calls BFF → API-A + API-B are shown as a tree.
- How it looks when an exception occurs (an exception in API-B)

This time I built an environment that connects the frontend through the backend with a single Trace ID.
For real operation there is still a lot to consider, such as how to design Span granularity, but I think I got a picture of how distributed tracing works.
- kaz29/cakephp-otel-plugin
- I built an OpenTelemetry plugin for CakePHP (Japanese)
- OpenTelemetry official documentation
- W3C Trace Context specification
- open-telemetry/opentelemetry-auto-psr15 (Packagist)
- open-telemetry/opentelemetry-auto-guzzle (Packagist)
- OpenTelemetry JavaScript SDK
- A rough overview of OpenTelemetry (Qiita) (Japanese)
- Application Insights OpenTelemetry overview (Microsoft Learn)
Translated from the Japanese original.
Thanks. I'll look into it.
Sorry, that didn't go through. Please try again later.