Observability and SREVol. 9 · Part IX
0 / 0

Shelves / Observability and SRE

OB·98

OpenTelemetry

OpenTelemetry end to end: why it exists, the API/SDK split, resources, the trace, metric and log data models, context propagation with W3C Trace Context and baggage, semantic conventions, OTLP, zero-code and manual instrumentation in Java, Go, Python, Rust and Node, the Collector (receivers, processors, exporters, connectors, pipelines, agent and gateway deployments, OTTL), exporters, head and tail sampling, configuration, and how to build a vendor-neutral telemetry pipeline.

32 topics · ~24 min read · 30-question quiz
Updated Suggest a correction

Start here: one standard from the code to any backend

The problem OpenTelemetry solves

Without a standard, instrumenting a service ties you to one vendor: their agent, their API, their wire format. Moving to another backend means touching every service. OpenTelemetry (OTel) separates the three concerns:

  1. What your code says: the OTel API (tracer.start_as_current_span("POST /pay")), the same whichever backend you use.
  2. How telemetry leaves the process: the SDK (sampling, batching, exporting) speaking OTLP, the OpenTelemetry Protocol.
  3. Where it goes: decided by configuration, usually in the Collector, a separate process that receives, cleans, enriches and forwards telemetry to one or many backends.

A Collector doing real work

Here is a payments service sending spans to a Collector that does four jobs before anything reaches Jaeger: drop health checks, add an environment attribute, hash email addresses, and mask anything that looks like a card number.

YAML
processors:
  filter/health:  {traces: {span: ['attributes["url.path"] == "/healthz"']}}
  resource:       {attributes: [{key: deployment.environment.name, value: lab, action: upsert}]}
  attributes/pii: {actions: [{key: user.email, action: hash}]}
  redaction:      {allow_all_keys: true, blocked_values: ['4[0-9]{12}(?:[0-9]{3})?']}

The service sent 300 root spans (100 health checks, 200 payments) with user.email = user7@example.com and payment.note = "card 4111111111111111 approved". What left the Collector:

Text
spans that left the Collector: 200
by name: {'POST /pay': 200}
resource: {'service.name': 'payments', 'service.version': '1.4.2', 'deployment.environment.name': 'lab'}
  user.email = b36a83701f1c3191e19722d6f90274bc1b5501fe69ebf33313e440fe4b0fe210
  payment.note = card **** approved
  redaction.masked.count = 1

None of that needed a change to the service's code. That's the point of a pipeline you control: privacy rules, cost filters and routing live in one place. The hashed email is still useful (the same user always hashes to the same value, so you can group by it) without the address being stored.

The trace context travels in one header

When orders calls kitchen, OpenTelemetry adds a W3C traceparent header so the downstream span joins the same trace:

Text
traceparent: 00-0fbc0f1759b40b5493dd1eddd3c0053e-713b32557c49d410-03
             ^  ^ trace ID (16 bytes)            ^ parent span ID  ^ flags
             version                                (8 bytes)        01 = sampled, 02 = random trace ID
baggage: tenant=acme

Baggage carries your own key-value pairs (a tenant, a feature flag) to every downstream service. It's sent on every call, so keep it small and never put secrets in it.

How deep to go in OpenTelemetry

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain the API, SDK, OTLP and Collector and why they're separate
L2 Instrument a service (zero-code plus manual spans) and send to a Collector
L3 Configure propagation, resources, semantic conventions, processors and sampling
L4 Diagnose broken context, dropped telemetry, and Collector pipeline problems from its own metrics
L5 Design an organisation's telemetry pipeline: agents, gateways, scrubbing, routing, multi-backend
L6 Run it as a platform: conventions, SDK distributions, Collector fleets, cost and compliance controls

Why OpenTelemetry exists

