# Tracing with OpenTelemetry and Jaeger

Follow one request through many services: spans, trace context and the traceparent header, OpenTelemetry SDKs and the Collector, and reading a real Jaeger waterfall to find the slow and failing parts.

Course: [Monitoring](https://devops.rajeev.pro/courses/monitoring), lesson 6. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/monitoring/06-tracing-with-opentelemetry

## What you will learn

- Explain traces, spans, parent spans and trace context in plain words
- Read a traceparent header and say what each part means
- Describe what the OpenTelemetry SDK, OTLP and the Collector each do
- Run Jaeger and read a real trace waterfall to find the slowest span and the errors
- Jump from a log line to its trace with a trace ID, and choose a sampling strategy

When one click goes through five services, metrics say the request is slow and logs show forty
unrelated lines, but neither says where the time went. A **trace** follows that one request across
every service. In this lesson you'll run Jaeger, send real requests through a demo app, and read a
real trace to find the slow part and the errors.

> **Video.** [Introduction to Tracing : OpenTelemetry & Opentracing](https://www.youtube.com/watch?v=idDu_jXqf4E) (That DevOps Guy)

## Traces, spans and context

- A **span** is one timed operation: "handle GET /dispatch", "SELECT from customers", "call Redis
  GetDriver". It has a name, a start time, a duration, **attributes** (key-value details such as
  `http.status_code=200`), a status (OK or error), and the ID of its **parent** span.
- A **trace** is all the spans of one request, forming a tree. The first span, with no parent, is the
  **root span**.
- **Trace context** is the trace ID plus the current span ID. Passing it from service to service is
  called **context propagation**, and it's the part that makes distributed tracing work.

> **Figure.** A request enters the frontend, which starts trace 4bf9 with span A lasting 1,840 ms. It calls cart with a traceparent header; cart creates span B with parent A, then calls payment, which creates span C with parent B and takes 1,742 ms. Each service sends its spans over OTLP to an OpenTelemetry Collector, which batches, samples and exports them to Jaeger. Jaeger joins spans by trace ID and draws a waterfall where payment holds 95 percent of the time.
>
> Each hop passes traceparent on. A service that drops the header starts a new trace, and the waterfall splits in two.

### The traceparent header

For HTTP, the standard is **W3C Trace Context**. A traced request carries one header:

```text
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             │  │                                │                └ flags: 01 = sampled
             │  │                                └ parent span ID (16 hex characters)
             │  └ trace ID (32 hex characters)
             └ version
```

When the cart service receives this, it does three things:

1. It reads the trace ID and the caller's span ID.
2. It starts its own span with the same trace ID and the caller's span as **parent**.
3. When it calls payment, it sends a new `traceparent` with the same trace ID and **its own** span ID.

If any service in the chain doesn't forward the header (an old library, a proxy that strips
headers, a message queue without context), the next service starts a brand-new trace. That's the
most common reason a trace "stops" halfway.

## OpenTelemetry

**OpenTelemetry** (OTel) is the open standard for producing telemetry: traces, metrics and logs.
It's a CNCF project that replaced the older OpenTracing and OpenCensus. Before it, every vendor
had its own agent and SDK, and switching from one APM tool to another meant re-instrumenting every
service. With OTel you instrument once and choose the backend in config.

It has three parts you need to know:

| Part                        | What it is                                                        | Example                                                              |
| --------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------- |
| **SDK and instrumentation** | Libraries in your app that create spans                           | `opentelemetry-instrument python app.py`, or the Java agent jar      |
| **OTLP**                    | The wire protocol for sending telemetry                           | gRPC on port **4317**, HTTP on port **4318**                         |
| **Collector**               | A separate service that receives, processes and exports telemetry | Receive OTLP, batch, drop health checks, send to Jaeger and a vendor |

### Instrumenting an app

There are two ways, and most teams use both:

