SPANS · CONTEXT · THE SDK · THE COLLECTOR · SAMPLING · STORAGE

OpenTelemetry:
how distributed tracing is put together

A trace records one request’s path through every service it touched, each step a timed span. OpenTelemetry is the open standard and set of libraries that makes those spans, carries their context between services and ships them to a backend you choose.

The system on this page is the checkout of a concert-ticket shop. One click on Buy runs through a Python service that holds the seats in a Java service, charges the card through a Go service and puts a message on Kafka for the email worker. Each chapter follows that same click, and the later ones ask which of a thousand such clicks a second are worth keeping.

Here is the whole setup. Most boxes won’t mean much yet; each chapter explains one of them.

MapThe solid outline is the Kubernetes cluster; the dashed one is the internet outside it. Requests run across the top, and spans flow down and to the right, from the services to Grafana.

You need to know what an HTTP request, a process, a Kubernetes pod and a message queue are; no tracing background is assumed. The versions are OpenTelemetry specification 1.63.0, the Collector 0.166.0 and Tempo 3.1.1, checked on 3 December 2026. The shop and every duration, count and size on this page are a made-up example, chosen to be realistic; figures that show them carry an illustrative tag. If you build AI agents, AI agent tracing applies the same spans to model and tool calls, and its traceparent chapter is a shorter take on chapter 03 here. Tap any figure to open it full screen and zoom. Dotted terms are tappable.

Spans and traces: one checkout, one tree

One click on Buy takes 412 ms (an illustrative timing) and touches three services, a database, a card processor and Kafka. When it is slow or fails, each service’s logs show only its own part, and nothing says which part took the time. A trace is the record of that one request across all of them, and OpenTelemetry is the open standard that writes it. What does a trace of one checkout contain, and who writes it?

STEP 01 / 04

THE MAP SO FAR

Fig 1.1The accent chip is new: the tracer inside checkout. Faint parts arrive in later chapters.

A tracer is the OpenTelemetry object inside a process that creates spans, keeps track of the current one and stamps each with its trace id. On the map it sits in checkout, the Python service that handles POST /checkout, under its FastAPI handler.

Checkout is drawn in detail because every checkout trace starts there. Inventory, a Java service, and payments, a Go service, hold the same parts; the map leaves them out to stay readable. Nothing leaves a process yet: sending spans is chapter 05.

STEP 02 / 04

A TRACE IS A TREE OF TIMED SPANS

Fig 1.2Bars share one time scale; the accent row is the card processor call, inside payments, inside checkout.

A span is one timed operation: a name, a start time, a duration and the id of its parent span. A trace is every span of one request, all sharing one trace id. The root span, the one with no parent, covers the whole request.

Here is the hero checkout, with illustrative timings: 10 spans written by 3 services. The root, POST /checkout, lasts 412 ms. Payments’ call to the card processor takes 226 ms of it, 55%, inside payments’ POST /charges, inside checkout’s call to payments.

Indentation is parentage and bar length is time, on one scale for all three services. Each bar was timed by the machine that ran the work, and the tree puts them in order.

STEP 03 / 04

FIVE SPAN KINDS SAY WHO WAITS FOR WHOM

Fig 1.3Each pair of rows is one call seen from both ends; the accent pair is checkout calling payments.

A span kind says how a span relates to other processes. Every call between services is two spans: a CLIENT span in the caller and a SERVER span in the callee. Checkout’s POST to payments and payments’ POST /charges are one call seen from both ends.

Around a queue the pair is PRODUCER and CONSUMER: checkout’s order.placed send, and the email worker’s processing in chapter 04. Everything else, such as reserve-seats, is INTERNAL, the default.

The gap between the two ends is time on the wire and in queues. Checkout waited 248 ms for an answer that payments spent 241 ms producing, so 7 ms went somewhere in between.

STEP 04 / 04

ONE TRACE ID, WRITTEN BY THREE PROCESSES

Fig 1.4Three processes send their own spans; the accent trace id is what joins them later.

The 10 spans never sit in one place while the request runs. Checkout, inventory and payments each send the spans they wrote, separately, after each span ends. Every span carries the same 32-hex-digit trace ID, and the 16-hex-digit span ID of its parent.

A trace backend, the database that stores traces (Tempo, in chapter 08), joins them after the fact. The same trace ID puts spans in one trace; the parent ID puts each in its place in the tree. A span whose parent never arrives shows up as a gap or as a root of its own.

Most spans come from instrumentation, chapter 02. You can also open one by hand around a business step, as checkout does for reserve-seats; the code below shows the API.

A SPAN OPENED BY HAND IN CHECKOUT
from opentelemetry import trace

tracer = trace.get_tracer("checkout")

async def reserve_seats(order: Order) -> Hold:
    # One span for a step only this service knows about.
    with tracer.start_as_current_span("reserve-seats") as span:
        span.set_attribute("order.seats", len(order.seats))   # 2
        # The instrumented HTTP call inside becomes this span's child:
        # a CLIENT span "POST", whose SERVER side is inventory's "POST /holds".
        response = await inventory.post("/holds", json=order.hold_request())
        return Hold.from_response(response)

COMMON QUESTIONS

How is a trace different from a log line?
A log line is one event with no duration and no parent. A span has both, so a trace shows what ran inside what, and for how long.
Does creating spans slow the service down?
A span costs microseconds of CPU and a few hundred bytes. Sending and storing spans cost more, which chapters 05 and 07 deal with.
Where can I read about every field of a span?
The AI agent tracing tutorial’s chapter 01 walks through them, from the ids and times to attributes, events and links.

WHAT YOU NOW KNOW

  • A trace is every span of one request, joined by parent IDs under one 32-hex-digit trace ID; the hero checkout has 10.
  • Span kinds pair up across a call: CLIENT in the caller, SERVER in the callee, PRODUCER and CONSUMER around a queue.
  • Each process sends its own spans, and the backend assembles the tree from their IDs.
DEEP DIVE: span fields, an event or a child span, status, clocks

Span fields

A trace ID is 16 bytes and a span ID 8; neither may be all zeros. A span also holds a name, a kind, start and end times in nanoseconds since 1970, attributes (key–value pairs), events, links to spans in other traces, and a status.

By default the SDK keeps 128 attributes, 128 events and 128 links per span and drops the rest, counting what it dropped. OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT and its siblings change that. OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT has no default, so a long SQL statement is stored whole.

An event or a child span

An event is a timestamped note inside a span: a name and attributes, but no duration and no status. A child span has both. If you would ever ask how long a step took or whether it failed, make it a span; if it only marks that something happened, an event is enough.

Exceptions are the common event: record_exception still adds one. Semantic conventions have since deprecated exceptions on spans in favour of log records, and OTEL_SEMCONV_EXCEPTION_SIGNAL_OPT_IN switches instrumentations over.

Status

A span’s status is UNSET, OK or ERROR. Instrumentation sets ERROR and never OK; only your code or your configuration may mark a span OK, and once set it is final. UNSET counts as success. A parent never inherits a child’s error, and chapter 02 shows when an HTTP reply becomes one.

Clocks

Each span is timed by the clock of the machine that wrote it. If inventory’s node runs a few milliseconds behind checkout’s, POST /holds can appear to start before the CLIENT span that caused it. Keep every node on network time (NTP), let the backend correct what skew it can, and read gaps of a few milliseconds between machines as noise.

Instrumentation: where spans come from

The tracer can make spans, but nothing calls it yet. Checkout’s handler, its HTTP client, inventory’s SQL queries and payments’ handler would all need code that starts and ends a span with the right name and attributes. Writing that by hand in Python, Java and Go is slow, and three teams would name things three ways. What creates the spans in each service, and how do all three agree on what to call things?

STEP 01 / 05

THE MAP SO FAR

Fig 2.1The accent chip is the instrumentation: it calls the tracer from the previous chapter.

Instrumentation is code that wraps a library, such as FastAPI, a JDBC driver or Go’s net/http, so that each call through it becomes a span with the right name and attributes.

On the map it sits in checkout, between the FastAPI handler and the tracer. Inventory and payments carry it too, each in its own language’s way: the Java agent in inventory, the otelhttp package in payments.

STEP 02 / 05

THREE WAYS TO GET SPANS

Fig 2.2One column per service; the accent column is payments, where Go needs code.

Zero-code instrumentation loads when the program starts and needs no change to its code. Checkout runs under opentelemetry-instrument, which wraps FastAPI and the HTTP client before the app imports them. Inventory starts with -javaagent, and the Java agent rewrites supported libraries as their classes load.

Go compiles to one static binary, so nothing can attach at start-up. Payments uses library instrumentation instead: otelhttp.NewHandler wraps its handler and otelhttp.NewTransport its client for the card processor. Go’s zero-code options are OBI, which watches the process with eBPF, and otelc, which adds instrumentation at build time.