Before 2019, instrumentation was fragmented: each vendor shipped its own agents and APIs; open-source projects had to choose between OpenTracing (a tracing API standard) and OpenCensus (Google's tracing and metrics libraries). Switching backends meant re-instrumenting everything.

OpenTelemetry (OTel) merged the two in 2019 under the CNCF. It's now one of the most active CNCF projects, supported by essentially every observability vendor and cloud. It provides:

  • APIs and SDKs for traces, metrics, logs (and profiles, in alpha) in all major languages.
  • Automatic instrumentation for popular frameworks and libraries.
  • Semantic conventions: standard names for attributes (http.request.method, db.system.name, service.name).
  • OTLP: the OpenTelemetry Protocol for transmitting telemetry.
  • The Collector: a vendor-neutral agent/gateway to receive, process and export telemetry.

What OTel is not: a storage backend or a UI. You still need Prometheus, Tempo, Jaeger, Loki, a commercial platform, or similar.

Signal maturity (October 2026): traces, metrics and logs are stable in the major language SDKs (Java, .NET, Go, Python, JavaScript, C++, PHP; Rust and some others are close behind with some components still beta), profiles entered public alpha in March 2026, and the Collector is heading toward 1.0 (many components are already stable; its core configuration and APIs are being finalised).

Architecture

your process app code + instrumentation libs(HTTP, gRPC, JDBC, Kafka…) OTel API (vendor-neutral, no-op default) OTel SDKresource · sampler · processorsmetric readers · viewsbatching · OTLP exporterspropagators (W3C) Collectorreceiversprocessorsexporters OTLP metrics traces logs vendor X
OpenTelemetry's architecture. Application and library code call the vendor-neutral API; the SDK, configured once at startup, implements it: sampling, processing, batching and exporting via OTLP to a Collector (or directly to a backend). The Collector receives, processes and exports to any number of backends.

API versus SDK

  • The API is a thin, stable interface: get a Tracer, start a span, record a metric. Libraries depend only on the API. Without an SDK installed, the API is a no-op with negligible overhead, so library authors can instrument safely.
  • The SDK is the implementation, configured once by the application (or automatically by an agent): resource, samplers, processors, exporters, views. Swapping backends means changing SDK configuration, not code.

Resources

A resource describes the entity producing telemetry, attached to every span, metric and log from that process:

Attribute Example
service.name orders (the single most important attribute: set it!)
service.version 1.4.2 or Git SHA
service.namespace, service.instance.id shop, pod UID
deployment.environment.name prod
cloud.provider, cloud.region, cloud.availability_zone aws, ap-south-1
k8s.namespace.name, k8s.pod.name, k8s.deployment.name added automatically by resource detectors or the Collector's k8sattributes processor
host.name, container.id, process.runtime.name detected automatically

Resource detectors (environment, host, process, cloud metadata, Kubernetes) fill most of these; set OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=prod,service.version=1.4.2 in deployments.

Data models

  • Traces: spans with trace ID (16 bytes), span ID (8 bytes), parent span ID, name, kind (SERVER, CLIENT, PRODUCER, CONSUMER, INTERNAL), start/end time, attributes, events (timestamped annotations, e.g. exceptions), links (to spans in other traces, for batch and messaging), and status (UNSET, OK, ERROR).
  • Metrics: instruments (Counter, UpDownCounter, Histogram, Gauge, and asynchronous/observable versions) produce data points aggregated by the SDK; temporality is cumulative (Prometheus style) or delta (some vendors); views customise aggregation (bucket boundaries, dropping attributes to control cardinality); exemplars link to spans.
  • Logs: log records with timestamp, severity, body, attributes, and trace/span IDs from the active context. OTel's approach is to bridge existing logging libraries (Logback, Log4j, SLF4J, Python logging, Zap/slog, Serilog/ILogger, Winston/Pino) rather than invent a new logging API, so your existing log statements gain trace correlation and OTLP export.

Context propagation

Inside a process

The Context is an immutable bag carrying the active span (and baggage) through a call chain. Languages implement it differently:

Language How context flows
Java ThreadLocal-based Context.current(); the Java agent instruments executors, CompletableFuture, reactive libraries; virtual threads and structured concurrency inherit it via instrumentation
Go Explicit context.Context parameter: every function that should propagate tracing must accept and pass ctx
Python contextvars (works with asyncio tasks)
Node.js AsyncLocalStorage (async hooks)
.NET Activity.Current (AsyncLocal)
Rust tracing crate spans with Instrument for futures; opentelemetry context; explicit propagation across task spawns

Losing context at async boundaries (thread pools, callbacks, message queues, background tasks) is the most common cause of broken traces (chapter 101).

Across processes: W3C Trace Context

Between services, context travels in headers, standardised by the W3C Trace Context recommendation:

Text
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             │  └──────────── trace-id ────────────┘ └─ parent span ─┘ └ flags (01 = sampled)
             version
tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE       # vendor-specific extras
  • Propagators inject context into outgoing requests (HTTP headers, gRPC metadata, Kafka record headers, AMQP properties) and extract it from incoming ones.
  • Other formats exist for interoperability: B3 (Zipkin), Jaeger's uber-trace-id, AWS X-Ray's X-Amzn-Trace-Id; configure composite propagators (OTEL_PROPAGATORS=tracecontext,baggage,b3) while migrating.
  • The sampled flag lets downstream services honour the upstream sampling decision (parent-based sampling), so traces aren't half-recorded.
  • Security: treat incoming traceparent from the internet as untrusted (it can't be used to read data, but attackers can force sampling or correlate requests); many edges start a new trace and link to the incoming one.

Baggage

Baggage is a set of key-value pairs propagated alongside trace context (W3C baggage header) to every downstream service: e.g. tenant.id=acme, feature.flag=new-pricing, user.tier=gold. Services can read it to add attributes or make decisions.

Cautions: baggage is sent on every downstream request (keep it tiny), it's visible to all services and any third parties you call (never put secrets or personal data in it), and it isn't automatically added to spans (use a span processor to copy chosen keys).

Semantic conventions

Semantic conventions standardise attribute and metric names so that dashboards, alerts and backends work across languages and libraries. Examples:

Area Attributes / metrics (current stable names)
HTTP http.request.method, http.route (templated: /orders/{id}), http.response.status_code, url.full, server.address; metric http.server.request.duration (histogram, seconds)
Databases db.system.name, db.namespace, db.operation.name, db.query.text (sanitised), db.collection.name; metric db.client.operation.duration
Messaging messaging.system (kafka), messaging.destination.name, messaging.operation.type (send, receive, process), messaging.kafka.offset
RPC rpc.system (grpc), rpc.service, rpc.method, rpc.grpc.status_code
Exceptions exception.type, exception.message, exception.stacktrace
GenAI (experimental) gen_ai.operation.name, gen_ai.request.model, gen_ai.usage.input_tokens

HTTP semantic conventions were declared stable in 2023 (with renames like http.method → http.request.method); database conventions stabilised later. Instrumentation libraries let you opt into new names during migration (OTEL_SEMCONV_STABILITY_OPT_IN=http,database). The Weaver tool generates code and documentation from convention registries, including your own company-specific conventions.

Use templated routes (/orders/{id}), never raw paths, as span names and metric labels; otherwise every order ID becomes a new series.

OTLP

The OpenTelemetry Protocol encodes all signals as protobuf messages (resource → scope → spans/metrics/logs), sent over:

  • gRPC (default port 4317), or
  • HTTP/protobuf or HTTP/JSON (port 4318, paths /v1/traces, /v1/metrics, /v1/logs).

It supports compression (gzip), retries with backoff, and partial-success responses. Most backends now accept OTLP natively (Prometheus has an OTLP receiver; Jaeger, Tempo, Loki, and commercial vendors ingest it).

Instrumentation

Zero-code (automatic) instrumentation

Language Mechanism
Java Java agent (-javaagent:opentelemetry-javaagent.jar) rewrites bytecode for 100+ libraries (Spring, Servlet, JDBC, Kafka, gRPC, OkHttp, Netty, Lettuce…); Spring Boot starter as an alternative; Quarkus and Micronaut have built-in OTel support
.NET Automatic instrumentation via CLR profiler, or OpenTelemetry.Instrumentation.* packages
Python opentelemetry-instrument wrapper with auto-detected instrumentations (Django, Flask, FastAPI, requests, SQLAlchemy, psycopg…)
Node.js @opentelemetry/auto-instrumentations-node registered at startup (--require / --import)
Go No runtime bytecode rewriting; use instrumentation libraries (otelhttp, otelgrpc, otelsql) or eBPF-based zero-code instrumentation (OBI, OpenTelemetry eBPF Instrumentation, from Grafana Beyla's donation) and compile-time instrumentation tools
Kubernetes The OpenTelemetry Operator injects agents into pods via an annotation (instrumentation.opentelemetry.io/inject-java: "true") and manages Collectors

Zero-code instrumentation gives HTTP, database and messaging spans and metrics immediately; add manual instrumentation for business operations and attributes.

Manual instrumentation across languages

// Java: manual span + metrics on top of the agent (API only; the agent provides the SDK)
private static final Tracer tracer = GlobalOpenTelemetry.getTracer("com.acme.orders");
private static final Meter meter = GlobalOpenTelemetry.getMeter("com.acme.orders");
private static final LongCounter ordersPlaced = meter.counterBuilder("orders.placed")
        .setDescription("Orders successfully placed").setUnit("{order}").build();

public Order place(Cart cart) {
    Span span = tracer.spanBuilder("place_order").startSpan();
    try (Scope scope = span.makeCurrent()) {                       // child spans (JDBC, HTTP) nest under it
        span.setAttribute("order.item_count", cart.items().size());
        span.setAttribute("tenant.id", cart.tenantId());
        Order order = repository.save(pricing.price(cart));
        ordersPlaced.add(1, Attributes.of(AttributeKey.stringKey("payment.method"), cart.paymentMethod()));
        return order;
    } catch (Exception e) {
        span.recordException(e);
        span.setStatus(StatusCode.ERROR, e.getMessage());
        throw e;
    } finally {
        span.end();
    }
}

Instrumentation guidance:

  • Name spans for operations, low cardinality: place_order, GET /orders/{id}, SELECT orders, not GET /orders/9817.
  • Put high-cardinality details in attributes (order ID, tenant, user tier), where they're queryable without creating metric series.
  • Always end spans (finally/defer/context managers) and flush on shutdown (or the last batch is lost, especially in short-lived jobs and functions).
  • Record errors with recordException and set status ERROR; don't mark expected business outcomes (a 404 from a lookup) as errors on client spans unless they are.
  • Don't log and trace sensitive data: SQL parameters, request bodies, tokens; instrumentation libraries sanitise queries by default.

Configuration

The SDKs read standard environment variables, so deployments configure telemetry without code:

Shell
OTEL_SERVICE_NAME=orders
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=prod,service.version=1.4.2
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector.observability:4317
OTEL_EXPORTER_OTLP_PROTOCOL=grpc
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1
OTEL_PROPAGATORS=tracecontext,baggage
OTEL_METRIC_EXPORT_INTERVAL=30000
OTEL_LOGS_EXPORTER=otlp

Declarative configuration (a single YAML file describing the SDK: resource, processors, exporters, samplers, views; OTEL_CONFIG_FILE) was marked stable in 2026, giving one portable configuration format across languages.

The Collector

Pipelines

The OpenTelemetry Collector (Go) receives, processes and exports telemetry. A configuration wires components into pipelines per signal:

Component Role Examples
Receivers Get data in (push or pull) otlp, prometheus (scrape), filelog (tail files), kafka, hostmetrics, kubeletstats, k8s_cluster, jaeger, zipkin, syslog, cloud receivers
Processors Transform in flight memory_limiter (first!), batch, k8sattributes, resourcedetection, attributes, transform (OTTL), filter, redaction, tail_sampling, probabilistic_sampler, groupbyattrs
Exporters Send data out otlp/otlphttp, prometheusremotewrite, prometheus (expose for scraping), loki, kafka, file, debug, vendor exporters
Connectors Join pipelines: output of one is input to another spanmetrics (RED metrics from spans), servicegraph, count, routing, failover
Extensions Non-pipeline features health_check, pprof, zpages, auth extensions, file_storage (persistent queues)
YAML
# otel-collector.yaml (gateway): receive OTLP, enrich, sample, derive RED metrics, export to backends
receivers:
  otlp:
    protocols:
      grpc: { endpoint: 0.0.0.0:4317 }
      http: { endpoint: 0.0.0.0:4318 }

processors:
  memory_limiter: { check_interval: 1s, limit_percentage: 80, spike_limit_percentage: 20 }
  k8sattributes: {}
  resourcedetection: { detectors: [env, system] }
  transform/scrub:
    trace_statements:
      - context: span
        statements:
          - delete_key(attributes, "http.request.header.authorization")
          - replace_pattern(attributes["url.full"], "token=[^&]+", "token=REDACTED")
  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 } }
  batch: {}

connectors:
  spanmetrics:
    histogram: { explicit: { buckets: [5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s] } }

exporters:
  otlp/tempo: { endpoint: tempo.observability:4317, tls: { insecure: true } }
  prometheusremotewrite: { endpoint: http://mimir.observability/api/v1/push }
  otlphttp/loki: { endpoint: http://loki.observability:3100/otlp }

service:
  pipelines:
    traces:                                           # sampled traces to storage
      receivers: [otlp]
      processors: [memory_limiter, k8sattributes, resourcedetection, transform/scrub, tail_sampling, batch]
      exporters: [otlp/tempo]
    traces/red:                                       # every span (before sampling) → RED metrics
      receivers: [otlp]
      processors: [memory_limiter, k8sattributes]
      exporters: [spanmetrics]
    metrics:
      receivers: [otlp, spanmetrics]
      processors: [memory_limiter, k8sattributes, batch]
      exporters: [prometheusremotewrite]
    logs:
      receivers: [otlp]
      processors: [memory_limiter, k8sattributes, batch]
      exporters: [otlphttp/loki]

OTTL (OpenTelemetry Transformation Language) expresses transformations and filters (set, delete_key, replace_pattern, truncate_all, conditions with where) in the transform, filter and routing components.

Deployment patterns

node pod pod agent (DaemonSet)k8s metadata gatewaytail sampling gateway(scaled out) load-balancing exporter:same trace → same gateway metrics store trace store log store
Collector deployment patterns. Applications send to a local agent (sidecar or DaemonSet on each node) that adds host and Kubernetes metadata cheaply; agents forward to a central gateway tier that does tail sampling, redaction and routing to backends. A load-balancing exporter keeps all spans of a trace on the same gateway instance.
  • Agent (sidecar or DaemonSet per node): close to applications, cheap metadata enrichment, host metrics and log file tailing, quick offload so apps don't buffer.
  • Gateway (a scaled Deployment): central processing that needs a global view: tail sampling (needs all spans of a trace on the same instance, via the load-balancing exporter keyed by trace ID), redaction policies, routing to multiple backends, credential management for vendors.
  • Reliability: memory_limiter first in every pipeline, sending queues with persistent storage for retries, horizontal scaling, and monitoring the Collector's own metrics (accepted, refused, dropped).
  • Distributions: otelcol (core), otelcol-contrib (everything), otelcol-k8s, vendor distributions; build a minimal custom one with the Collector Builder (ocb).

Sampling

At high traffic, recording every trace is too expensive. Sampling chooses which traces to keep:

Type Decision made Pros Cons
Head sampling At trace start, typically by trace-ID ratio; propagated via the sampled flag (parent-based) Cheap, simple, consistent across services Blind to outcome: keeps 10% of errors and slow requests too
Tail sampling After the trace completes, in a Collector, based on its content (errors, latency, attributes) Keeps the interesting traces Must buffer whole traces (memory), requires trace-aware routing; decision delay
Rate-limited / adaptive Keep N traces per second per service/endpoint Bounded cost, protects rare endpoints More complex
Consistent probability sampling Sampling probability encoded in tracestate so downstream can make compatible decisions and backends can extrapolate counts Accurate span-derived metrics Newer specification

Common production setup: SDK parent-based sampler with a generous ratio (or always-on to the local agent), and tail sampling at the gateway keeping 100% of errors and slow traces plus a small baseline. Derive metrics before sampling (span metrics connector, or SDK metrics) so rates and latencies stay accurate.

Vendor-neutral telemetry pipelines

Putting it together, the roadmap's goal:

  1. Instrument with OTel APIs (zero-code where possible, manual for business context); never use vendor-specific APIs in application code.
  2. Configure SDKs with standard env vars or declarative config, sending OTLP to a local Collector.
  3. Process in Collectors you control: enrich, scrub sensitive data, sample, derive metrics, route.
  4. Export to one or more backends: switching vendors, running two in parallel during migration, or sending security-relevant logs to a SIEM is a Collector configuration change.
  5. Standardise semantic conventions (and your own company conventions) so dashboards and alerts work across services.

Lab: a Collector pipeline, its buffers and its pitfalls

OpenTelemetry Python SDK 1.45, OpenTelemetry Collector Contrib 0.149 and Jaeger 2.14 (in-memory storage). The Collector receives OTLP/HTTP on port 4320, exports to Jaeger over OTLP/gRPC, writes a copy to a file, and derives metrics from the spans.

The pipeline

YAML
receivers:
  otlp: {protocols: {http: {endpoint: 127.0.0.1:4320}}}
processors:
  memory_limiter: {check_interval: 1s, limit_mib: 200}
  filter/health:  {error_mode: ignore, traces: {span: ['attributes["url.path"] == "/healthz"']}}
  resource:       {attributes: [{key: deployment.environment.name, value: lab, action: upsert}]}
  attributes/pii: {actions: [{key: user.email, action: hash}]}
  redaction:      {allow_all_keys: true, blocked_values: ['4[0-9]{12}(?:[0-9]{3})?'], summary: info}
  batch:          {timeout: 1s, send_batch_size: 512}
connectors:
  spanmetrics: {histogram: {explicit: {buckets: [50ms, 100ms, 250ms, 500ms, 1s]}}}
exporters:
  otlp_grpc/jaeger:
    endpoint: 127.0.0.1:4317
    tls: {insecure: true}
    sending_queue: {enabled: true, queue_size: 5000}
    retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 120s}
  file: {path: /tmp/V9/c98/out.json}
  prometheus: {endpoint: 127.0.0.1:8889}
service:
  telemetry: {metrics: {readers: [{pull: {exporter: {prometheus: {host: 127.0.0.1, port: 8898}}}}]}}
  pipelines:
    traces:  {receivers: [otlp], processors: [memory_limiter, filter/health, resource, attributes/pii, redaction, batch],
              exporters: [otlp_grpc/jaeger, file, spanmetrics]}
    metrics: {receivers: [spanmetrics], exporters: [prometheus]}

Order matters: memory_limiter first (so overload is refused before work is done), filters early (don't spend effort on spans you'll drop), batch last. The spanmetrics connector is an exporter of the traces pipeline and a receiver of the metrics pipeline: it turns spans into request counts and latency histograms.

Experiment 1: filtering, enrichment and scrubbing

Covered in the Start Here section: 300 spans in, 200 out, health checks gone, the environment added, the email hashed, the card number masked.

Experiment 2: RED metrics from spans

Text
traces_span_metrics_calls_total{service_name="payments",span_name="POST /pay",span_kind="SPAN_KIND_SERVER",
  status_code="STATUS_CODE_UNSET",instance="296cac1c-…"} 200
traces_span_metrics_duration_milliseconds_bucket{…,le="250"} 152      # 152 of 200 under 250 ms
traces_span_metrics_calls_total{…,instance="828b1d35-…"} 40            # a second run of the sender

Two observations. First, these metrics are computed from every span before any tail sampling would drop them, so rates and percentiles stay exact even if you keep 1% of traces. Second, each run of the sender got a new instance label: the SDK generates a fresh service.instance.id per process, so every restart (or every pod) creates new series. That's correct for a few long-lived instances, but in a system with frequent restarts or serverless functions it multiplies cardinality; drop or aggregate the label in the connector configuration if you don't need per-instance metrics. (Also: the metrics appeared up to a minute after the spans; the connector flushes on an interval, so don't expect them instantly.)

Experiment 3: the Collector buffers when a backend is down

Jaeger was stopped, 90 spans sent (60 after filtering), then Jaeger restarted:

Text
Jaeger down:  otelcol_exporter_queue_size{otlp/jaeger} 1     sent_spans_total 240    "Exporting failed" logged 3 times
Jaeger back:  all 60 traces visible 7 s later                 queue_size 0            sent_spans_total 300

The exporter's sending queue held the batch and retry_on_failure kept trying with backoff; nothing was lost. Two limits: the queue is in memory unless you configure storage: file_storage (a Collector restart loses it), and after max_elapsed_time (120 s here) the data is dropped. Watch otelcol_exporter_queue_size, otelcol_exporter_send_failed_spans_total and otelcol_processor_refused_spans_total: they're how a pipeline tells you it's losing data.

Experiment 4: the SDK alone, with no Collector reachable

Text
created 5000 spans in 0.09s with no backend (the app isn't blocked)
ERROR …trace_exporter: Failed to export spans batch due to timeout, max retries or shutdown.   (×5)
shutdown took 5.2s; the spans are gone: nothing persisted them

The SDK is designed never to hurt the application: span creation stayed fast, the BatchSpanProcessor queue (2,048 spans by default) silently dropped the overflow, and failed batches were discarded after retries. Losing telemetry is preferred over slowing requests. This is why most deployments run a Collector next to the application (a sidecar, a DaemonSet agent, or on the host): the hop is local and nearly always up, and the Collector does the buffering and retrying towards remote backends.

Experiment 5: a context pitfall in Python

Text
start_as_current_span(..., context=ctx):  {'traceparent': '00-8c0d…-f506…-03'}                       # baggage missing
context.attach(ctx) first:                 {'traceparent': '00-0fbc…-713b…-03', 'baggage': 'tenant=acme'}

context= only chooses the parent of the new span; the span is then made current on top of the current context, which didn't contain the baggage. Attaching the context first (or setting baggage inside the span) fixes it. Bugs like this are the main cause of "broken traces" and missing context: always check a real outgoing request's headers when adding propagation.

Experiment 6: head sampling with parent-based ratio

With ParentBased(TraceIdRatioBased(0.25)), 2 of 8 traces were sampled (-03 flag ending; unsampled ones end -02: random, not sampled). A downstream service given traceparent: 00-4bf92f35…-00f067aa0ba902b7-01 continued trace 4bf92f35… with parent 00f067aa0ba902b7 and recorded the span because the parent said "sampled": the decision made once at the root is honoured by every service, so traces are complete or absent, never half-recorded.

Try it yourself

  1. Add a tail_sampling processor keeping errors and spans over 250 ms; compare the file exporter's span count with spanmetrics counts (chapter 101 does this in depth).
  2. Add storage: file_storage to the sending queue, stop Jaeger, restart the Collector, start Jaeger, and check whether the spans survived.
  3. Add a second exporter (for example debug with verbosity: detailed) to see how one pipeline fans out to several backends.

Revision sheet: OpenTelemetry

Key ideas

  • API / SDK split: libraries and apps depend on the no-op API; the application configures the SDK once (resource, sampler, processors, exporters).
  • Resource: who emits (service.name, service.version, deployment.environment.name, service.instance.id, host, k8s attributes).
  • Propagation: W3C traceparent (version-traceid-spanid-flags), tracestate, baggage; inject on outgoing, extract on incoming.
  • Semantic conventions: standard attribute names (http.request.method, url.path, db.system.name) so tools work across services.
  • OTLP over gRPC (4317) or HTTP/protobuf (4318).
  • Collector: receivers → processors → exporters in pipelines; connectors join pipelines; agent (near the app) and gateway (central) tiers; OTTL for transforms.
  • Sampling: head (parent-based ratio, decided at the root) vs tail (after completion, in a gateway); derive metrics before sampling.

Numbers to remember

  • Ports 4317 (gRPC) and 4318 (HTTP). BatchSpanProcessor default queue 2,048 spans, batch 512.
  • Lab: 300 spans in, 200 out after filtering; 60 spans buffered and delivered 7 s after the backend returned; 5,000 spans created in 0.09 s with no backend, then dropped.

Pitfalls

  • Using a vendor's API in application code.
  • Context not propagated (thread pools, async, queues, or the context= vs attach mistake): broken traces.
  • Secrets or large values in baggage.
  • Processors in the wrong order (batch before filter, no memory_limiter).
  • In-memory queues only, and nobody watching the Collector's own metrics.
  • Per-instance labels multiplying span-metric series.

Glossary

  • Span processor: SDK component that receives finished spans (batching, exporting).
  • Exporter: sends telemetry somewhere (OTLP, Prometheus, file).
  • Connector: Collector component that's an exporter of one pipeline and a receiver of another (spanmetrics, count, routing).
  • OTTL: OpenTelemetry Transformation Language for transform and filter processors.
  • Parent-based sampler: follows the parent's sampled flag; samples roots by a ratio.