Columns › 5. Going live and operating › Part 23
Distributed Tracing in Practice: When to Add It, How to Design It, and How to Debug with It
鏈路追蹤怎麼做:什麼時候該上、怎麼設計、怎麼用它查問題
Distributed tracing answers where the time and the failures went across services. This article covers when it is worth adding, the span model and naming, context propagation over HTTP, gRPC and NATS headers with links, head versus tail sampling, Collector agent and gateway tiers, correlation with logs and metrics, and debugging an order stuck in pending.
In this article
- What this article solves
- Step 1: What kind of question a trace answers
- Step 2: When it is worth adding, and when logs plus a request ID are enough
- Step 3: The data model: trace, span and how they relate
- Step 4: Naming and attributes: follow the semantic conventions
- Step 5: Auto-instrumentation plus manual spans
- Step 6: Propagation over HTTP, gRPC and message headers
- Step 7: Sampling: head and tail
- Step 8: The Collector: agent and gateway tiers
- Step 9: Connecting logs and metrics to traces
- Step 10: A design checklist for starting from scratch
- Step 11: In practice: an order stuck in pending
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “Observability in Go: Logs, Metrics and Tracing”, built all three pillars: structured logs with log/slog, RED metrics exported to Prometheus, and OpenTelemetry (OTel) otelhttp stitching one request across services into a trace. That article covered how to wire tracing in. This one goes a level deeper and is only about tracing: when you actually need it, how to design and name spans, how context crosses a message queue, where the sampling decision belongs, how to deploy the Collector, and how to use traces to find the problem when something goes wrong.
What this article solves
Some time after the online shop went live, two reports arrived on the same day. The on-call alert said the p99 of POST /orders had risen from 300 milliseconds to 1.8 seconds; customer support said order A123 had been paid, yet the screen still showed pending.
Every service logs a request ID, but both problems cross services. An order request enters through api-gateway and passes through the order, inventory and payment services; the payment-completed event then travels back to order through NATS JetStream. A consumer handling that event no longer has the original HTTP request, so the request ID is gone too. Each log can tell you "what happened here", but none can tell you "where the time went, and at which hop the failure happened".
That is the question distributed tracing answers. This article covers, in order:
- Which questions traces answer and which logs answer, when tracing is worth adding, and when logs plus a request ID are enough.
- The data model: trace, span, parent and child, span kind, attributes, events, status and links.
- Naming and attributes that follow the semantic conventions, avoiding name explosions and personal-data leaks.
- How auto-instrumentation and manual spans divide the work.
- Context propagation over HTTP, gRPC and NATS/Kafka message headers, and choosing between a parent span and a link.
- Head versus tail sampling, with the cost and the right situation for each.
- Deploying the OpenTelemetry Collector as agent and gateway tiers, and choosing a backend.
- Connecting logs and metrics to traces, and finally one real investigation that ties it all together.
Why it matters
When a monolith breaks, one log and one stack trace usually find the cause. Once it is split into microservices, a single request passes through several services, queues and databases, and without tracing these five things become slow or impossible to find out:
- Which part is slow. Every service's logs say it is fine, yet the user waited two seconds. A trace draws the duration of every hop, so you can tell at a glance whether the payment provider is slow, the database is slow, or something is retrying.
- Where the error started.
api-gatewayreturns 500, but the real cause may be ininventory, three layers away. A trace marks the first failing span, so you do not have to line up several services' logs by timestamp. - Asynchronous flows join back up. Once an order is handed to the next service through NATS, the request ID is lost; put the trace context in the message headers and the consumer joins the same chain. A problem like "the order is stuck in
pending" is mostly solved this way. - Calls that should not be there become visible. One request hitting the database 50 times (N+1), the same downstream called twice, work done in sequence that could run in parallel: all of it is obvious on a trace's timeline and nearly invisible in logs.
- Shorter investigations. Metrics say "P99 went up", the trace says "which part is slow", and the logs say "what happened there". Joined by the trace ID, they locate the problem minutes after an alert, instead of several teams each searching logs for hours.
It has costs too: instrumentation, a Collector and storage, and sampling is a must at high traffic; and it only answers "where", while "why" still needs logs and metrics. So the point is not whether you have tracing, but to connect it as soon as requests start crossing services and queues.
First, a quick reference: find the row that matches your situation to see whether tracing is worth it, and why. Step 2 goes into detail.
| Scenario | Why tracing is needed | Example in the shop |
|---|---|---|
| A request passes through three or more services | Logs only show what happened inside one service; a trace shows which hop the time went to | Placing an order: api-gateway → order → inventory, payment |
| p99 rose, but every service's own metrics look normal | One hop is slow, or a downstream was retried several times; averaged metrics hide it | The payment provider is occasionally slow and order's retries stretch the whole request |
| The flow has asynchronous hops (events, queues) | A request ID easily breaks once it leaves HTTP; tracing carries the context in message headers and rejoins the chain | Order events travel over NATS to inventory to reserve stock |
| "It's stuck and we don't know where" | The last span in the trace points straight at the service and step it stopped in | An order stays in pending |
| There is a latency SLO and slow requests must be found | Tail sampling can keep exactly the failed and slow requests | Checkout must finish within 500ms |
| Several teams each own a few services | During an incident everyone talks about the same trace instead of piecing logs together | The payments and orders teams investigate together |
| A monolith or one or two services, low traffic | Not yet: a request ID already ties the logs together, and pprof finds hot spots in the code | Internal admin tools |
| You only want "how many, how fast" | No tracing needed: that is the job of metrics | Orders per minute, error rate |
As for timing, add it once there are several services or once events and queues appear, and at the latest before the first time nobody can say what is slow: instrumentation added after an incident cannot recover the data from it. It can be done in two steps: first auto-instrumentation (otelhttp, otelgrpc) with head sampling, which costs the least; then, once there is a latency SLO or errors must be kept, tail sampling in the Collector and manual spans around business steps.
Step 1: What kind of question a trace answers
In a tracing system, one order looks like the figure below. Each row is a span (a piece of work with a start and an end), indentation is the parent-child relation, and each bar is the span's time range; all spans share one trace ID, and together they form a trace.
Figure: UPDATE stock in inventory takes most of the time; the orders.created event is processed after the response has been sent, yet it still sits in the same trace.
This picture answers at a glance two things logs struggle with: where the time went (UPDATE stock) and who was waiting for whom (order waits for inventory.Reserve, api-gateway waits for order). You could piece the same story together from logs, but you would first have to find the logs of four services, filter them by request ID, sort them by timestamp yourself, and assume that every machine's clock agrees.
The three signals divide the work like this:
| Question | Best signal | Why |
|---|---|---|
What went wrong inside inventory for this request? | Logs | Details, error messages and values live in log fields |
What were the error rate and p99 of POST /orders today? | Metrics | Pre-aggregated numbers, cheap to query, good for alerting |
| When p99 rises, which part of which service took the time? | Traces | Only traces keep the timing structure and causality across services |
| Was this order's event processed, and how many times? | Traces + logs | Traces show how many attempts and which failed; logs say why |
| Why is the stock update for one SKU especially slow? | Traces + metrics | Traces find the slow span; metrics confirm whether it is widespread |
Tracing does not replace logs or metrics. It is good at exactly one thing: keeping the structure of a request as it crosses services. Its value therefore grows with the number of boundaries one request crosses.
Step 2: When it is worth adding, and when logs plus a request ID are enough
Tracing has real costs: every service needs the SDK, you must deploy a Collector and a storage backend, someone must maintain the sampling rules, and the data volume is not small. Not every system should go all in from day one.
Figure: first ask how many services one request crosses, then whether there are async hops or latency nobody can explain.
| Situation | Recommendation | Why |
|---|---|---|
| A monolith, or one or two services with low traffic | Logs + request ID + metrics | A request ID ties all the logs together; pprof finds hot spots in-process |
| Three or more services, mostly synchronous HTTP/gRPC | Light tracing: auto-instrumentation + head sampling | The main need is to see which hop is slow; auto-instrumentation barely touches code |
| Events, queues, sagas, an outbox or other async flows | Full tracing: header propagation + manual spans | The request ID breaks at the first async hop; only propagated trace context survives |
| A latency SLO, or a p99 nobody can explain | Full tracing + tail sampling | You want exactly the few slow and failing traces, which a random tenth may miss |
| Batch jobs and data pipelines where one job runs in one process | Usually not needed; use logs and pprof | There is no cross-service structure to keep |
A few signals that are easy to overlook:
- Latency questions go unanswered. The alert says p99 is up, the team spends half a day comparing dashboards across services and still cannot say which part is slow. This is where tracing pays off most directly.
- More async hops. “Message Queues and Event-Driven Design” and “Distributed Transactions: Sagas and the Outbox Pattern” spread a flow across several consumers; a request ID only travels along synchronous calls, so it breaks as soon as events pile up.
- Work across teams. When services belong to different teams, the "is it slow on your side or mine?" argument ends with one waterfall.
Conversely, while the system is small, getting the request ID and RED metrics from “Observability in Go: Logs, Metrics and Tracing” right is better value than rushing to deploy a full tracing stack. But once you know you will split into several services, wire in the SDK and propagation early: instrumenting during an incident cannot recover data from when it started, and every new service will be written in the image of the existing ones.
Step 3: The data model: trace, span and how they relate
The previous article introduced traces, spans and trace IDs. To design them well, you also need to know which fields a span carries and what belongs in each:
| Field | Content | Example in the order flow |
|---|---|---|
| Name | What this work is; the set of values must be bounded | POST /orders, inventory.v1.Inventory/Reserve |
| Kind | The role of this work in the call relationship | server, client, producer, consumer, internal |
| Parent span | What triggered this work | The parent of inventory's server span is order's client span |
| Attributes | Key-value pairs describing this run; high-cardinality values are fine | http.route, order.id, product.sku |
| Events | Something that happened at a point in time during the span | stock.reserved, an exception record |
| Status | Unset, Ok or Error | Error on a database failure |
| Links | Pointers to spans in other traces, not parent-child | A batch consumer linking back to each message's producer span |
Span kind is often ignored, yet it matters. Backends use it to work out calls between services, draw the service topology and compute latency per edge:
| Kind | Use | Example |
|---|---|---|
| server | Handling an incoming synchronous request | order handling POST /orders |
| client | Making a synchronous request and waiting | order calling inventory.Reserve, a SQL query |
| producer | Sending a message without waiting for the result | Publishing orders.created |
| consumer | Handling a received message | inventory handling orders.created |
| internal | A step inside the process, crossing no boundary | Computing shipping, building the response |
Status has one very practical rule: set Error only when the work itself failed; a business refusal does not count. Insufficient stock or a card declined by the issuer means the system correctly handled an unsuccessful business outcome; marking those as Error drowns the error-rate metric and tail sampling in perfectly normal events. OTel's HTTP semantic conventions follow the same idea: a server receiving a 4xx leaves the status Unset (the caller is at fault), while a client receiving a 4xx sets Error.
Events suit "something happened at this moment" without opening another span, such as "lock acquired" or "retry number 2". span.RecordError(err) is in fact just an event named exception.
Links are covered in Step 6 together with context propagation.
Step 4: Naming and attributes: follow the semantic conventions
Tracing backends group spans by name, compute latency distributions and build indexes on them. So span names, like the metric labels in the previous article, must come from a bounded set; anything that varies, such as an ID, goes in an attribute.
| Written as | Problem | Change to |
|---|---|---|
GET /orders/A123 | One name per order, so grouping stops working | Name GET /orders/{id}, attribute order.id=A123 |
reserve stock for A123 | Same as above | Name reserve stock, attributes order.id, product.sku |
send orders.A123.created | An ID in the subject explodes both name and destination | Subject orders.created; the ID goes in the payload or an attribute |
SELECT * FROM stock WHERE sku = 'X-1' | Full SQL as the name, possibly leaking data | A name like UPDATE stock; keep parameters out of traces |
handler, process | Too vague to tell which part it is | "Action + object", e.g. process orders.created |
For attribute names, prefer OTel's semantic conventions: HTTP uses http.request.method, http.route, http.response.status_code; databases use db.system.name, db.operation.name; messaging uses messaging.system, messaging.destination.name, messaging.operation.type. Backends and dashboards recognise these names, so switching tools does not break your queries. In Go, use the constants from the go.opentelemetry.io/otel/semconv/v1.xx.0 package rather than spelling strings by hand.
Business attributes (order.id, product.sku, payment.provider) have no standard, so keep one shared list within the team, follow the same style as the conventions (lower case, dot-separated), and avoid prefixes OTel already uses.
Two kinds of data must never go into attributes: personal data (names, phone numbers, addresses, email, full card numbers) and secrets (access tokens, API keys, passwords). Trace data usually lives under looser permissions and may be sent to a third-party platform. If you genuinely need a user ID, store a hash or an internal ID, and add another filter in the Collector in Step 8.
Step 5: Auto-instrumentation plus manual spans
Instrumentation comes in two kinds with a clear division of labour:
| Approach | Coverage | Strengths | Weaknesses |
|---|---|---|---|
| Auto | Every HTTP, gRPC, database and messaging client call | No change to business code; propagation included | Sees only technical boundaries, not business steps |
| Manual | The business steps you choose | Names and attributes carry business meaning | Code to write and maintain; too many become noise |
Cover every boundary with auto-instrumentation first, then add manual spans only to business steps you will want to see during an investigation. This is how the shop's services are wired:
package tracing
import (
"database/sql"
"net/http"
"github.com/XSAM/otelsql"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// GatewayHandler is for the public api-gateway: a traceparent from outside cannot be trusted,
// so it becomes a link, not the parent; health checks create no span.
func GatewayHandler(mux http.Handler) http.Handler {
return otelhttp.NewHandler(mux, "api-gateway",
otelhttp.WithPublicEndpointFn(func(*http.Request) bool { return true }),
otelhttp.WithFilter(func(r *http.Request) bool { return r.URL.Path != "/healthz" }),
)
}
// NewGRPCServer turns every RPC in order, payment and inventory into a server span.
func NewGRPCServer() *grpc.Server {
return grpc.NewServer(grpc.StatsHandler(otelgrpc.NewServerHandler()))
}
// DialInventory writes the trace context into gRPC metadata on every call to inventory.
func DialInventory(target string) (*grpc.ClientConn, error) {
return grpc.NewClient(target,
grpc.WithTransportCredentials(insecure.NewCredentials()), // in-cluster sketch; use mTLS in production
grpc.WithStatsHandler(otelgrpc.NewClientHandler()),
)
}
// OpenDB wraps database/sql so that every query becomes a client span.
// driverName must be registered by a driver first, e.g. import github.com/jackc/pgx/v5/stdlib and use "pgx".
func OpenDB(driverName, dsn string) (*sql.DB, error) {
return otelsql.Open(driverName, dsn, otelsql.WithAttributes(semconv.DBSystemNamePostgreSQL))
}A few design choices:
api-gatewayis the public entry point, so an externaltraceparentmust not become the parent span. A malicious or misconfigured client could send atraceparentwith the sampled flag set, forcing you to keep its trace, or hang your spans under someone else's trace. WhenWithPublicEndpointFnreturns true,otelhttpstarts a new trace and only links back to the external context. Internal services keep using the parent span as usual.- Health checks should not produce spans.
/healthzis called every few seconds and would flood the backend with meaningless traces. - gRPC gets
otelgrpcthrough a stats handler, one on the server and one on the client;traceparentis written to and read from gRPC metadata automatically. - The database gets
otelsqlwrappingdatabase/sql, so every query is a client span. This pays off in Step 11: a lock wait shows up directly as one very long SQL span.
Manual spans go on business steps and keep "business not successful" apart from "system failed":
package tracing
import (
"context"
"errors"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
var ErrInsufficient = errors.New("insufficient stock")
// ReserveStock wraps a business step in a manual span; reserve is the function that writes to the database.
func ReserveStock(ctx context.Context, orderID, sku string, qty int64,
reserve func(context.Context) (bool, error)) error {
ctx, span := otel.Tracer("example.com/shop/inventory").Start(ctx, "reserve stock",
trace.WithAttributes(
attribute.String("order.id", orderID), // IDs go in attributes, not in the span name
attribute.String("product.sku", sku),
attribute.Int64("stock.quantity", qty),
))
defer span.End()
ok, err := reserve(ctx)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "reserve stock failed")
return err
}
if !ok {
// Insufficient stock is a normal business outcome, not a system failure: record an event, leave the status alone.
span.AddEvent("stock.insufficient")
return ErrInsufficient
}
span.AddEvent("stock.reserved")
return nil
}Which steps deserve a manual span? A simple test: if this step were slow or failing, would you want to see it directly in the waterfall? Reserving stock, authorising a payment and computing a discount qualify; a small function that only converts a string does not, and its time is naturally counted in the parent span.
Step 6: Propagation over HTTP, gRPC and message headers
Tracing crosses services through context propagation: the caller writes the current trace ID and span ID into the request, and the callee reads them and continues. The W3C Trace Context specification defines two headers:
traceparent:version-trace ID-parent span ID-flags, for example00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01. The trailing01means upstream decided to keep it (sampled).tracestate: extra vendor-specific information as a list of key-value pairs; ordinary code does not need to read or write it.
Figure: the same traceparent travels in an HTTP header, gRPC metadata and a NATS message header; the consumer chooses a parent span or a link depending on how it processes messages.
HTTP and gRPC are handled by the auto-instrumentation in Step 5. A message queue you wire yourself: OTel propagators read and write a carrier through the TextMapCarrier interface (three methods: Get, Set, Keys). OTel ships two: propagation.MapCarrier (map[string]string) and propagation.HeaderCarrier (http.Header). nats.Header is also a map[string][]string, but its keys are case-sensitive; converting it to HeaderCarrier canonicalises the key to Traceparent, and a consumer in another language looking for lowercase traceparent, as the specification says, will not find it. So write a small carrier for it:
package tracing
import (
"context"
"github.com/nats-io/nats.go"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
"go.opentelemetry.io/otel/trace"
)
// NATSCarrier lets a propagator read and write nats.Header directly.
// nats.Header keys are case-sensitive; no canonicalisation here, so the header stays lowercase traceparent.
type NATSCarrier nats.Header
var _ propagation.TextMapCarrier = NATSCarrier{}
func (c NATSCarrier) Get(key string) string { return nats.Header(c).Get(key) }
func (c NATSCarrier) Set(key, value string) { nats.Header(c).Set(key, value) }
func (c NATSCarrier) Keys() []string {
keys := make([]string, 0, len(c))
for k := range c {
keys = append(keys, k)
}
return keys
}
const scope = "example.com/shop/messaging"
var systemNATS = semconv.MessagingSystemKey.String("nats")
// StartPublish starts a producer span before sending and writes the trace context into the headers.
// The subject must come from a bounded set (such as orders.created); never put an order ID in it.
func StartPublish(ctx context.Context, msg *nats.Msg) (context.Context, trace.Span) {
ctx, span := otel.Tracer(scope).Start(ctx, "send "+msg.Subject,
trace.WithSpanKind(trace.SpanKindProducer),
trace.WithAttributes(
systemNATS,
semconv.MessagingDestinationName(msg.Subject),
semconv.MessagingOperationTypeSend,
))
if msg.Header == nil {
msg.Header = nats.Header{}
}
otel.GetTextMapPropagator().Inject(ctx, NATSCarrier(msg.Header))
return ctx, span
}
// StartProcess restores the upstream trace context from the headers and starts a consumer span as its child.
// Use it when one message triggers one piece of processing.
func StartProcess(ctx context.Context, msg *nats.Msg) (context.Context, trace.Span) {
ctx = otel.GetTextMapPropagator().Extract(ctx, NATSCarrier(msg.Header))
return otel.Tracer(scope).Start(ctx, "process "+msg.Subject,
trace.WithSpanKind(trace.SpanKindConsumer),
trace.WithAttributes(
systemNATS,
semconv.MessagingDestinationName(msg.Subject),
semconv.MessagingOperationTypeProcess,
))
}
// StartBatch starts a new trace for a batch of messages and links back to where each one came from.
// A span can have only one parent, but many links.
func StartBatch(ctx context.Context, subject string, msgs []*nats.Msg) (context.Context, trace.Span) {
links := make([]trace.Link, 0, len(msgs))
for _, m := range msgs {
mctx := otel.GetTextMapPropagator().Extract(ctx, NATSCarrier(m.Header))
if l := trace.LinkFromContext(mctx); l.SpanContext.IsValid() {
links = append(links, l)
}
}
return otel.Tracer(scope).Start(ctx, "process "+subject,
trace.WithNewRoot(),
trace.WithLinks(links...),
trace.WithSpanKind(trace.SpanKindConsumer),
trace.WithAttributes(
systemNATS,
semconv.MessagingDestinationName(subject),
semconv.MessagingOperationTypeProcess,
attribute.Int("messaging.batch.message_count", len(msgs)),
))
}A test with the in-memory exporter (go.opentelemetry.io/otel/sdk/trace/tracetest) proves that producer and consumer really share one trace, and that the consumer's parent is the producer span:
// fragment: part of tracing_test.go; useMemory installs tracetest.NewInMemoryExporter
func TestPublishAndProcessShareTrace(t *testing.T) {
exp := useMemory(t)
ctx, root := otel.Tracer("test").Start(context.Background(), "POST /orders")
msg := &nats.Msg{Subject: "orders.created", Data: []byte(`{"order_id":"A123"}`)}
_, pub := StartPublish(ctx, msg)
pub.End()
root.End()
if msg.Header.Get("traceparent") == "" {
t.Fatalf("traceparent not injected, header=%v", msg.Header)
}
// The consumer lives in another service and has only the message itself.
_, proc := StartProcess(context.Background(), msg)
proc.End()
spans := exp.GetSpans()
p := find(t, spans, "send orders.created")
c := find(t, spans, "process orders.created")
if c.SpanContext.TraceID() != p.SpanContext.TraceID() {
t.Fatalf("trace id differs: %s vs %s", c.SpanContext.TraceID(), p.SpanContext.TraceID())
}
if c.Parent.SpanID() != p.SpanContext.SpanID() {
t.Fatalf("consumer parent = %s, want producer %s", c.Parent.SpanID(), p.SpanContext.SpanID())
}
if p.SpanKind != trace.SpanKindProducer || c.SpanKind != trace.SpanKindConsumer {
t.Fatalf("kinds = %v, %v", p.SpanKind, c.SpanKind)
}
}Parent span or link? This is a decision to make when you design a message consumer:
| Situation | Approach | Why |
|---|---|---|
| One message triggers one piece of processing (most event consumers) | Producer span as parent | Processing is part of this order and reads best in the same waterfall |
| Pulling a batch of messages and processing them together | New trace, link back to each one | A span can have only one parent, but many links |
| The message starts a long, independent process (e.g. daily reconciliation) | New trace, link back | Squeezing it into the original trace would stretch it to hours and strain the backend |
| Webhooks or messages from external systems | New trace, link back | As with api-gateway, external context cannot be trusted |
A few practical details:
- With an outbox, store
traceparentin the outbox table together with the event (one extra column), and have the relay write it back into the message header when it publishes. The relay is a different process running at a different time; without the stored value the trace cannot be continued. - When JetStream redelivers, each delivery produces a new consumer span, all under the same producer span. That is actually helpful: the waterfall shows "processed five times, failed every time" directly.
- Kafka works the same way. A Kafka record's headers are a slice of key-value pairs; write a carrier with the same three methods for the header type of the client library you use.
Baggage is another header (baggage) that carries arbitrary key-value pairs down the call chain, such as tenant=shop-tw. It is convenient, but the risks are clear:
- It is carried automatically to every downstream call, including third-party APIs you call. Treat whatever you put in it as public.
- Every hop parses and forwards it, so larger values cost more.
- Downstream services treat it as trustworthy, but any upstream caller, including an external client, can forge it.
So keep baggage to a little non-sensitive routing information that downstream services genuinely need; do not put user IDs or permissions in it, and do not use it in place of proper API parameters.
Step 7: Sampling: head and tail
Keeping every trace is expensive: storage, network and backend indexing all grow with request volume. Sampling decides which ones to keep, and there are two places to decide:
Figure: head sampling decides at the start of the trace, cheaply but blindly; tail sampling waits for the whole trace, so it can pick out errors and slow traces, at the cost of Collector memory and sending everything.
Head-based sampling decides when the first span of a trace is created; the decision is written into the traceparent flags and downstream services follow it. The ParentBased(TraceIDRatioBased(0.1)) from the previous article is head sampling:
package tracing
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
)
// NewProvider builds the TracerProvider. The caller picks exp: OTLP in production, in-memory in tests.
// ratio is the share kept when this service starts the trace, e.g. 0.1 for ten per cent.
func NewProvider(ctx context.Context, exp sdktrace.SpanExporter, service, version string, ratio float64) (*sdktrace.TracerProvider, error) {
res, err := resource.New(ctx,
resource.WithSchemaURL(semconv.SchemaURL),
resource.WithAttributes(
semconv.ServiceName(service),
semconv.ServiceVersion(version),
),
resource.WithFromEnv(), // reads OTEL_RESOURCE_ATTRIBUTES, e.g. the deployment environment
resource.WithTelemetrySDK(), // records the SDK name and version
)
if err != nil {
return nil, err
}
return sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithResource(res),
// Follow the upstream decision if there is one; sample by trace ID only at the root.
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio))),
), nil
}
// Setup is called once from main. Endpoint and TLS come from OTEL_EXPORTER_OTLP_ENDPOINT and friends,
// not from code; put the returned shutdown in the shutdown sequence so buffered spans get sent.
func Setup(ctx context.Context, service, version string, ratio float64) (shutdown func(context.Context) error, err error) {
exp, err := otlptracegrpc.New(ctx)
if err != nil {
return nil, err
}
tp, err := NewProvider(ctx, exp, service, version, ratio)
if err != nil {
return nil, err
}
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{}))
return tp.Shutdown, nil
}ParentBased means "if there is an upstream decision, follow it". This matters: if every service sampled 10% on its own, then of the traces order keeps, inventory would keep only a tenth, leaving you with a pile of traces missing their second half. The tests check this behaviour directly: with the ratio set to 0, a span the service starts itself is not kept, but a span whose upstream traceparent carries the 01 flag still is.
The ratio is best a configuration value rather than hard-coded. The OTel SDK also honours the environment variables OTEL_TRACES_SAMPLER=parentbased_traceidratio and OTEL_TRACES_SAMPLER_ARG=0.1; note, however, that once the code calls WithSampler explicitly, the environment variables have no effect (a comment in the SDK source states that WithSampler overrides them). Pick one and do not mix them.
Tail-based sampling happens in the Collector: services send every span, the Collector buffers them, waits a while (decision_wait) for the whole trace to arrive, then decides by rules such as "any span has Error", "the whole trace took more than a second" or "keep 5% of the rest".
| Aspect | Head sampling | Tail sampling |
|---|---|---|
| Where it is decided | The SDK, at the start of the trace | The Collector, after the trace ends |
| Can it pick errors? | No, the outcome is unknown when deciding | Yes, every error and slow trace can be kept |
| Cost in the service | Low; unsampled spans cost almost nothing | Every span must be created and sent |
| Infrastructure cost | Low | The Collector buffers traces, needing memory and routing |
| Fits | High traffic, overall picture only, tight budget | A latency SLO, catching the few errors and slow requests |
When you combine them, raise the head ratio. Tail sampling can only choose from the spans it receives; if the head has already dropped nine tenths, the errors among them are never seen. The common setup is ParentBased(AlwaysSample()) (or a very high ratio) at the head so that every span reaches the Collector, and the tail decides what to keep. Only when traffic is so high that you cannot afford to send everything do you lower the head ratio a little, accepting that you will catch only some of the errors.
Tail-sampling memory is roughly "new traces per second × decision_wait × the size of a trace". At 500 traces a second with a 10-second wait, about 5,000 traces sit in memory at once; give num_traces plenty of headroom, or traces will be evicted before a decision is made. decision_wait also must not be much shorter than your slowest requests, or the slow part's spans will arrive after the decision.
Step 8: The Collector: agent and gateway tiers
The SDK could send data straight to the backend, but in practice almost everyone puts the OpenTelemetry Collector in between. It receives, processes and forwards, so a service only needs to know one local endpoint:
- Changing backend (from Jaeger to Tempo, or to a commercial platform) means changing Collector configuration, not redeploying services.
- Sampling, attribute scrubbing, retries and buffering live in one place.
- Sending returns quickly, so the service is never slowed down by backend latency.
Figure: services send to the agent on their node; the agent routes by trace ID to a gateway, which tail-samples and scrubs before exporting to the backend.
Why two tiers? Tail sampling must see the whole trace, but a trace's spans come from different services on different nodes. With several gateway replicas, one trace's spans would scatter across them, each replica would see only part of it, and decisions would be wrong. The fix is a first tier of agents using the load_balancing exporter, which sends every span of a trace to the same gateway by trace ID.
| Deployment | Fits | Watch out for |
|---|---|---|
| Agents only (one per node) | Head sampling only, modest scale | Configuration spread over every node; no tail sampling |
| Gateway only (one central group) | Few services, a single gateway | One replica is a single point of failure; more replicas need routing |
| Agent + gateway | Tail sampling with several gateway replicas | One more tier to run, but the clearest split of duties |
The first-tier agent (usually a DaemonSet on Kubernetes) only protects and routes:
# Tier 1: agent (one per node, a DaemonSet). Protects and routes only; makes no sampling decision.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
processors:
memory_limiter:
check_interval: 1s
limit_mib: 400
spike_limit_mib: 80
batch:
timeout: 2s
exporters:
load_balancing:
routing_key: traceID
protocol:
otlp:
tls:
insecure: true
resolver:
dns:
hostname: otel-gateway-headless.observability.svc.cluster.local
port: '4317'
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [load_balancing]The second-tier gateway tail-samples, scrubs attributes, then exports to the backend:
# Tier 2: gateway. All spans of one trace arrive at the same replica, which makes tail sampling possible.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
processors:
memory_limiter:
check_interval: 1s
limit_mib: 1600
spike_limit_mib: 320
tail_sampling:
decision_wait: 10s
num_traces: 100000
expected_new_traces_per_sec: 500
decision_cache:
sampled_cache_size: 1000000
non_sampled_cache_size: 1000000
policies:
- name: keep-errors
type: status_code
status_code:
status_codes: [ERROR]
- name: keep-slow
type: latency
latency:
threshold_ms: 1000
- name: baseline
type: probabilistic
probabilistic:
sampling_percentage: 5
attributes/scrub:
actions:
- key: enduser.id
action: delete
- pattern: ^card\..*
action: delete
batch:
send_batch_size: 8192
timeout: 5s
exporters:
otlp:
endpoint: tempo.observability.svc.cluster.local:4317
tls:
insecure: true
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, tail_sampling, attributes/scrub, batch]
exporters: [otlp]Key points of the configuration:
memory_limitergoes first. When memory nears the limit it refuses new data so that upstream backs off, instead of the Collector being killed and losing every buffered trace. The documentation recommends acheck_intervalof 1 second, aspike_limit_mibof about 20% oflimit_mib, and settingGOMEMLIMITas well.- The three
tail_samplingpolicies mean "keep if any one matches":status_codekeeps traces with an Error,latencykeeps traces longer than one second (measured from the earliest start to the latest end), andprobabilistickeeps 5% of the rest as a normal sample so you can see what "usual" looks like.decision_cacheremembers decisions already made, so late spans follow the same decision. attributes/scrubdeletes attributes that should not be there, such asenduser.idand every key starting withcard.. This is the last line of defence; the main responsibility is still not to write them in code.batchgoes last, packing data before export to cut network round trips.- Component names change between versions. In the Collector v0.165 source checked for this article, the OTLP gRPC exporter's type has been renamed
otlp_grpc, withotlpkept as the old name; the load-balancing exporter isload_balancing, formerlyloadbalancing. Check the documentation of the Collector version you deploy for which name to use.
Choosing a backend:
| Backend | Characteristics | Fits |
|---|---|---|
| Jaeger | A CNCF project, self-hosted, a UI focused on tracing, several storage options | Self-hosting, tracing only, a team at home with Elasticsearch-style storage |
| Grafana Tempo | Indexes only by trace ID, stores data in object storage, queried with TraceQL | Already using Grafana with Prometheus/Loki, large volumes, cost-sensitive |
| A cloud provider's tracing service | Managed, integrated with that cloud's other services | Everything runs in one cloud and you do not want to operate it |
| A commercial APM platform | Traces, metrics, logs and alerting in one place, usage-based pricing | Budget allows and you want to hand over operations |
Because the code depends only on the OTel API and the data travels as OTLP, this choice is reversible: changing backend touches only the Collector's exporter. That is the main reason to start with OTel rather than a single vendor's SDK.
The levers for cost control, in order: first, use tail sampling to cut normal traces to the share you need; next, check span counts, since opening a span on every loop iteration is a common source of blow-ups; finally, attribute size: never put whole request or response bodies in attributes. Set a retention period as well: most investigations finish within a few days of an incident, so trace data rarely needs to be kept as long as logs.
Step 9: Connecting logs and metrics to traces
The previous article said the three pillars should let you jump between them. Here the two connection points become testable code.
Figure: trace_id is the key shared by all three signals; the business attribute order.id lets a support question lead straight to a trace.
Put trace_id and span_id in logs. Wrap slog.Handler and take the current span from the context:
package tracing
import (
"context"
"log/slog"
"go.opentelemetry.io/otel/trace"
)
// TraceHandler wraps any slog.Handler and adds the current span's trace_id and span_id before output.
type TraceHandler struct{ slog.Handler }
func (h TraceHandler) Handle(ctx context.Context, r slog.Record) error {
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
r.AddAttrs(
slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()),
// An unsampled trace cannot be found in the backend; flag it so nobody follows a dead link.
slog.Bool("trace_sampled", sc.IsSampled()),
)
}
return h.Handler.Handle(ctx, r)
}
func (h TraceHandler) WithAttrs(as []slog.Attr) slog.Handler {
return TraceHandler{h.Handler.WithAttrs(as)}
}
func (h TraceHandler) WithGroup(name string) slog.Handler {
return TraceHandler{h.Handler.WithGroup(name)}
}As long as business code uses context-aware methods such as logger.InfoContext(ctx, ...), every log record carries trace_id automatically. Recording trace_sampled as well is a small but useful detail: a request not picked by head sampling still has a trace ID, but the backend has no trace for it, so the logging platform can show an "open trace" link only for records with trace_sampled=true. With tail sampling, the flag only means "was sent to the Collector"; whether the trace is finally kept is the Collector's decision.
Another option is OTel's slog bridge, go.opentelemetry.io/contrib/bridges/otelslog, which sends logs directly as OTLP with the trace context attached. The two can coexist: JSON on standard output for the existing logging system, OTLP for backends that support it.
Put exemplars on metrics. An exemplar is a "representative sample" attached next to a histogram bucket, carrying its trace ID:
package tracing
import (
"context"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/trace"
)
// ObserveWithTrace records a duration and, if the request is sampled, attaches its trace_id as an exemplar.
func ObserveWithTrace(ctx context.Context, o prometheus.Observer, seconds float64) {
sc := trace.SpanContextFromContext(ctx)
if eo, ok := o.(prometheus.ExemplarObserver); ok && sc.IsSampled() {
eo.ObserveWithExemplar(seconds, prometheus.Labels{"trace_id": sc.TraceID().String()})
return
}
o.Observe(seconds)
}Attach an exemplar only for sampled requests; otherwise clicking it opens a trace that does not exist. For exemplars to actually appear in Grafana, two more things are needed: /metrics must use the OpenMetrics format (promhttp.HandlerOpts{EnableOpenMetrics: true}), and Prometheus must enable exemplar storage (--enable-feature=exemplar-storage). Also, client_golang limits the total length of exemplar labels; a single trace_id is fine, but do not add anything else.
Put business attributes on spans. That is what order.id in Step 5 is for. When support says "order A123 is stuck", the TraceQL query { span.order.id = "A123" } in Tempo finds every related trace, including the synchronous order request and every later event-processing attempt.
Step 10: A design checklist for starting from scratch
The steps above, condensed into a checklist before a new service goes live:
| Item | Decision |
|---|---|
| SDK and resource | service.name, service.version and the deployment environment are set |
| Propagators | W3C Trace Context everywhere (plus Baggage, if used) |
| Auto-instrumentation | HTTP server and client, gRPC, database and messaging clients all wired in |
| Entry points | Public entry points use a link, not a parent; health checks create no span |
| Messaging | Producers inject, consumers extract; the outbox stores traceparent |
| Naming | Span names come from a bounded set; IDs in attributes; a shared list of business attributes |
| Sampling | The head ratio is a configuration value; raised when tail sampling is used |
| Personal data | No personal data or secrets in attributes; filter rules in the Collector |
| Correlation | trace_id in logs; exemplars on latency histograms |
| Shutdown | Call the TracerProvider's Shutdown before exit |
Step 11: In practice: an order stuck in pending
Back to the two reports from the start, now investigated with traces.
Figure: two apparently unrelated symptoms point to one root cause in the traces.
- Start from the alert. On the p99 latency graph for
POST /orders, there are a few exemplar dots next to the peak. Opening one shows the waterfall from Step 1:orderwaited 1.5 seconds forinventory.Reserve, and insideinventorythe SQL spanUPDATE stockalone took 1.4 seconds. Every other part, includingpayment.Authorize, looks normal. - Check whether it is widespread. Open a few more exemplars: the slow ones are all orders for the same SKU (same
product.skuspan attribute). That day there happened to be a flash sale. You now have a hypothesis: many orders updating the same stock row at once, waiting for the row lock. - Look up the stuck order. Searching
{ span.order.id = "A123" }finds two traces. The order request completed normally. The other is the trace in whichpaymentpublished thepayments.completedevent: under it are fiveprocess payments.completedconsumer spans, every one an Error, and nothing after the last. JetStream redelivered five times, stopped once the consumer's maximum delivery count was reached, and so the order stayed inpendingfor good. - Jump from the span to the logs. Click one failed consumer span and search the logs by its trace_id: when confirming the order,
order's consumer callsinventoryto turn the reservation into a deduction, and that call could not get the same row lock within its one-second timeout, returningcontext deadline exceeded. - Root cause and fix. Both symptoms have one cause: row-lock contention on a hot SKU. Orders were slow because reserving stock waited for the lock; the order got stuck because confirming stock waited for the same lock, and after timing out, all five retries hit the peak. The fix has three layers: in the short term, find orders that are still
pendingwith an event that has reached the maximum delivery count, and reprocess them; in the medium term, rewrite the stock deduction to hold the lock for less time, for example with the conditional update from “Concurrency Pitfalls: From Data Races to Overselling”; in the long term, alert when a consumer reaches the maximum delivery count, and following “Timeouts, Retries and Circuit Breakers”, add backoff to retries so they do not fire back to back during a peak.
Without tracing, these two reports would likely go to two people investigating separately, one looking at inventory's database and one at order's consumer, and it would take a long time to realise they were the same thing.
Common pitfalls
- A goroutine without ctx breaks the trace. Calling
go doSomething()in a handler without passing ctx makes any span inside a new root. When the work must outlive the request's cancellation but keep the trace, passcontext.WithoutCancel(ctx). - Consumers start spans from
context.Background(). Without first extracting the context from the message headers, every message becomes its own trace, and the waterfall shows only the synchronous part of the order. - Span names or subjects contain IDs.
GET /orders/A123ororders.A123.createddefeats the backend's grouping and indexing and drives up cost. Use patterns in names and put IDs in attributes. - Sampling drops the errors you need. A random tenth at the head means nine tenths of errors never reach the backend; or every service samples independently and traces are left half complete. Use
ParentBased, and when you need errors, switch to tail sampling and raise the head ratio. - Tail sampling in a single tier with several gateway replicas. One trace's spans scatter across replicas, each sees only part, and both
latencyandstatus_codepolicies misjudge. Put a tier that routes by trace ID in front. - Business refusals marked as Error. If insufficient stock and declined cards are all Error, the error rate and tail sampling drown in normal events and real failures become invisible.
- Clock skew. Span times come from each machine's own clock; a skew of a few tens of milliseconds can make a child span appear to start before its parent. Some backends try to correct for it, but the real fix is time synchronisation on every node. When the ordering looks impossible, suspect the clocks first.
- Personal data or secrets in attributes. Putting whole request bodies, authorisation headers or email addresses in attributes or baggage copies them into a system with looser access. Do not write them in code, and filter them in the Collector too.
- Forgetting Shutdown. The SDK sends in batches; without calling
Shutdownbefore exit, the last batch of spans is lost, and it is precisely the part just before the incident.
Key takeaways
- Logs answer "what happened here"; traces answer "where did the time and the failures go across services". Their value grows with the number of boundaries one request crosses.
- With one or two services, logs plus a request ID and metrics are enough; with three or more services, async flows, or a p99 nobody can explain, add tracing, and wire in the SDK and propagation early.
- Span names come from a bounded set and IDs go in attributes; prefer the semantic conventions for attributes; business refusals are not Error.
- Cover every boundary with auto-instrumentation; add manual spans only to business steps you would want to see when they are slow or failing.
- Message queues need you to inject and extract
traceparent; one-at-a-time processing uses a parent span, batches and long processes use links; the outbox storestraceparent. - Public entry points do not trust an external
traceparent; baggage carries only a little non-sensitive information. - Head sampling is cheap but blind; tail sampling keeps errors and slow traces at the cost of Collector memory and a two-tier deployment; raise the head ratio when using both.
- The Collector decouples services from the backend:
memory_limiterfirst,batchlast, and routing by trace ID in front of tail sampling. - trace_id in logs, exemplars on histograms and business attributes on spans are what let you jump between the three signals.
References
- Trace Context (W3C Recommendation): the
traceparentandtracestateformats and the sampled flag, used in step 6. - Traces (OpenTelemetry documentation): span kinds, attributes, events, status and links, used in step 3.
- Semantic conventions for HTTP spans (OpenTelemetry specification): HTTP attribute names and leaving the status unset on a server span for 4xx, used in steps 3 and 4.
- Semantic conventions for messaging spans (OpenTelemetry specification): messaging attribute names, producer and consumer spans, and links for batch processing, used in steps 4 and 6.
- Sampling (OpenTelemetry documentation): the difference and trade-offs between head and tail sampling, used in step 7.
- Gateway deployment pattern (OpenTelemetry documentation): using the load-balancing exporter to route by trace ID when there are several gateways, used in step 8.
- Tail Sampling Processor (OpenTelemetry Collector Contrib):
decision_wait,num_traces,decision_cacheand the sampling policies, used in steps 7 and 8. - Memory Limiter Processor (OpenTelemetry Collector): a recommended
check_intervalof 1 second,spike_limit_mibat about 20% of the limit, and settingGOMEMLIMIT, used in step 8.
Next
Trace data must be flushed before the program exits, and values such as the sampling ratio and the Collector endpoint should come from configuration rather than code. The next article, “Configuration and Graceful Shutdown in Go”, deals with both: where configuration comes from and how to validate it, and how to stop a service without dropping requests or losing trace data.