The third way is manual: a span you open yourself, like checkout’s reserve-seats. No library knows that holding seats is one business step, so only your code can name it.

CHECKOUT: SPANS WITH NO CODE CHANGES
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install   # instrumentations for the packages installed now

export OTEL_SERVICE_NAME=checkout
export OTEL_SEMCONV_STABILITY_OPT_IN=http   # stable HTTP attribute names
opentelemetry-instrument uvicorn checkout.main:app --host 0.0.0.0 --port 8000
PAYMENTS: OTELHTTP AROUND THE HANDLER AND CLIENT
func main() {
	// The tracer provider and the propagator are set up first (chapter 03).
	mux := http.NewServeMux()
	mux.HandleFunc("POST /charges", charge)

	// A SERVER span per request, named "POST /charges" from the route pattern.
	handler := otelhttp.NewHandler(mux, "payments")

	// A CLIENT span per call to the card processor, with traceparent written in.
	cardClient = &http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}

	log.Fatal(http.ListenAndServe(":8080", handler))
}
STEP 03 / 05

SEMANTIC CONVENTIONS NAME EVERY ATTRIBUTE

Fig 2.3Rows are inventory’s server span; the accent row keeps the span name low in variety.

Semantic conventions fix span names and attribute keys for HTTP, databases and messaging, so a Java span and a Go span use the same words. A server span is named {method} {route}: inventory’s is POST /holds.

The route is the template the framework matched, never the raw path. An endpoint such as /holds/{id} keeps one span name for every hold; the raw path would make a new name per hold and split every chart. Required keys are http.request.method, url.path and url.scheme; http.route and http.response.status_code join them when known.

Database spans follow the same idea: UPDATE seats carries db.system.name set to postgresql and db.query.text with each literal value replaced by ?, so the values stay out of the span.

STEP 04 / 05

A 4XX IS AN ERROR ONLY FOR THE CALLER

Fig 2.4The accent rows are the CLIENT spans, the callers that got a 402.

Span status is UNSET, OK or ERROR, set by the code that ends the span. Take an illustrative declined card: the card processor answers 402 to payments, payments answers 402 to checkout, and checkout answers 402 to the customer.

For a 4xx reply the conventions set ERROR on the CLIENT span and leave the SERVER span UNSET: the server did its job by refusing a bad request. So the two caller spans, checkout’s call to payments and payments’ call to the card processor, are ERROR, and both server spans stay UNSET.

A 5xx reply is ERROR on both ends. A call that gets no reply at all, such as a refused connection, is ERROR on the CLIENT span with an error.type attribute saying why.

STEP 05 / 05

service.name IS THE ATTRIBUTE YOU MUST SET

Fig 2.5The accent row names the service; unset, every Python service shares one name.

A resource is the set of attributes about the process rather than the request: service.name, service.version and deployment.environment.name. Every span the process sends carries it. Chapter 06 adds the pod and the node from outside the process.

Inventory sets its resource in its Deployment, below. Without a name, the Python SDK falls back to unknown_service:python3, the same for checkout and the email worker, so their spans merge into one service in every view.

OTEL_SERVICE_NAME wins over a service.name inside OTEL_RESOURCE_ATTRIBUTES. Keep the name the same in every environment, and let deployment.environment.name tell production from staging.

INVENTORY’S RESOURCE, SET IN ITS DEPLOYMENT
# inventory's container: who made the spans, and the Java agent that makes them
env:
  - name: OTEL_SERVICE_NAME
    value: inventory
  - name: OTEL_RESOURCE_ATTRIBUTES
    value: service.version=3.2.1,deployment.environment.name=production
  - name: OTEL_SEMCONV_STABILITY_OPT_IN
    value: database            # "UPDATE seats" with db.query.text, the stable names
  - name: JAVA_TOOL_OPTIONS
    value: -javaagent:/otel/opentelemetry-javaagent.jar

COMMON QUESTIONS

Can I mix zero-code and manual spans?
Yes. A manual span becomes a child of whatever span is current, so reserve-seats sits under checkout’s POST /checkout and holds the instrumented call to inventory.
Does the Java agent need code changes?
No. It loads with -javaagent, or through JAVA_TOOL_OPTIONS, and instruments supported libraries as their classes load.
On Kubernetes, can instrumentation be injected?
Yes. The OpenTelemetry Operator’s Instrumentation resource adds the agent for Java, Python and Node to a pod that carries its annotation. Go injection is off by default.

WHAT YOU NOW KNOW

  • Checkout and inventory get spans with no code changes; payments needs otelhttp because Go has no runtime agent.
  • Semantic conventions give every language the same span names and keys, such as POST /holds and http.route.
  • A 402 reply marks only the callers’ CLIENT spans as ERROR, and every service must set its own service.name.
DEEP DIVE: the Operator, Go without code changes, old and stable names, database spans, what lands in attributes

The Operator

The OpenTelemetry Operator (0.165.0) adds an Instrumentation resource to the cluster. A pod annotation such as instrumentation.opentelemetry.io/inject-java: "true" makes the Operator add the agent and its environment variables when the pod starts. Java, Python, Node and .NET are switched on by default.

Go is off until the Operator runs with --enable-go-instrumentation. It then needs the instrumentation.opentelemetry.io/otel-go-auto-target-exe annotation, runs a privileged container as root, and still uses the eBPF package the Go project has deprecated.

Go without code changes

OBI, OpenTelemetry eBPF Instrumentation, reached 1.0.0 as its first stable release. It runs beside the program as a privileged process or a DaemonSet and leaves the binary unchanged. Writing traceparent into outgoing requests is off by default (OTEL_EBPF_BPF_CONTEXT_PROPAGATION turns it on) and needs CAP_SYS_ADMIN.

otelc go build adds instrumentation at compile time instead, with no privileges at run time. The older go.opentelemetry.io/auto package is deprecated in favour of OBI.

Old and stable names

OTEL_SEMCONV_STABILITY_OPT_IN takes http for the stable HTTP names only, http/dup for both old and new while dashboards move over, and database for the stable database names. The Java agent writes stable HTTP names already; its stable database names sit behind otel.semconv-stability.opt-in=database. Build dashboards on the names you actually see in your spans.

Database spans

A database span is named by its query summary, such as UPDATE seats, or else by its operation and table. The PostgreSQL conventions are stable. db.query.text is recorded by default only when literal values are replaced; a parameterized query is kept as written, since its values travel separately.

What lands in attributes

Client spans record url.full, query string included, so a token passed in a URL lands in your traces. SQL text lands too, which is why the sanitizing matters. Check what your URLs and queries carry before you send spans to a shared backend.

FastAPI’s instrumentation also adds two internal spans per request, such as POST /checkout http receive and POST /checkout http send; exclude_spans=["receive", "send"] drops them, and OTEL_PYTHON_FASTAPI_EXCLUDED_URLS skips health checks. The FastAPI tutorial shows where in a request that instrumentation hooks in.

ERRORS THIS CHAPTER EXPLAINS

A service called unknown_service:python3
OTEL_SERVICE_NAME was never set
set it in the Deployment’s env block
A dashboard on http.response.status_code shows nothing for checkout
Python writes the older names by default
set OTEL_SEMCONV_STABILITY_OPT_IN=http
A new library’s calls make no spans
its instrumentation was never installed
run opentelemetry-bootstrap -a install again

Context propagation: one trace across HTTP

Each service now makes good spans, but each puts them in a trace of its own: payments has no way to know that its POST /charges belongs to checkout’s click. Something has to travel with the request and say which trace, and which span, it came from. What crosses the wire with each call, and what breaks the chain?

STEP 01 / 05

THE MAP SO FAR

Fig 3.1The accent parts are new: the propagator, and the two calls that now carry the trace context.

A propagator writes the current trace context, meaning the trace ID and the current span ID, into an outgoing request’s headers, and reads it back from an incoming one. Checkout’s propagator writes it onto the calls to inventory and payments, and theirs read it.

Every service carries one; the map draws checkout’s. The ingress proxy in front of checkout carries none, and it must forward trace headers unchanged so that a caller’s context reaches checkout.

STEP 02 / 05

traceparent CARRIES FOUR FIELDS

Fig 3.2Follow 1 to 3: the accent hop carries the header, and its accent field becomes payments’ parent.

When checkout calls payments, its HTTP instrumentation opens the CLIENT span and the propagator writes the traceparent header: version 00, the trace ID, the CLIENT span’s ID and flags 01, meaning sampled. The format is W3C Trace Context Level 1, a W3C Recommendation that every OpenTelemetry SDK reads and writes.

Payments’ otelhttp handler reads the header and opens POST /charges in the same trace, with 5c0e9b7a3d2f1e64 as its parent. Only two IDs and a flag cross the wire; every attribute stays in the process that recorded it.

