Understanding OpenTelemetry Tracing

Contents

Introduction

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.

What I built

Architecture diagram: Next.js sends traceparent to the BFF, the BFF calls API-A, API-B and API-C with traceparent, API-C also calls API-A, every service sends OTLP to the OTel Collector, which forwards to Jaeger. Next.js also uses Supabase for authentication.

I want to check the following 👇

  • Connect the trace from the frontend to the APIs with the traceparent header
  • Browser → BFF → API show up in Jaeger under a single Trace ID

What is OpenTelemetry?

OpenTelemetry (OTel) is an open-source observability framework. It lets you collect and send telemetry data without depending on a vendor.

https://opentelemetry.io/

Telemetry signals

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"

Terminology

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

The traceparent header

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.

Packages and their roles

This time, I combined the following packages to keep changes to the app code small.

Frontend (Next.js)

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

Backend (CakePHP)

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

How tracing works

Step 1: Browser → BFF

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

Step 2: Carrying the trace over in the BFF

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']);
}

Step 3: BFF → calling API-A and API-B (inject)

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.

Step 4: API-A receives it (extract)

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

Step 5: Telemetry reaches Jaeger through the Collector

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.

Data flow

Each service's OTel SDK sends OTLP to the OTel Collector, which sends OTLP to Jaeger

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.

Setting up the environment

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.

Initializing the OTel SDK on the frontend

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) {
  // ...
}

Backend

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');

How it looks in Jaeger

When calling the APIs (API-A/B called in parallel)

Jaeger trace tree: frontend HTTP GET, then nested bff spans through the CakePHP middleware down to DashboardController::index, which calls api-a-user and api-b-product

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)

The same Jaeger trace tree with red error markers on the bff spans and on the api-b-product call

Wrapping up

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.

References

Translated from the Japanese original.

Thanks. I'll look into it.

Spotted a mistake?

Tell me what's wrong and I'll fix it. Only I see what you send.