Creating an implementation guide
I need to prepare an implementation guide for OpenTelemetry distributed tracing. It should include details on instrumentation, context propagation, trace/span semantics, exporters, sampling, and service maps. I want to provide concise configuration snippets for typical web and worker stacks, like Node.js/Express with workers or Python/FastAPI with Celery. I'll also address context propagation over HTTP and messaging queues, incorporating the W3C TraceContext and baggage header while explaining instrumentation methods.Drafting exporter and configuration details
I need to outline exporters like OTLP, Jaeger, and Zipkin, along with sampling approaches such as parent-based and traceidratio. Tail sampling will be included for the collector. I'll address service maps, requiring specific span kinds and attributes like peer.service and db.system, as well as baggage propagation while avoiding PII. Troubleshooting aspects should cover issues like missing spans and exporter errors. I'll provide configuration snippets and environment variables for both web and worker setups, presented in markdown format.Detailing collector configuration and semantics
I need to explain how the collector exports data to backends like Jaeger, Tempo, and Honeycomb. I’ll provide a sample collector configuration and clarify trace/span semantics. A trace consists of a tree of spans, and each span has a start and end time, along with context IDs and sampling flags. I’ll outline span kinds for web and worker interactions, ensuring proper linking and context propagation via headers or async context. Including correlation with logs may be useful for troubleshooting, even if it wasn’t specifically requested.Explaining service mapping and sampling
To ensure the service map functions correctly, I need to propagate context, use appropriate service.name, and set resource attributes. Some backends create the service map from CLIENT to SERVER spans. For messaging, I’ll highlight attributes like messaging.system and messaging.destination.name. I should recommend head sampling at the SDK and tail sampling at the collector for improved accuracy. Additionally, I’ll touch on exporters, provide configuration snippets for tail sampling, and mention troubleshooting steps for issues like context loss and missing instrumentation.Crafting the implementation guide
I want to provide a minimal configuration snippet for a typical stack, focusing on a "web" setup using FastAPI and a "worker" setup with Celery. I'll also include a configuration for Node with Express and Bull, sticking to the user's request for typical examples.
I’ll outline an overview and steps for setup, including environmental variables, auto-instrumentation instructions, and exporting to a collector, potentially using Jaeger or Tempo. I’ll ensure to cover aspects like trace/span semantics, instrumentation methods, and provide a structured response with code blocks. Keeping it concise while covering the essentials is key!
1) What “distributed tracing” means in OpenTelemetry (OTel)
- Trace: the end-to-end record of a request across services. Identified by a TraceId.
- Span: a timed operation within a trace (HTTP request, DB query, job execution). Identified by a SpanId and a ParentSpanId (except the root).
- Context: in-process container for the currently-active span + propagation state.
- Propagation: moving that context across process boundaries (HTTP headers, message headers, etc.) so downstream spans become children of upstream spans.
Span kinds (important for service maps and correct topology):
SERVER: handling an inbound request (web handler)
CLIENT: outbound request (HTTP client, DB client, cache client)
PRODUCER: publishing a message/job to a broker/queue
CONSUMER: receiving a message/job from a broker/queue
INTERNAL: internal function/step
2) Instrumentation and context propagation (web + worker)
A. Instrumentation strategy
- Auto-instrumentation first (fastest path): HTTP server/client, common DB drivers, Redis, messaging clients.
- Add manual spans only where you need semantic clarity (e.g., “charge-card”, “generate-pdf”, “reconcile-batch”) or to fill gaps.
Manual span pattern (language-agnostic):
- Start span → set attributes → record exceptions → set status → end span.
B. In-process context propagation
To keep the “current span” across async boundaries:
- Node: relies on
AsyncLocalStorage (must initialize SDK early)
- Python:
contextvars (must avoid losing context in thread pools unless instrumented)
- Java: context is handled by instrumentation (executors need instrumentation)
C. Cross-process propagation
HTTP: use W3C Trace Context by default:
traceparent / tracestate headers
Baggage: baggage header (optional; see §7)
Messaging/queues: you must inject/extract context into message metadata:
- Producer: inject into message headers/properties
- Consumer: extract and start a
CONSUMER span as child
If your queue system can’t carry headers, include traceparent (and optionally baggage) in the payload (be careful not to log it accidentally).
3) Exporters, Collector, and minimal config for “web + worker”
Recommended topology
Apps → OTel Collector → tracing backend (Jaeger/Tempo/Lightstep/Honeycomb/etc.)
Why: centralized retries/buffering, tail sampling, redaction, multi-export.
Minimal Collector config (otel-collector.yaml)
Receives OTLP (gRPC+HTTP), exports to a backend via OTLP, plus optional debug logging.
receivers:
otlp:
protocols:
grpc: { endpoint: 0.0.0.0:4317 }
http: { endpoint: 0.0.0.0:4318 }
processors:
batch: {}
exporters:
otlp:
endpoint: YOUR_BACKEND_OTLP_ENDPOINT:4317
tls:
insecure: true # set false + configure certs in real deployments
debug:
verbosity: basic
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlp, debug]
Minimal app-side config (environment variables)
Use these in both web and worker services:
# identity (shows up in UI + service map)
OTEL_SERVICE_NAME=orders-web # set differently for worker, e.g. orders-worker
OTEL_RESOURCE_ATTRIBUTES=deployment.environment=prod,service.version=1.2.3
# export to Collector
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
# propagation
OTEL_PROPAGATORS=tracecontext,baggage
# sampling (see §4)
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1
If you use gRPC OTLP from SDK, use endpoint otel-collector:4317 and protocol accordingly.
4) Sampling (head vs tail) and “don’t break traces”
Head sampling (in SDK)
Decides at trace start whether to record/export.
- Pros: simple, low overhead
- Cons: you can drop the interesting traces (errors) if unlucky
Common SDK sampler: ParentBased + TraceIdRatio
- Ensures child spans follow the parent decision (critical so traces don’t fragment).
Env var example already shown:
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1 (10%)
Tail sampling (in Collector)
Decides after seeing spans (e.g., “keep errors and slow traces”).
- Pros: keep the “right” traces
- Cons: more Collector memory/latency; needs careful sizing
Minimal tail-sampling snippet (add to Collector):
processors:
tail_sampling:
decision_wait: 10s
policies:
- 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 }
service:
pipelines:
traces:
receivers: [otlp]
processors: [tail_sampling, batch]
exporters: [otlp]
Rule of thumb: if you do tail sampling, often set SDK sampling to “always on” (or a high rate) and let the Collector decide.
5) Minimal “web + worker” snippets (typical stack)
Below are minimal examples showing (1) SDK init, (2) HTTP tracing, (3) queue propagation.
Option A: Node.js (Express web + worker publishing/consuming jobs)
Install
npm i @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node \
@opentelemetry/exporter-trace-otlp-http
otel.js (load before anything else)
const { NodeSDK } = require("@opentelemetry/sdk-node");
const { getNodeAutoInstrumentations } = require("@opentelemetry/auto-instrumentations-node");
const { OTLPTraceExporter } = require("@opentelemetry/exporter-trace-otlp-http");
const sdk = new NodeSDK({
traceExporter: new OTLPTraceExporter(), // uses OTEL_EXPORTER_OTLP_ENDPOINT
instrumentations: [getNodeAutoInstrumentations()],
});
sdk.start();
Web entrypoint
require("./otel"); // must be first
require("./server"); // express app
Queue propagation (generic)
Producer injects context into message headers:
const { context, propagation } = require("@opentelemetry/api");
function publish(queueClient, body) {
const headers = {};
propagation.inject(context.active(), headers);
return queueClient.send({ body, headers });
}
Consumer extracts context and runs handler under it:
const { context, propagation, trace } = require("@opentelemetry/api");
async function onMessage(msg) {
const ctx = propagation.extract(context.active(), msg.headers || {});
await context.with(ctx, async () => {
const span = trace.getTracer("worker").startSpan("job.process", { kind: 5 /* CONSUMER */ });
try {
// do work
} catch (e) {
span.recordException(e);
throw e;
} finally {
span.end();
}
});
}
Option B: Python (FastAPI web + Celery/RQ-style worker)
Install
pip install opentelemetry-distro opentelemetry-exporter-otlp \
opentelemetry-instrumentation-fastapi opentelemetry-instrumentation-requests
Web (auto-instrument run)
OTEL_SERVICE_NAME=orders-web \
opentelemetry-instrument uvicorn app:app
Worker (ensure it exports too)
OTEL_SERVICE_NAME=orders-worker \
opentelemetry-instrument python worker.py
Queue propagation idea (pseudocode)
- Producer: inject into message headers (dict)
- Consumer: extract from headers and start a
CONSUMER span
In Python you typically use:
opentelemetry.propagate.inject(carrier_dict)
opentelemetry.propagate.extract(carrier_dict)
(Exact hook points depend on your queue library; the key is “inject on publish, extract on consume”.)
6) Service maps (getting correct topology)
Service maps generally require:
- Consistent service identity
service.name differs per service (orders-web, orders-worker, payments, etc.)
- same
deployment.environment for grouping
- Correct span kinds
- inbound HTTP handler =
SERVER
- outbound HTTP call =
CLIENT
- publish job =
PRODUCER
- consume job =
CONSUMER
- Peer/service attributes (usually set by instrumentations)
- HTTP client spans should include destination attributes (
server.address, server.port, etc.)
- Messaging spans should include
messaging.system and destination name
If your map shows “unknown service” nodes, you’re usually missing:
- context propagation, or
- destination attributes on client spans, or
- proper
service.name on one side.
7) Baggage (cross-service key/value context)
What it is: small key/value pairs propagated with the request (baggage header) and readable by downstream services.
Use for:
- routing hints / feature flags (“tenant=…”, “plan=tier1”) if you truly need them everywhere
- attaching low-cardinality business context
Avoid:
- PII, secrets
- high-cardinality values (user ids) unless you’re sure about cost/risks
- large baggage (it bloats headers and can hurt performance)
Important: baggage is not automatically turned into span attributes everywhere; you typically must explicitly read it and set attributes if you want it searchable.
8) Troubleshooting checklist (most common failures)
“Traces don’t connect across services”
- Ensure both sides use the same propagators (
tracecontext,baggage).
- Verify headers exist:
- HTTP: check
traceparent is present on outbound and inbound
- Messaging: check your carrier is actually transmitted (message headers/properties)
- Make sure the worker uses ParentBased sampling; otherwise it may drop child spans and appear disconnected.
“Spans missing / only root span appears”
- Auto-instrumentation not loaded early enough (Node: require SDK before other imports).
- Unsupported library version (instrumentation doesn’t patch).
- Async context lost (custom thread pools/executors without instrumentation).
“Service map is empty/wrong”
- Wrong span kinds (everything INTERNAL).
- Outbound dependencies not instrumented (no CLIENT/PRODUCER spans).
- Missing destination attributes (peer info).
“No data in backend”
- Export endpoint wrong (
OTEL_EXPORTER_OTLP_ENDPOINT)
- Protocol mismatch (gRPC vs HTTP/protobuf)
- Collector not reachable from container network
- TLS issues (set correct
insecure/certs)
- Enable Collector
debug exporter temporarily to confirm it receives spans.
“Too much telemetry / high cost”
- Reduce head sampling ratio.
- Use tail sampling to keep errors/slow traces.
- Add span limits (events/attributes) and avoid high-cardinality attributes.
Minimal “golden rules” for a web + worker stack
- Run an OTel SDK in every process (web, worker).
- Use OTLP → Collector by default.
- Use W3C tracecontext propagation everywhere.
- For queues: inject on publish, extract on consume (don’t assume it’s automatic).
- Use ParentBased sampling to avoid trace fragmentation.
- Keep
service.name stable and unique per service.
If you share your language/runtime (e.g., Java/Spring + Kafka, Python/Django + Celery, Node/Nest + BullMQ, Go + NATS), I can provide exact minimal code/hooks for your HTTP server and message broker client.