With the hero trace’s illustrative IDs, the header on this hop reads traceparent: 00-7d1c4a9e2f6b80d35e91a7c04b2f6e18-5c0e9b7a3d2f1e64-01.

STEP 03 / 05

BOTH SIDES MUST SPEAK THE SAME FORMAT

Fig 3.3Each row is a caller and a callee; the accent row is payments without a propagator, which splits the trace.

Both ends of a call must use the same header format. The default, OTEL_PROPAGATORS=tracecontext,baggage, writes and reads traceparent and baggage; checkout and inventory use it without any setting.

Go is the exception: its global propagator does nothing until otel.SetTextMapPropagator is called. Without that call, payments’ otelhttp neither reads nor writes headers, so every charge starts a new trace, and checkout’s CLIENT POST has nothing under it.

The same split happens when a B3 header, the older Zipkin format some service meshes still send, meets a reader that only knows tracecontext. Adding b3 to the reader’s OTEL_PROPAGATORS lets it take both.

PAYMENTS: THE PROPAGATOR, SET IN MAIN
func initPropagation() {
	// The global propagator does nothing until it is set.
	otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{}, // traceparent and tracestate
		propagation.Baggage{},      // baggage
	))
}
STEP 04 / 05

INSIDE A PROCESS, CONTEXT FOLLOWS THE CALL

Fig 3.4The accent span started with an empty context, so it became a trace of its own.

Inside a process, the current span lives in the context: a per-request slot from which the next span takes its parent. Python keeps it in a contextvars variable, Java in a thread-local, and Go in the context.Context value you pass to each function.

In Go nothing is implicit. Payments starts a fraud check in a goroutine and passes it context.Background(), an empty context, instead of the request’s. The check’s span, score-fraud (35 ms, illustrative), finds no parent and becomes the root of a new one-span trace.

Other runtimes do part of this for you. The Java agent wraps thread pools so their tasks carry the context. Python’s asyncio tasks copy it, while a plain thread starts empty unless the threading instrumentation is installed; opentelemetry-bootstrap adds it by default.

STEP 05 / 05

BAGGAGE TRAVELS FURTHER THAN YOU MEANT

Fig 3.5Baggage set in checkout rides every hop; the accent hop leaves the shop.

Baggage is a second header, baggage, that carries key–value pairs to every service downstream. Checkout sets one entry, order.id=ord_5521 (illustrative), and every instrumented call copies it: to inventory, to payments, and from payments to the card processor outside the shop.

The W3C format allows 64 entries and 8,192 bytes in all. Baggage is not copied onto spans unless a span processor does it, and it has no integrity check: any hop can read it, change it or add to it.

Use it for a value every service needs, such as a tenant or a test flag, and remove the header at the edge where calls leave your network.

COMMON QUESTIONS

What does the ingress proxy do with the header?
A proxy that isn’t traced must pass traceparent on unchanged. A proxy that traces itself adds a span of its own and sends that span’s ID on as the parent.
Should checkout trust a traceparent from the internet?
Not blindly: a client can choose the trace ID and the sampled flag. Many shops start a new trace at the edge and keep the incoming one as a link.
What is tracestate?
A second W3C header for vendor and sampling data, up to 32 entries. OpenTelemetry’s probability sampler writes its threshold there, as ot=th:….

WHAT YOU NOW KNOW

  • traceparent carries the trace ID, the caller’s span ID and the sampled flag; the callee’s SERVER span takes that span as its parent.
  • Both sides must use the same propagator; Go’s does nothing until otel.SetTextMapPropagator is called.
  • Inside a process the context must be passed on, or a goroutine or pool thread starts a new trace.
DEEP DIVE: tracestate, Level 2 and the random flag, B3 and service meshes, untrusted context at the edge, async Python and threads

tracestate

tracestate travels beside traceparent as a list of key–value entries, at most 32, each owned by one tracing vendor or system. A service updates only its own entry and moves it to the front; when the list grows too long, the longest entries are dropped first. OpenTelemetry’s own key is ot.

Level 2 and the random flag

Trace Context Level 2 adds a second flag bit, 02, meaning the right-most seven bytes of the trace ID are random. Level 2 is still a Candidate Recommendation Draft, not a Recommendation, but OpenTelemetry’s probability samplers already rely on that randomness to make the same keep-or-drop decision in every service.

B3 and service meshes

B3 comes in two shapes: one b3 header (OTEL_PROPAGATORS=b3) or several X-B3-* headers (b3multi). A B3 propagator reads both and writes the single header unless told otherwise. A service mesh whose sidecars add spans of their own must use the same propagator as the services, or each sidecar starts a fresh trace.

Untrusted context at the edge

A traceparent from the internet is input like any other. A client can force the sampled flag on every request, or reuse one trace ID to pile unrelated requests into it. At the edge, ignore incoming context from untrusted callers and start a new trace, or keep the caller’s trace as a link rather than a parent.

Async Python and threads

An asyncio task copies the context when it is created, so spans opened inside it find their parent. A threading.Thread or a ThreadPoolExecutor job starts with none, unless the threading instrumentation is active: it carries the context into new threads and makes no spans of its own.

Without it, pass the context by hand with contextvars.copy_context().run(fn). The AI agent tracing tutorial follows the same context through async agent code and groups traces into sessions.

ERRORS THIS CHAPTER EXPLAINS

A CLIENT span with no SERVER span under it
the callee never read the header: no propagator set, a different format, or a proxy dropped it
match the propagators on both sides
Many one-span traces such as score-fraud
work started with an empty context
pass the request’s ctx to the goroutine

Through a queue: producer, consumer and links

After the charge, checkout puts an order.placed message on Kafka and answers the customer. The email worker reads that message seconds later, when checkout’s request is long finished. There is no HTTP call between them to carry a header, and a span can’t sit inside a parent that ended seconds ago. How does the email’s work stay connected to the order that caused it?

STEP 01 / 04

THE MAP SO FAR

Fig 4.1The accent parts are new: the topic and the worker that reads it.

A Kafka topic, order.placed, now sits between checkout and a fourth service, the email worker, on the left of the map under the ingress proxy. Checkout writes one message to the topic for each order, and the worker reads them and sends the confirmation email.

Both ends are instrumented with the Python confluent-kafka instrumentation. Two more span kinds appear: a PRODUCER span is the sending side of a message, and a CONSUMER span the receiving side. The HTTP hops and the SDK parts stay as chapter 03 left them.

STEP 02 / 04

THE MESSAGE CARRIES TRACEPARENT IN ITS HEADERS

Fig 4.2Follow 1 and 2; the accent chip is the header the send span wrote.

A Kafka record carries headers, key–value pairs beside its key and value, and the broker stores and delivers them with it. When checkout calls produce(), the instrumentation opens a PRODUCER span, order.placed send, and the propagator writes that span’s traceparent into the record’s headers. In the illustrative example the send takes 4 ms.

The header holds checkout’s trace id and the send span’s id, 0b6d…. In the email worker, poll() returns the record and the instrumentation reads the header back, so the worker’s span knows which span sent the message. Step 3 shows what it does with that.

Both spans carry messaging attributes, under the older names this instrumentation still writes: messaging.system=kafka, messaging.destination=order.placed and messaging.operation. The consumer side adds messaging.kafka.partition and messaging.message.id, here order.placed.4.182337: topic, partition and offset.

CHECKOUT PUBLISHES THE ORDER
from confluent_kafka import Producer

# Under opentelemetry-instrument, the confluent-kafka instrumentation wraps
# Producer: each produce() opens a PRODUCER span "order.placed send" and
# writes its traceparent into the record headers.
producer = Producer({"bootstrap.servers": "kafka.shop:9092"})

def publish_order(order: Order) -> None:
    producer.produce(
        "order.placed",
        key=order.id,                        # ord_5521
        value=order.to_json().encode(),
    )
    producer.poll(0)                         # serve delivery callbacks
STEP 03 / 04

A LINK JOINS TWO TRACES WITHOUT NESTING THEM

Fig 4.3Two traces on one time axis; the accent arrow is the link, not a parent.

The worker doesn’t make its span a child of the send. It opens order.placed process, a CONSUMER span, in a new trace, c41e…5f60, and gives it a link to order.placed send: the send span’s trace id and span id, stored on the new span. A trace view shows a link as a jump to another trace, not as nesting.

In the example the process span starts 1.9 s after checkout answered and lasts 840 ms. As a child, it would keep checkout’s trace open until the email went out, though the customer had an answer after 412 ms. Because poll() leaves the process span current until the next poll, the worker’s call to the mail API (790 ms) becomes its child.

Links also fit batches. A span has at most one parent, so a consumer that handles many messages at once can’t point at every sender that way. It can carry one link per message, up to 128 by default.