- **Zero-code (automatic) instrumentation.** An agent or wrapper hooks into common libraries (HTTP
  servers and clients, database drivers, gRPC) and creates spans with no code changes. For Java
  that's the `-javaagent` jar, for Python `opentelemetry-instrument`, for Node.js a `--require`
  hook. It also handles propagation for those libraries.
- **Manual spans** around your own important steps, so the trace shows business logic, not just
  network calls:

```python
from opentelemetry import trace

tracer = trace.get_tracer("checkout")

def charge(order):
    with tracer.start_as_current_span("charge-card") as span:
        span.set_attribute("order.id", order.id)
        ...  # the span ends, with its duration, when the block exits
```

Where to send spans is configuration, through standard environment variables:

```sh
OTEL_SERVICE_NAME=checkout
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1   # keep 10% of new traces
```

### The Collector

Apps could send straight to Jaeger, and in the lab HotROD does exactly that. In production you put
an **OpenTelemetry Collector** in between. Its config is a pipeline:

```yaml
# otel-collector.yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318
processors:
  batch: {} # send spans in batches, not one by one
exporters:
  otlp/jaeger:
    endpoint: jaeger:4317
    tls:
      insecure: true
service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlp/jaeger]
```

Why bother? Apps stay simple (they only know "send OTLP to the Collector"). You can add a second
backend, remove sensitive attributes, or change sampling in one place. And if the backend is down,
the Collector buffers for a while instead of every app dropping data.

## Read a real trace in Jaeger

**Jaeger** is an open-source tracing backend, originally from Uber and now a CNCF project. It
stores spans and gives you a UI to search and read traces. The lab ran Jaeger 2.22 with the
**HotROD** demo app from the logs lesson, sending spans over OTLP:

```sh
$ docker run -d --name jaeger --network mon -p 16686:16686 -p 4317:4317 -p 4318:4318 jaegertracing/jaeger
$ docker run -d --name hotrod --network mon -p 8080:8080 \
    -e OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318 jaegertracing/example-hotrod all
$ for c in 123 392 731 567; do curl -s -o /dev/null -w "customer=$c %{http_code} %{time_total}s\n" "localhost:8080/dispatch?customer=$c"; done
customer=123 200 1.031454s
customer=392 200 0.705003s
customer=731 200 0.727585s
customer=567 200 0.734258s
```

Each `/dispatch` request is one ride booking. Jaeger's **Search** page lists the traces for a
service, with their span count, error count and duration:

> **Figure.** Jaeger Search page for service frontend over the last hour, 5 traces. A scatter chart shows four traces between about 700 ms and 1.1 s. The table lists four frontend GET /dispatch traces with 39 or 40 spans, 2 or 3 errors each, and durations of 718, 709, 693 and 960 milliseconds, plus one GET / trace with 1 span taking 10.6 ms.
>
> Four ride bookings, each about 40 spans across 6 services, each with 2 or 3 errors, which the services retried.

Open the slowest one (960 ms) and Jaeger draws the **waterfall**: one row per span, indented under
its parent, with a bar showing when it started and how long it took.

> **Figure.** Jaeger trace view for frontend GET /dispatch, trace 9881c56, duration 960 ms, 6 services, depth 4, 40 spans. The frontend root span runs the full 960 ms. Under it, frontend HTTP GET 396 ms calls customer GET /customer 349 ms, which runs a mysql SQL SELECT taking 330 ms. Then frontend calls driver FindNearest, 267 ms, whose driver span of 230 ms makes one redis FindDriverIDs call and then fourteen GetDriver calls one after another, each about 8 to 32 ms, three of them marked with a red error icon. At the bottom, route GET /route calls run partly in parallel.
>
> A real trace. The MySQL query is a third of the request, then fourteen Redis calls run one after another, and three of them failed.

Read it top to bottom. The same trace from Jaeger's API, one line per span (start offset, duration,
service, operation), cut after the Redis calls:

```text
     0.0ms    959.9ms  frontend   GET /dispatch
    33.5ms    396.3ms  frontend   HTTP GET
    67.9ms    348.7ms  customer   GET /customer
    70.9ms    330.3ms  mysql      SQL SELECT
   464.5ms    266.8ms  frontend   driver.DriverService/FindNearest
   498.9ms    230.2ms  driver     driver.DriverService/FindNearest
   501.9ms     25.1ms  redis-manual FindDriverIDs
   527.2ms     32.6ms  redis-manual GetDriver
   559.9ms      7.8ms  redis-manual GetDriver
   568.1ms      9.7ms  redis-manual GetDriver
   ...
   740.1ms     59.2ms  route      GET /route
   750.3ms     46.4ms  route      GET /route
   750.3ms     47.2ms  route      GET /route
```

What the trace tells you, in a minute, that no single dashboard could:

1. **The biggest cost is one SQL query.** `SQL SELECT` takes 330 ms of 960 ms. Before touching
   anything else, look at that query and its index.
2. **Redis is called in a loop.** One `FindDriverIDs`, then `GetDriver` fourteen times, **one
   after another** (each starts when the previous one ends). That's the N+1 pattern: one batched
   call (Redis `MGET`, or a pipeline) would replace fourteen round trips.
3. **Some calls fail and get retried.** The red icons are spans with error status. Their logs say
   `redis timeout`, the same errors you found in Loki in the last lesson.
4. **The route calls run in parallel.** Several `GET /route` spans start at the same time (740 ms,
   750 ms, 750 ms). That part was already designed well.

### From a log line to its trace

HotROD writes the trace ID into every log line:

```text
2026-11-04T04:37:32.258Z	INFO	customer/server.go:64	HTTP request received	{"service": "customer", "trace_id": "9881c56bd9002eeee8637029115c5b57", "span_id": "5bb184a1881997f0", "method": "GET", "url": "/customer?customer=123"}
```

Paste `9881c56bd9002eeee8637029115c5b57` into Jaeger's **Lookup by Trace ID** box and you get the
waterfall above. Go the other way in Loki with `{container="hotrod"} |= "9881c56bd9002eeee8637029115c5b57"`
to get every log line of that one request, from every service. In Grafana you can make this a
click: a Loki data source setting called **derived fields** turns each `trace_id` in a log line into
a link to the trace. That link between logs and traces is what lesson 1 called observability.

## Sampling

A busy service handles thousands of requests a second, each with dozens of spans. Keeping all of
them costs a lot of network, storage and money, and you'd never read most of them. So traces are
**sampled**:

- **Head sampling** decides at the start of the request, in the first service, for example "keep
  10%". The decision travels in the `traceparent` flags, so every service agrees. It's simple and
  cheap, but it throws away 90% of the slow and failed requests too.
- **Tail sampling** decides after the whole trace has finished, in the Collector (the
  `tail_sampling` processor). It can keep **every** trace with an error or a duration above 1
  second, and only a few per cent of the fast, healthy ones. It's better, and it needs a Collector
  that sees all spans of a trace and the memory to hold them for a few seconds.

Start with head sampling at a rate you can afford. Move to tail sampling when you keep missing the
interesting traces.

> **Jaeger, Tempo or a vendor.** Jaeger is the classic open-source backend. Grafana Tempo stores traces cheaply in object storage and sits next to Loki and Prometheus in Grafana. Datadog, New Relic, Dynatrace and Honeycomb all accept OTLP too. Instrument with OpenTelemetry and the choice stays a config change.

> **In production.** Run the Collector as an agent on each node (or a sidecar) plus a central gateway for tail sampling. Strip personal data from span attributes in the Collector. Put trace IDs in every log line and return them in an `X-Request-Id` or `traceparent` response header, so support can turn a customer's complaint into a trace in seconds.

## Mission: Explain one slow request