THE EMAIL WORKER’S POLL LOOP
from confluent_kafka import Consumer

consumer = Consumer({
    "bootstrap.servers": "kafka.shop:9092",
    "group.id": "email-worker",
})
consumer.subscribe(["order.placed"])

while True:
    # poll() ends the previous "order.placed process" span and, for a message,
    # opens a new one: CONSUMER, in a trace of its own, linked to the send.
    msg = consumer.poll(1.0)
    if msg is None or msg.error():
        continue
    send_confirmation(msg.value())   # its POST to the mail API is a child span
STEP 04 / 04

CHILD OR LINK DEPENDS ON THE LIBRARY

Fig 4.4One row per library; the accent row is the email worker’s.

Whether you get a child or a link is the instrumentation’s choice. The Java agent’s kafka-clients instrumentation (2.34.0) makes the consumer’s process span a child of the send by default, so one trace runs from the click to the email. Python’s confluent-kafka instrumentation, the shop’s worker, makes a link and a new trace.

Python’s kafka-python instrumentation makes a child, order.placed receive, but that span ends when the record is handed to your code, before your handler runs. The handler’s time and its errors are not in it.

The messaging semantic conventions are still at Development stability. They make a link the default and allow a parent only for a single message. Today’s names are messaging.system.name and messaging.destination.name, with Kafka’s own keys under kafka.*; version 1.45.0 renamed the first and moved the Kafka keys. The Python instrumentation still writes the older names from step 2.

COMMON QUESTIONS

Why not keep one trace from click to email?
A child that starts seconds after its root makes the trace’s duration meaningless. A tail sampler (chapter 07) would also have to wait for the email before deciding on the checkout.
Does Kafka itself appear as a span?
No. The broker isn’t instrumented. The traces show the producer’s send and the consumer’s process, and the gap between them is the time the message spent in the topic.
How do I find the email for one order?
Open the email trace and follow its link back to the send, or put the order id on both spans as an attribute and search by it.

WHAT YOU NOW KNOW

  • Checkout’s PRODUCER span order.placed send writes traceparent into the Kafka record’s headers, and the email worker reads it back.
  • The worker’s CONSUMER span starts a new trace with a link to the send, so the email doesn’t stretch checkout’s 412 ms trace.
  • Kafka instrumentations differ: the Java agent makes a child, confluent-kafka makes a link, and kafka-python ends its span before your handler runs.
DEEP DIVE: the five messaging operations, batches and the recv span, attribute names in flux, other brokers

The five messaging operations

The messaging conventions name five operations. create and send are PRODUCER spans, although send becomes CLIENT when a separate create span carries the message’s context. receive is a CLIENT span around a pull, process is CONSUMER, and settle, an acknowledgement or a commit, is CLIENT.

The conventions name a span {operation} {destination}, such as send order.placed. The Python instrumentation predates that rule and writes order.placed send, so a query written from the conventions finds nothing in this shop.

Batches and the recv span

When consume() returns several records at once, the confluent-kafka instrumentation opens one order.placed process span for the whole batch, with one link per record. Every send that fed the batch is reachable from it.

Both poll() and consume() also open a short CONSUMER span named recv and start the process span while it is current. In the instrumentation’s source that makes recv the new trace’s root and the process span its child, which outlives it. A search for root spans in the worker finds recv, not the process span.

Attribute names in flux

Messaging conventions are not stable, so instrumentations keep the older names until they are. Where an instrumentation supports it, OTEL_SEMCONV_STABILITY_OPT_IN=messaging switches to the new names and messaging/dup writes both, which lets dashboards move over before the old names go. Build dashboards on the names your spans actually carry, and expect them to change once.

Other brokers

RabbitMQ, Amazon SQS and NATS follow the same pattern. The producer writes the trace context into the message’s own headers or attributes, and the consumer either continues the trace or links to it. On SQS the context travels in message attributes, which are limited in number per message, so check how many your messages already use.

The SDK pipeline: sampler, processor, exporter

Every service now writes connected spans, but they still sit in each process’s memory. Three parts of the SDK decide what happens next: the sampler decides whether a trace is recorded at all, the batch span processor decides when finished spans leave, and the exporter decides how and where they go. What happens to a span between end() and the network, and what goes wrong on the way?

STEP 01 / 04

THE MAP SO FAR

Fig 5.1The accent chips are the SDK’s export path; the lanes end at a Collector the next chapter explains.

The SDK inside each service holds three more parts, drawn as chips under checkout’s propagator: a sampler, a batch span processor and an OTLP exporter. Inventory, payments and the email worker hold the same three.

Each service’s exporter sends to the Collector agent on its own node, along the accent lanes into the band at the bottom of the map. Chapter 06 explains what the agent does with the spans.

STEP 02 / 04

THE SAMPLER DECIDES AT THE ROOT

Fig 5.2Each row is a case the sampler meets; the accent row is why a ratio on payments has no effect.

The sampler runs when a span starts and decides whether it is recorded. The default, parentbased_always_on, records every trace a service starts, and for a span with a parent it copies the parent’s decision. That decision travels as the sampled flag, the last field of traceparent: 01 for sampled, 00 for not.

With illustrative values: set OTEL_TRACES_SAMPLER=parentbased_traceidratio and OTEL_TRACES_SAMPLER_ARG=0.1 on checkout, and checkout records 10% of checkouts. Every service downstream follows the flag, so a kept trace is complete and a dropped one leaves no spans anywhere.

The same setting on payments changes nothing for calls from checkout. Each of those requests arrives with a remote parent, and ParentBased consults the ratio only for a span with no parent at all. This is head sampling: decided at the first span, before anyone knows whether the request fails.

STEP 03 / 04

A BATCH PROCESSOR SENDS EVERY FIVE SECONDS

Fig 5.3The accent queue holds finished spans until the next five-second tick.

A span processor receives every span as it ends. The batch span processor, the one zero-code setups install, puts it in an in-memory queue of up to 2,048 spans. A background thread sends what is waiting every 5 seconds, or sooner once 512 spans wait, in requests of up to 512 spans each.

When the queue is full, spans are dropped. Python’s SDK pushes out the oldest span to make room and logs Queue full, dropping Span. once per drop. The request that ended the span carries on as if nothing happened, so the log line is the only sign.

The simple span processor exports each span the moment it ends, on the thread that ended it, so every request waits for a network call. The AI agent tracing tutorial shows what one OTLP request contains.

STEP 04 / 04

PYTHON SENDS gRPC, JAVA SENDS HTTP

Fig 5.4One row per service; the accent row uses gRPC, unlike the Java one under it.

OTLP, the OpenTelemetry Protocol, has two transports: gRPC on port 4317, and protobuf over HTTP on port 4318, at the path /v1/traces. The Collector listens on both. Each SDK picks a default, and they differ: Python with opentelemetry-distro sends gRPC, while the Java agent and Node send http/protobuf.

Go has no default to inherit: main() builds either otlptracegrpc or otlptracehttp. A gRPC exporter pointed at port 4318, or an HTTP one at 4317, fails on every export: the service logs export errors, and the backend shows nothing.

The shop points every service at the agent on its own node. The Kubernetes downward API puts the node’s IP in an environment variable, and OTEL_EXPORTER_OTLP_ENDPOINT uses it with the port that matches the service’s protocol.

CHECKOUT’S EXPORT SETTINGS
# checkout's container (Python exports gRPC, so port 4317)
env:
  - name: NODE_IP
    valueFrom:
      fieldRef:
        fieldPath: status.hostIP     # the node this pod runs on
  - name: OTEL_EXPORTER_OTLP_ENDPOINT
    value: http://$(NODE_IP):4317
  - name: OTEL_TRACES_SAMPLER
    value: parentbased_always_on     # the default, written out
# inventory (Java agent, http/protobuf) uses http://$(NODE_IP):4318

COMMON QUESTIONS

Can I configure all this in one file?
Yes. OTEL_CONFIG_FILE points the SDK at a declarative YAML file, now mostly stable. When it is set, every other OTEL_* variable is ignored unless the file refers to it.
Why not export straight to the backend?
You can, but then every service carries the backend’s address, credentials and retry policy. The next chapter moves them to one place.
What is ProbabilitySampler?
The spec’s replacement for the trace-id ratio sampler, still in Development. It records its threshold in tracestate, so later stages can scale counts back up to the full traffic.

WHAT YOU NOW KNOW

  • The root service’s sampler decides, and every child follows the sampled flag in traceparent; a ratio set on payments changes nothing.
  • The batch processor sends every 5 s or at 512 spans, and drops spans once its 2,048-span queue is full.
  • Python exports gRPC to port 4317 and the Java agent HTTP to 4318: match the port to the protocol.
DEEP DIVE: sampler names, ProbabilitySampler and its threshold, export retries and timeouts, shutdown and flush, the declarative file

Sampler names

OTEL_TRACES_SAMPLER accepts always_on, always_off and traceidratio, the parentbased_* version of each, and jaeger_remote and xray, which fetch their rules from a server. OTEL_TRACES_SAMPLER_ARG gives the ratio as a fraction and defaults to all traces. Python falls back to parentbased_always_on when the name is one it doesn’t know.

ProbabilitySampler and its threshold

The spec deprecates the trace-id ratio sampler in favour of ProbabilitySampler, which compares the random last seven bytes of the trace id with a threshold. It writes the threshold into tracestate as ot=th:…, so a Collector downstream can count each kept span as the many it stands for. No sampler name selects it yet; Go offers it as an experiment under sdk/trace/x.

Export retries and timeouts

OTLP exporters retry transient failures, such as gRPC UNAVAILABLE or HTTP 429 and 503, with exponential backoff, while the queue keeps filling behind them. The spec’s export timeout, OTEL_BSP_EXPORT_TIMEOUT, defaults to 30 s; Python 1.45.3 reads the setting but doesn’t apply it to the export yet.

Shutdown and flush

The batch processor sends what is left in its queue when the tracer provider shuts down, and the Python SDK registers that shutdown for a normal exit. A process killed with SIGKILL loses the queue. In a script, a cron job or a serverless function, call force_flush() or shutdown() on the tracer provider before returning.

The declarative file

A configuration file starts with file_format: "1.2", the current schema, and nests the same choices: tracer_provider with its processors, exporter and sampler, and propagator. Keys ending in /development are not stable and may not work in every SDK. SDKs also lag the schema, so check which file format yours reads before copying an example.

ERRORS THIS CHAPTER EXPLAINS

Queue full, dropping Span.
Spans end faster than the exporter sends them, often because the agent is unreachable.
Fix the exporter’s endpoint first; raise the queue size only for real bursts.
Export errors in the service log, and nothing arrives at port 4317 or 4318
The exporter’s protocol doesn’t match the port it was given.
gRPC to 4317, http/protobuf to 4318.

The Collector agent: one per node

Each pod now sends spans to an address on its own node. Something must listen there: accept OTLP from every pod, say which pod and deployment each span came from, survive a burst without running out of memory, and forward the spans on. What does the Collector agent do to a span, in what order, and what happens when it can’t keep up?

STEP 01 / 04

THE MAP SO FAR

Fig 6.1The accent box is the agent: one pod on every node, receiving from every pod beside it.

The OpenTelemetry Collector is a separate program that receives telemetry, processes it in pipelines and exports it. Run as a DaemonSet, it puts one Collector pod on every node: the agent, drawn as the band under all the services. Every exporter from chapter 05 now has something to send to.

The shop runs the otelcol-k8s distribution, version 0.166.0. This chapter covers the agent’s two processors, memory_limiter and k8s_attributes; its load_balancing exporter is chapter 07.

STEP 02 / 04

A PIPELINE IS RECEIVERS, PROCESSORS, EXPORTERS

Fig 6.2Spans pass top to bottom; the accent processor is the one that must come first.

A Collector config defines components of three kinds. Receivers take data in: here otlp, on port 4317 for gRPC and 4318 for HTTP. Processors change it in order: memory_limiter, then k8s_attributes. Exporters send it on: load_balancing, to the gateways. A component only runs once service.pipelines.traces lists it, and that list sets the order.

memory_limiter comes first so it can refuse data before anything else holds it in memory. k8s_attributes comes before anything that batches, because it needs the incoming connection, and batching loses it. Batching sits on the exporter itself, as sending_queue with batch: {}, which the Collector project now recommends over a separate batch processor.

THE AGENT’S CONFIG
receivers:
  otlp:
    protocols:
      grpc: { endpoint: 0.0.0.0:4317 }
      http: { endpoint: 0.0.0.0:4318 }
processors:
  memory_limiter:              # first: refuse before memory runs out
    check_interval: 1s
    limit_percentage: 80
    spike_limit_percentage: 20
  k8s_attributes:
    filter:
      node_from_env_var: KUBE_NODE_NAME   # only the pods on this node
exporters:
  load_balancing:              # chapter 07: one gateway per trace
    routing_key: traceID
    protocol:
      otlp:
        tls: { insecure: true }
        sending_queue:
          batch: {}            # batching on the exporter, not a processor
    resolver:
      k8s: { service: otel-gateway.observability }
service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, k8s_attributes]
      exporters: [load_balancing]
STEP 03 / 04

K8S_ATTRIBUTES ADDS THE POD

Fig 6.3The rows under the line were added by the agent; the accent row names the pod.

A span reaches the agent with the service’s resource attributes, such as service.name, and nothing about Kubernetes. k8s_attributes takes the source IP of the incoming connection, finds the pod with that IP, and adds k8s.namespace.name, k8s.pod.name, k8s.deployment.name and k8s.node.name, plus the pod’s uid and start time.

For checkout’s spans, in the illustrative shop, that is pod checkout-7f9c6d5b8-x2kqp in namespace shop on node-a. The deployment name comes from the name of the pod’s ReplicaSet, with its hash suffix cut off. A query can now ask which pod a slow span came from, and checkout set none of it.

To look pods up, the agent’s service account needs RBAC permission to get, watch and list pods and namespaces. On an agent, node_from_env_var: KUBE_NODE_NAME limits that watch to its own node, so each agent keeps only its node’s pods in memory.

STEP 04 / 04

WHEN IT FALLS BEHIND, THE AGENT REFUSES OR DROPS

Fig 6.4Each row is a way spans stop at the agent; the accent row loses them without telling the sender.

Above its soft limit, which is the limit minus a spike allowance of 20% of it by default, memory_limiter refuses new data. The receiver answers gRPC UNAVAILABLE or HTTP 503, both retryable, and the SDK’s exporter tries again later. Nothing is lost while the sender keeps retrying and its own queue has room.

When the next hop is slow or down, the exporter keeps requests in its sending queue and retries them for up to 300 s. The queue holds 1,000 requests by default. Once it is full, new data is dropped with the log line Dropping data because sending_queue is full, and the sending service is never told.

So alert on the agent’s own metrics, served on port 8888: otelcol_exporter_enqueue_failed_spans counts spans lost to a full queue, and otelcol_receiver_refused_spans counts refusals. The names carry no _total suffix.

COMMON QUESTIONS

Sidecar or DaemonSet?
A sidecar per pod isolates teams but costs a Collector in every pod. A DaemonSet shares one per node and is the usual default.
Can the agent remove personal data from spans?
Yes, with the redaction or transform processors. The AI agent tracing tutorial builds a redaction pipeline in the Collector.
Is the Collector required?
No; an SDK can export straight to a backend. The Collector moves retries, credentials, Kubernetes metadata and sampling out of every service into one config.

WHAT YOU NOW KNOW

  • The agent runs one pod per node and processes spans in the order its pipeline lists, with memory_limiter first.
  • k8s_attributes adds the namespace, pod, deployment and node from the span’s connection IP, given RBAC to read pods and namespaces.
  • Over its memory limit the agent refuses and senders retry; once its 1,000-request queue is full, it drops spans and tells nobody.
DEEP DIVE: distributions, the batch processor, persistent queues, the Collector’s own metrics, resource detection, renamed components

Distributions

The Collector ships in several builds. otelcol is the core set; otelcol-contrib adds hundreds of components; otelcol-k8s, the shop’s, holds what a cluster needs and allows only OTLP exporters. ocb, the Collector builder, compiles your own from a list of modules.

A DaemonSet is one of the Kubernetes controllers; the Kubernetes tutorial shows how it places one pod on every node and replaces it when the node changes.

The batch processor

Older configs put a batch processor in every pipeline. The project announced its deprecation in November 2026: the startup warning comes in the release after 0.166.0, exporter batching becomes the default in early 2027, and the processor is due to go later that year. Move to sending_queue: { batch: {} } on the exporter; a pipeline with both logs a warning at startup.

Persistent queues

The sending queue lives in memory, so a restarted agent loses it. Point sending_queue.storage at a file_storage extension and the queue is written to disk and read back after a restart. On Kubernetes, give that directory a volume that outlives the pod, or the disk copy goes with it.

The Collector’s own metrics

The Collector serves its own metrics on port 8888, at /metrics. Besides the two in step 4, watch otelcol_exporter_queue_size against otelcol_exporter_queue_capacity; the scaling guide suggests adding capacity once it passes 60–70%. otelcol_processor_dropped_spans, in older dashboards, has been deprecated since Collector 0.110.0.

Resource detection