Run Jaeger and HotROD, book four rides, and open the slowest trace. Write down: its total duration, the number of services and spans, the single slowest span and its share of the total, any spans marked as errors and their message, and one change that would make the request faster.

- You need: http://localhost:16686 and curl 'localhost:8080/dispatch?customer=123'
- You'll have: ~/trace-notes.txt

```sh
$ for c in 123 392 731 567; do curl -s -o /dev/null -w "%{time_total}s\n" "localhost:8080/dispatch?customer=$c"; done
$ curl -s localhost:16686/api/traces/<trace-id> > ~/trace.json   # the trace ID from Jaeger or a log line
```

On the lab the slowest trace took 960 ms across 6 services and 40 spans. The MySQL `SQL SELECT`
took 330 ms (about 34%). Three `GetDriver` spans failed with `redis timeout`. The best fix:
fetch the drivers from Redis in one batched call instead of fourteen calls in a row. Your numbers
will differ a little, the pattern won't.

## Try it

- Run Jaeger and open `http://localhost:16686`.
- Start HotROD, book a ride, and find the trace in Jaeger's Search page.
- Open the trace and name the span that takes the most time.
- Find a span marked with an error and read its tags and logs.
- Copy a trace_id from a HotROD log line and paste it into "Lookup by Trace ID".
- Do the mini mission and keep `~/trace-notes.txt`.

## Quiz

1. What is a span?
   - A whole request from start to finish across every service
   - **One timed operation inside a trace, such as one HTTP call or one SQL query, with a parent** (answer)
   - A log line with a timestamp
   Why: A trace is a tree of spans. Each span has a name, start time, duration, attributes and the ID of its parent, and all spans in a trace share one trace ID.

2. How does the cart service know it belongs to the same trace as the frontend that called it?
   - Jaeger guesses from the timestamps
   - **The frontend sends the trace ID and its span ID in the traceparent HTTP header** (answer)
   - Both services read the same database row
   Why: Context propagation passes the trace context with every call, using the W3C traceparent header for HTTP. The receiving service creates a child span with the caller's span as parent.

3. What does the OpenTelemetry Collector do?
   - It replaces Jaeger's UI
   - **It receives telemetry (often over OTLP), processes it, for example batching or sampling, and exports it to one or more backends** (answer)
   - It instruments your code automatically
   Why: The Collector is a pipeline of receivers, processors and exporters. Apps send to it, and you can change or add backends without touching application code.

4. In the lab trace, one request took 960 ms and the MySQL span took 330 ms. What does that tell you first?
   - **The database query is about a third of the whole request and the first place to look** (answer)
   - MySQL is down
   - The trace is broken
   Why: The waterfall shows where the time goes. A single span taking a third of the request is the biggest win, before micro-optimising anything else.

5. Why do busy systems sample traces instead of keeping all of them?
   - Jaeger can only show 100 traces
   - **Keeping every span of every request costs a lot of network, storage and money; a sample shows the same patterns** (answer)
   - Sampling makes requests faster
   Why: Head sampling keeps a fixed share decided at the start. Tail sampling in the Collector decides after the trace ends, so it can keep every slow or failed trace and only some of the fast ones.

## Resources

- [OpenTelemetry concepts (traces and spans)](https://opentelemetry.io/docs/concepts/signals/traces/) (OpenTelemetry)
- [Context propagation](https://opentelemetry.io/docs/concepts/context-propagation/) (OpenTelemetry)
- [W3C Trace Context (traceparent)](https://www.w3.org/TR/trace-context/) (W3C)
- [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/) (OpenTelemetry)
- [Zero-code instrumentation](https://opentelemetry.io/docs/zero-code/) (OpenTelemetry)
- [Jaeger getting started](https://www.jaegertracing.io/docs/latest/getting-started/) (Jaeger)
- [HotROD demo application](https://github.com/jaegertracing/jaeger/tree/main/examples/hotrod) (Jaeger on GitHub)