resource_detection adds attributes about the host or the cloud, such as the provider, Region and instance, from detectors like env, system, ec2 or eks. The shop’s agent leaves it out, since k8s_attributes already names the pod and the node. If you add it, know that a detector that fails stops the Collector from starting.

Renamed components

In 2026 several component names moved to snake case: the otlp exporter became otlp_grpc, otlphttp became otlp_http, and k8sattributes, loadbalancing, resourcedetection, spanmetrics and servicegraph gained underscores.

The old names still work as aliases that log a deprecation warning, so older configs and blog posts keep running. The otlp receiver kept its name.

ERRORS THIS CHAPTER EXPLAINS

Dropping data because sending_queue is full
The next hop is down or too slow, and the exporter’s queue filled up.
Fix the next hop, add agents or gateways, or use a persistent queue; alert on otelcol_exporter_enqueue_failed_spans.
data refused due to high memory usage
memory_limiter is above its soft limit, and senders get a retryable error.
Give the agent more memory, or find the service sending a burst.
Spans with no k8s.pod.name
k8s_attributes can’t read pods: its service account lacks RBAC, or it runs after something that batches.
Grant get, watch and list on pods and namespaces, and list it before any batching.

The gateway and tail sampling: keeping the traces that matter

At 1,200 traces a second, keeping every one costs 933.1 GB of storage a day in this illustrative shop. The sampler of chapter 05 could cut that at the root: a 10% ratio keeps one trace in ten. But it decides before anyone knows whether the card will be declined or the call will be slow, so it throws away most failures with the rest. How do you keep every failing and slow trace, and only a share of the healthy ones?

STEP 01 / 05

THE MAP SO FAR

Fig 7.1The accent parts are new: a routing exporter in each agent and the gateway tier behind it.

A gateway is a second tier of Collectors that receives from the agents and sees whole traces. The shop runs 3 gateway pods, otel-gateway-0 to otel-gateway-2, as a StatefulSet, the Kubernetes object that gives each pod a stable name. They are the band under the agents, and tail sampling runs there.

Inside each agent, the new load_balancing exporter, the last step of the agent’s pipeline from chapter 06, decides which gateway gets each span. It picks by trace id, so every span of one trace goes to the same gateway, whichever node it left from.

STEP 02 / 05

HEAD SAMPLING DECIDES BEFORE ANYTHING FAILS

Fig 7.2Two columns, the same rows; the accent row is the one head sampling can’t promise.

Head sampling is the SDK’s sampler from chapter 05: it decides at the root span, from the trace id alone. It is cheap, holds no state and stays consistent, because every child follows the sampled flag in traceparent. What it can’t see is the outcome.

In this illustrative shop 0.4% of traces fail, 4.8 a second. A 10% head ratio keeps 0.5 of them a second, picked at random by trace id, and drops the rest along with the healthy traces.

Tail sampling waits until a trace has finished, then decides on its spans’ status, duration and attributes. The price is memory to hold traces while it waits, and every span of a trace in one place. The two can be combined; the deep dive shows how.

STEP 03 / 05

EVERY SPAN OF A TRACE MUST REACH ONE GATEWAY

Fig 7.3Spans leave three nodes, and every accent lane ends at otel-gateway-1. Below, round-robin splits the same trace.

The hero trace’s spans leave from three nodes: checkout’s from the agent on node-a, inventory’s from node-b, payments’ from node-c. Tail sampling needs all of them in one gateway; otherwise each gateway judges a fragment.

The agents’ load_balancing exporter does this. With routing_key: traceID, the default for traces, it hashes each span’s trace id and sends the span to the gateway the hash picks. For 7d1c…6e18 that is otel-gateway-1, from every agent.

It finds the gateways through a resolver. The dns resolver reads the addresses of the headless Service otel-gateway.observability; the k8s resolver watches its EndpointSlices, which needs RBAC permission to read them.

STEP 04 / 05

POLICIES VOTE, AND A DROP VETOES

Fig 7.4One row per policy with the traces a second it keeps; the accent row keeps every failure.

The tail_sampling processor runs every policy on each finished trace, and each policy votes. drop-health votes drop for health checks on /healthz; errors votes sample for any span with status ERROR; slow for a trace over 1 s; baseline for 5% of trace ids.

The votes combine by one rule. Any drop vote drops the trace, whatever else voted. Otherwise any sample vote keeps it, and a trace no policy votes for is dropped. So the order of the policies doesn’t matter, and a failing health check is still dropped.

In the illustrative traffic, errors keep 4.8 traces a second and slow traces 13.2, 18 together. The baseline adds 59.1 from the healthy rest, for 77.1 of 1,200 a second, 6.4%. The hero checkout, 412 ms with no error, is kept only because the baseline picked its trace id.

THE GATEWAY’S TAIL SAMPLING POLICIES
processors:
  tail_sampling:
    decision_wait: 30s
    num_traces: 100000         # peak 2,000 traces/s x 30 s = 60,000, with room
    policies:
      - name: drop-health      # a drop vote overrules every keep vote
        type: drop
        drop:
          drop_sub_policy:
            - name: healthz
              type: string_attribute
              string_attribute: { key: http.route, values: [/healthz] }
      - name: errors
        type: status_code
        status_code: { status_codes: [ERROR] }
      - name: slow
        type: latency
        latency: { threshold_ms: 1000 }
      - name: baseline
        type: probabilistic
        probabilistic: { sampling_percentage: 5 }
STEP 05 / 05

THE BUFFER MUST HOLD EVERY TRACE FOR THE WHOLE WAIT

Fig 7.5Each bar is the traces one gateway holds at once; the accent bar passes the default limit.

The gateway holds each trace in memory for decision_wait, 30 s by default from its first span, then decides. num_traces, 50,000 by default, caps how many traces it holds at once. When the buffer is full, the oldest traces are evicted before their decision.

One gateway taking every trace needs traces a second times the wait: 1,200 × 30 s is 36,000 traces normally, which fits. At the on-sale peak, 2,000 × 30 s is 60,000, which doesn’t.

Routing by trace id splits the load across the 3 gateways: 12,000 traces each normally and 20,000 at the peak. The shop sets num_traces to 100,000 anyway, enough for the whole peak on a single gateway.

COMMON QUESTIONS

Why run the gateways as a StatefulSet?
Stable pod names keep the set of gateways steady. When replicas are added or removed, the hash moves some traces to another gateway mid-wait, and those traces are decided in pieces.
Do I need three gateways?
Not always. The Collector docs suggest one well-resourced tail-sampling gateway where it fits, because routing across several has caveats whenever the set of gateways changes.
Does tail sampling slow requests down?
No. It runs after the spans have left your services. It delays when a trace appears in the backend, by up to decision_wait.

WHAT YOU NOW KNOW

  • Head sampling at the root can’t see outcomes; tail sampling at the gateway keeps every error and every trace over 1 s.
  • load_balancing routes by trace id, so one gateway sees every span of a trace.
  • The buffer holds traces a second times decision_wait: 60,000 at the on-sale peak, over the default 50,000.
DEEP DIVE: policy types, late spans and decision caches, head then tail, the probabilistic sampler processor, where to start

Policy types

Besides the four the shop uses, tail_sampling has latency with an optional upper bound, attribute matches (string_attribute, numeric_attribute, boolean_attribute), rate_limiting in spans a second, bytes_limiting, span_count and ottl_condition for any OTTL expression. and, not, drop and composite combine others; composite shares a spans-a-second budget among sub-policies.

invert_match on attribute policies is deprecated. Write the same rule as a drop or not policy instead.

Late spans and decision caches

While a trace is still in the buffer, a span that arrives after the decision inherits it. Once the trace has been evicted, a late span starts over: it waits another decision_wait and is decided on its own, which leaves fragments in Tempo.

decision_cache remembers decisions after the spans are released. Its sampled_cache_size and non_sampled_cache_size are off by default, and the README says to make them much larger than num_traces. Set decision_wait above your slowest normal trace, and watch otelcol_processor_tail_sampling_sampling_late_span_age. The email worker’s spans are a trace of their own (chapter 04), so they never stretch checkout’s.

Head then tail

You can run both: a head ratio at the root cuts what leaves every service, and the gateway tail samples what arrives. Errors the head sampler dropped are gone for good, so keep a head ratio for routes where losing failures is acceptable.

Probability samplers can record their ratio in tracestate as ot=th:…, so backends can scale counts back up. tail_sampling writes it only with the processor.tailsamplingprocessor.usetracestate feature gate, which is alpha and off.

The probabilistic sampler processor

probabilistic_sampler is a stateless Collector processor that keeps a share of traces by hashing the trace id, so it needs no routing. Every Collector in one tier must use the same hash_seed, or each keeps different traces. Its modes are hash_seed (the default), proportional and equalizing, which accounts for sampling done upstream. It can’t see errors: it is head sampling, done in the Collector.

Where to start

The OpenTelemetry docs say a small rate often represents a high-volume system accurately, and that at tens of traces a second or fewer you may not need to sample at all. Start with errors and slow traces kept in full and a small baseline, then check the kept rate in otelcol_processor_tail_sampling_global_count_traces_sampled.

ERRORS THIS CHAPTER EXPLAINS

Traces in Tempo with parts missing
Spans of one trace reached different gateways: a plain load balancer in front of them, or the set of gateways changed mid-wait.
Route with load_balancing and routing_key: traceID; keep the replica count steady.
couldn't find the exporter for the endpoint ""
The k8s resolver may not read EndpointSlices.
Grant its service account get, list and watch on EndpointSlices.

Tempo: storing and finding traces

About 77.1 kept traces a second leave the gateways, 60 GB a day in this illustrative shop. They need a store that holds weeks of spans cheaply, returns one trace quickly when you have its id, and answers questions such as “which payments calls were slow?” without an id. Where do traces live, for how long, and how do you find the one you need?

STEP 01 / 04

THE MAP SO FAR

Fig 8.1The accent parts are the trace store, its bucket and the screen you read traces on.

Grafana Tempo is the trace store. It receives the kept traces from the gateways over OTLP, writes them to object storage and answers queries. The shop runs Tempo 3.1.1 in monolithic mode, every component in one process, on the map’s right edge with the S3 bucket s3://tickets-traces under it.

Grafana, at the top right, is the screen you read traces on: a search box, the waterfall of one trace, and links to other signals. It holds no traces itself; it asks Tempo.

STEP 02 / 04

TRACES ARE BLOCKS IN A BUCKET

Fig 8.2Spans enter on the left; the accent bucket holds every block older than the live-store’s window.

In monolithic mode, the default (-target=all), one Tempo process runs every component. First the distributor receives OTLP from the gateways. Next it hands the spans in-process to the live-store, which keeps recent ones searchable, with a write-ahead log on disk. Last the live-store flushes them as blocks to s3://tickets-traces.

A block is a set of Apache Parquet files, a column-oriented format; Tempo 3.1.1 writes vParquet5. A query reads the live-store for recent spans, typically the last half hour to an hour, and the bucket for the rest. A backend worker merges small blocks and deletes those older than block_retention, 336h (14 days) by default.

Tempo 3.0 removed the ingesters and the compactor that older guides describe. In microservices mode, Kafka sits between the distributor and a block-builder; monolithic mode needs no Kafka.

STEP 03 / 04

TRACEQL FINDS TRACES BY WHAT THEIR SPANS SAY

Fig 8.3Each row is a query and what it finds; the accent row searches inside the tree.

TraceQL is Tempo’s query language. A query in braces selects spans: resource. attributes describe the service, span. attributes the operation, and intrinsics such as span:duration and status are fields every span has. A trace matches when any of its spans does.

The first query finds payments spans over 2s; the second, spans whose HTTP status is >= 500. The third uses >>, “descendant”: an error span anywhere under a checkout span, such as the CLIENT spans of the declined card in chapter 02.

Grafana’s Tempo search runs these queries, and a trace id pasted into it opens one trace directly. The same lookups are on Tempo’s HTTP API, port 3200: /api/search and /api/traces/<trace id>.

THREE TRACEQL QUERIES
{ resource.service.name = "payments" && span:duration > 2s }

{ span.http.response.status_code >= 500 }

{ resource.service.name = "checkout" } >> { status = error }
STEP 04 / 04

SAMPLING CUTS THE BILL, NOT THE ANSWERS

Fig 8.4Two receipts on the same retention; the accent line is the day the tail sampler leaves.

Storage grows with the traces you keep times the days you keep them. Here a trace is 18 spans of 500 bytes as stored, illustrative values. Keeping all 1,200 traces a second is 933.1 GB a day, and 13.1 TB over 14 days.

After tail sampling, 77.1 traces a second make 60 GB a day and 839.3 GB over the same 14 days. Every error and every slow trace is still in the bucket. What is gone is most of the fast, healthy checkouts, which look alike.

COMMON QUESTIONS

Why not Jaeger?
Jaeger v2 is built on the Collector and stores in Elasticsearch, OpenSearch, Cassandra or Badger. It fits teams that already run one of those; spans, OTLP and sampling work the same way.
Can I send OTLP straight to a cloud service?
Yes. AWS X-Ray accepts OTLP over HTTP at xray.<region>.amazonaws.com/v1/traces, and most tracing vendors take OTLP too.
How do I open the trace a user reports?
Paste its trace id into Grafana’s Tempo search. Tempo fetches it by id from the live-store or from the blocks.

WHAT YOU NOW KNOW

  • Tempo keeps recent spans in a live-store and the rest as Parquet blocks in S3, 14 days by default.
  • TraceQL selects spans by attributes, duration, status and position in the tree.
  • Tail sampling turns 933.1 GB a day into 60 GB here, keeping every error and slow trace (illustrative).
DEEP DIVE: microservices mode, the metrics-generator, Jaeger v2, X-Ray and vendors, sizing

Microservices mode

Each component runs as its own deployment. Distributors write to Kafka, which is the write-ahead log; block-builders, one per Kafka partition, build blocks and flush them to the bucket; live-stores serve recent data; query-frontends split queries among queriers; a backend scheduler and its workers merge blocks and apply retention.

Data is written once. Tempo 2.x’s ingesters replicated every trace, so the same spans were stored several times over.

The metrics-generator

Tempo can compute span metrics and service graphs itself from what it receives, and remote-write them to Prometheus. It sees only the traces that reach Tempo, so behind a tail sampler it counts the sample. Run it or the Collector’s span_metrics connector, never both, or the series are duplicated. Chapter 09 uses the connector.

Jaeger v2

Jaeger v2 is a Collector distribution with Jaeger’s storage, query and UI parts; the UI listens on port 16686. It stores in Elasticsearch, OpenSearch, Cassandra, Badger or memory, with ClickHouse experimental. Jaeger v1 is deprecated and its client libraries are retired: instrument with OpenTelemetry and send OTLP to Jaeger.

X-Ray and vendors

X-Ray’s OTLP endpoint takes HTTP only, no gRPC, signed with SigV4 or carrying an X-Ray API key as a bearer token. The Collector adds either with its sigv4auth or bearertokenauth extension. Most vendors accept OTLP with an API key in a header.

The OpenTelemetry specification deprecated the Zipkin exporter in favour of OTLP, since Zipkin can receive OTLP itself.

Sizing

Tempo’s docs size storage as ingested bytes a day times retention days, the arithmetic of step 4. Compute follows ingest: monolithic mode suits low to moderate volumes, and in microservices mode you add distributors and queriers as ingest and query load grow, with one block-builder per Kafka partition.

Traces, metrics and logs: one request across all three

Tempo now holds 6.4% of traces, every failure among them. An alert on checkout’s error rate needs every request counted, though, and the on-call engineer usually starts from a graph or a log line, not a trace id. How do metrics, logs and traces point at each other, and where must the metrics be counted?

STEP 01 / 04

THE MAP SO FAR

Fig 9.1The accent parts turn spans into counts and tie log lines to traces.

The span_metrics connector, in the gateway, turns spans into request, error and duration metrics and sends them over OTLP to Prometheus. Loki stores log lines; the Collector agent on each node now also forwards the pods’ log lines to it.

Grafana, already on the map, now reads all three stores: Tempo for traces, Prometheus for metrics, Loki for logs. This chapter is about the links between them.

STEP 02 / 04

COUNT SPANS BEFORE YOU SAMPLE THEM

Fig 9.2Spans split in two; the accent branch counts every one before the sampler drops most.

A connector is a Collector component that is the exporter of one pipeline and the receiver of another. The gateway’s traces/in pipeline sends every span to two: span_metrics, which counts it, and forward, which passes it to traces/sampled, where tail_sampling runs before the exporter to Tempo.

Span metrics are traces.span.metrics.calls and the histogram traces.span.metrics.duration, one series per service.name, span.name, span.kind and status.code. The connector flushes them every 60 s through the metrics pipeline to Prometheus, which shows the names with underscores.

Order matters. Counted here, error rates describe all 1,200 traces a second. Counted after the sampler, they would describe the 6.4% it kept, where every error survives and most successes don’t.

THE GATEWAY’S PIPELINES: COUNT, THEN SAMPLE
connectors:
  span_metrics:
    exemplars: { enabled: true }
  forward: {}
exporters:
  otlp_grpc/tempo:
    endpoint: tempo.observability:4317
    tls: { insecure: true }
  otlp_http/prometheus:
    endpoint: http://prometheus.observability:9090/api/v1/otlp
service:
  pipelines:
    traces/in:
      receivers: [otlp]
      processors: [memory_limiter]
      exporters: [span_metrics, forward]   # every span, before sampling
    traces/sampled:
      receivers: [forward]
      processors: [tail_sampling]
      exporters: [otlp_grpc/tempo]
    metrics:
      receivers: [span_metrics]
      exporters: [otlp_http/prometheus]
STEP 03 / 04

AN EXEMPLAR LINKS A HISTOGRAM BUCKET TO ONE TRACE

Fig 9.3The accent bucket holds the hero checkout; its exemplar is one real request inside an aggregated count.

A histogram counts requests into buckets by duration, as the Prometheus tutorial explains. The hero checkout took 412 ms, so traces.span.metrics.duration counts it in the bucket from 400 ms up to 800 ms, along with every other checkout in that range.

An exemplar is a trace id attached to a metric point. With exemplars: { enabled: true }, the connector attaches the ids of a few spans it counted to each point, kept for one flush interval. One of them here is the hero trace, 7d1c…6e18.

In Grafana, exemplars are dots on the latency graph, and selecting one opens its trace in Tempo. This one opens because the baseline policy kept the hero trace. Prometheus stores exemplars only when started with --enable-feature=exemplar-storage.

STEP 04 / 04

THE TRACE ID ON A LOG LINE FINDS ITS SPAN

Fig 9.4The accent id is the same string in the log line and on the span.

Python’s logging instrumentation puts the current trace ID and span ID on every record as otelTraceID and otelSpanID, once you call LoggingInstrumentor().instrument(inject_trace_context=True). The Java agent puts trace_id and span_id in the logging MDC, a per-thread map that log patterns can print. The Python logging tutorial shows the setup.

Checkout’s JSON formatter writes them as trace_id and span_id, so its line for order ord_5521 carries 7d1c…6e18 and the root span’s id. The Collector agent on each node forwards the pods’ log lines to Loki.

That shared id is the whole correlation, the link between a log line and a trace. In Grafana, the Tempo data source’s “trace to logs” setting queries Loki for one span’s lines, and a link on Loki’s lines opens the trace. Neither store knows about the other.

COMMON QUESTIONS

Should I count with the Collector or Tempo’s metrics-generator?
One of them, never both. The generator sees only what reaches Tempo, so behind a tail sampler the counting has to happen in the Collector.
Do span metrics replace my Prometheus client metrics?
No. They give the rate, errors and duration of every span name without code. Business counters, such as seats sold, still come from your code.
Are log lines from a dropped trace useless?
No. They keep their trace id, which still groups one request’s lines across services; there is just no trace to open.

WHAT YOU NOW KNOW

  • span_metrics counts every span in the gateway, before tail_sampling, so rates describe all traffic.
  • An exemplar attaches the hero trace’s id to the 800 ms bucket, linking a graph to one request.
  • Log lines carry trace_id and span_id, so Grafana can jump between a span and its lines.
DEEP DIVE: the service graph, cardinality, adjusted counts, logs over OTLP

The service graph

The service_graph connector pairs each CLIENT span with the SERVER span under it into an edge, such as checkout to payments, with request, failure and duration metrics per edge. Grafana draws them as a map of which service calls which.

It is stateful: both spans of a pair must reach the same Collector. The agents’ routing by trace id already ensures that, so it runs in the gateway beside span_metrics.

Cardinality

Every distinct value of a dimension makes a new series. Span names must stay low-variety: POST /checkout, never a path with an order id in it. aggregation_cardinality_limit caps the series (no limit by default), and the overflow lands in one series marked otel.metric.overflow.

Each gateway also adds collector.instance.id, so the 3 replicas write separate series instead of overwriting each other. Prometheus’s side of this, histograms and why label values must stay few, is in the Prometheus tutorial.

Adjusted counts

Since contrib 0.148.0, span_metrics scales each span’s count by the adjusted count a probability sampler writes into tracestate (ot=th:…). That corrects counts after head sampling. Tail sampling writes no such value by default, one more reason to count before it.

Logs over OTLP

Log lines can also travel as OpenTelemetry log records, with the trace and span ids as fields of the record instead of text in the line. The Java agent exports logs over OTLP by default. In Python, the logging instrumentation installs a LoggingHandler that turns each record into one. The Collector then handles them like spans, in a logs pipeline of its own.

The whole picture

Every part from the nine chapters, numbered. Every numbered part has a row in the table below.

Numbers match the table below. Requests run across the top; spans run down from the services, through the agent and the gateway, to the stores on the right.
  1. 1tracer

    creates each span and keeps track of the current one

    runs in
    inside every service
    decides
    trace ID, span ID, parent, start and end time
    when wrong
    spans with no parent, each one a trace of its own
  2. 2instrumentation

    turns framework, HTTP and database calls into spans with standard names

    runs in
    inside every service, as an agent or a library
    decides
    span names, kinds and attributes
    when wrong
    a service with no spans, or raw URL paths as span names
  3. 3propagator

    carries the trace context across each call

    runs in
    inside every service, on both ends of a call
    decides
    the traceparent header written out and read back
    when wrong
    a CLIENT span with nothing under it, and the callee in a trace of its own
  4. 4Kafka instrumentation and span links

    carries the context inside a message and ties the consumer’s work to it

    runs in
    checkout’s producer and the email worker’s consumer
    decides
    the record headers, and a link from the consumer span to the send
    when wrong
    email work you can’t trace back to the order that caused it
  5. 5sampler

    decides when a trace starts whether it is recorded

    runs in
    the SDK of the service that starts the trace
    decides
    the sampled flag that every later service follows
    when wrong
    a sampling ratio set on payments that changes nothing
  6. 6batch processor and OTLP exporter

    queue finished spans and send them to the agent

    runs in
    inside every service
    decides
    batch size, send interval, protocol and port
    when wrong
    no spans arriving, and export errors in the service’s own log
  7. 7Collector agent

    receives spans on each node and adds the pod they came from

    runs in
    one pod on every node
    decides
    its memory limit, the Kubernetes attributes, where spans go next
    when wrong
    spans with no pod name, or a log line saying the send queue is full
  8. 8load-balancing exporter

    sends every span of one trace to the same gateway

    runs in
    inside each agent
    decides
    which gateway gets a span, by its trace ID
    when wrong
    kept traces with parts missing after tail sampling
  9. 9tail-sampling gateway

    keeps failing traces, slow traces and a share of the rest

    runs in
    a tier of gateway pods
    decides
    which whole traces are kept, after waiting for their spans
    when wrong
    errors missing from Tempo, or traces evicted before a decision at peak
  10. 10Tempo

    stores kept traces and answers searches

    runs in
    its own pod
    decides
    recent spans in memory, older ones as blocks, query results
    when wrong
    a trace ID that returns nothing
  11. 11object storage bucket

    holds trace blocks until retention ends

    runs in
    S3, or any store that speaks its API
    decides
    how many days of traces exist, 14 by default
    when wrong
    a storage bill that grows with every day of traces kept
  12. 12Grafana

    shows traces and links them to metrics and logs

    runs in
    its own pod
    decides
    the trace view, search, and the jumps between the three
    when wrong
    a trace with no way to open its log lines
  13. 13span-metrics connector

    counts every span into request, error and duration metrics

    runs in
    the gateways, before tail sampling
    decides
    one series per service, span name, kind and status
    when wrong
    error rates that describe the kept sample, not the real traffic
  14. 14Prometheus

    stores the span metrics and their exemplars

    runs in
    its own pod, receiving OTLP
    decides
    the series behind alerts and latency graphs
    when wrong
    a latency graph with no dots that open a trace
  15. 15Loki

    stores log lines that carry trace and span IDs

    runs in
    its own pod, fed by the agent
    decides
    which log lines belong to which span
    when wrong
    log lines that can’t be joined to their trace
  16. ·resource

    names the service, version and environment that made a span

    runs in
    every service’s SDK settings
    decides
    service.name, service.version, deployment.environment.name
    when wrong
    spans from unknown_service:python3, or two services merged under one name
  17. ·baggage

    carries extra values to every service downstream

    runs in
    the baggage header
    decides
    key–value pairs, which are not span attributes until you copy them
    when wrong
    internal values arriving at the card processor
  18. ·semantic conventions

    fix span names and attribute keys in every language

    runs in
    every instrumentation library
    decides
    names such as http.route and db.system.name
    when wrong
    a query that finds one language’s spans and misses the rest

THREE THINGS TO KEEP

  • A trace is one request’s spans from every service, joined later by a shared ID that travels with each call.
  • A trace breaks wherever that ID isn’t passed on, and nothing warns you when it happens.
  • Count every request before you sample, then keep the traces worth reading.
Read next. AI agent tracing for the same spans on model and tool calls, Prometheus for the metrics your span metrics become, and Logging in Python for the log lines your traces link to.

pass the context on, count before you sample