OpenTelemetry (OTel) is the open source standard for instrumenting your applications: you generate traces, metrics and logs once, then send them to any backend. No vendor lock-in, no re-instrumentation if you change your observability stack.
The previous lessons observed an application that was already instrumented; this one shows how to make yours observable. You will go from your first trace to a production-ready configuration: quickstart, auto-instrumentation, business spans, configuration and sampling.
What you will learn
- Understand OpenTelemetry's layered model (API, SDK, Collector).
- Watch a first trace go through a test Collector.
- Instrument an application automatically and then manually.
- Configure OTel with environment variables, OTLP protocol included.
- Prepare for production: sampling, propagation, conventions.
Why OpenTelemetry?
Before OpenTelemetry, every observability tool imposed its own agent and its own format. Changing backend meant re-instrumenting every application. OTel breaks this coupling: a single instrumentation, a single protocol (OTLP), and the choice of backend becomes a simple infrastructure decision. That is what made it the de facto standard.
| Question | Answer |
|---|---|
| What is it? | A set of APIs, SDKs and tools to generate telemetry (traces, metrics, logs) |
| Who maintains it? | CNCF (Cloud Native Computing Foundation), Graduated project since May 11, 2026 |
| Why use it? | One standard, multi-language, multi-backend, active community |
| Which backends? | Jaeger, Tempo, Prometheus, Mimir, Loki, Datadog, New Relic, Splunk... |
Mental model: how the building blocks fit together
Before coding, understand the 5 layers:
| Layer | What it does | Where it lives |
|---|---|---|
| API | Interface to create spans, metrics, logs | In your code |
| SDK | Implementation: buffering, sampling, export | App runtime |
| Auto-instrumentation | Automatically instruments frameworks | Agent/wrapper around the app |
| OTLP exporter | Sends the signals over OTLP | In the app (SDK) |
| Collector | Receives, transforms, routes | Infrastructure (container/daemon) |
Quickstart: your first trace (10 min)
Goal: see a trace go by before coding anything.
-
Start a Collector with the debug exporter
Terminal window docker run --rm -p 4317:4317 -p 4318:4318 \otel/opentelemetry-collector-contrib:0.155.0@sha256:4935caa35e9a4cb387e35732e8fb22b2b5759af8d12e7043357f03837f6e8df5 \--config='yaml:receivers:otlp:protocols:grpc:endpoint: 0.0.0.0:4317http:endpoint: 0.0.0.0:4318exporters:debug:verbosity: detailedservice:pipelines:traces:receivers: [otlp]exporters: [debug]'The
yaml:prefix is mandatory: without it,--configexpects a path or a URI, and the Collector stops right away withError: invalid uri. Tested on 0.155.0. Once started, it prints the traces it receives in the console. -
Send a test trace
With
telemetrygen(OTel test tool):Terminal window docker run --rm --network host \ghcr.io/open-telemetry/opentelemetry-collector-contrib/telemetrygen:v0.155.0@sha256:32d1762abb401e36dd8cfdf60a71075b41bd996a0cfb7c8d2e6eac4d609625b9 \traces --otlp-insecure --traces 1 -
Check the output
You should see in the Collector logs:
Span #0Name : okey-dokey-0Kind : ServerSpan #1Name : lets-goKind : ClientThese two names are hard-coded in
telemetrygen:lets-gois the client root span,okey-dokey-0the server child span that simulates the called service. Seeing both confirms that the trace context was propagated from parent to child. The display order follows the arrival of the spans, not their hierarchy: the child comes out first here.
You have a working pipeline. Now let's instrument a real application.
Choosing your mode: auto vs manual
The question is not "auto or manual" but "in which order". Both approaches produce spans in the same trace and combine without conflict: auto-instrumentation intercepts the libraries you did not write (HTTP client, SQL driver, Kafka consumer), manual instrumentation describes what your code does between those calls. Read the third row of the table as the real target in production, the first two as steps towards it.
| Mode | When to use it | What it covers |
|---|---|---|
| Auto-instrumentation | Quick start, legacy, standard frameworks | HTTP, SQL, Redis, Kafka, gRPC... |
| Manual instrumentation | Business logic, custom spans | Checkout, payment, PDF generation... |
| Both | Real production | Auto = "plumbing", manual = "business" |
Auto-instrumentation by language
Auto-instrumentation injects traces without changing your code for common frameworks (HTTP, DB, messaging). The mechanism differs by language and this changes what you must deploy: Java relies on a JVM agent loaded at startup, Python on a launcher (opentelemetry-instrument) that monkey-patches the libraries, Node.js on a module loaded before the application code with --require, .NET on an explicit registration in the dependency injection container. Go is the exception: its static compilation rules out monkey-patching, so instrumentation goes through explicit wrappers (or through the separate opentelemetry-go-instrumentation project, which relies on eBPF).
# Install the distro (includes SDK + common instrumentations)pip install opentelemetry-distroopentelemetry-bootstrap -a install
# Run with auto-instrumentationopentelemetry-instrument python app.pyConfiguration via env vars (recommended):
export OTEL_SERVICE_NAME=checkout-apiexport OTEL_EXPORTER_OTLP_PROTOCOL=grpcexport OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317# Optional: local debugexport OTEL_TRACES_EXPORTER=console# Download a specific agent version and its checksum fileVERSION="v2.32.0"BASE="https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/${VERSION}"curl -sSLO "${BASE}/opentelemetry-javaagent.jar"curl -sSLO "${BASE}/checksums.txt"
# Check the digest before any use: must print "OK"sha256sum --ignore-missing -c checksums.txt
# Run with the agentjava -javaagent:opentelemetry-javaagent.jar \ -jar myapp.jarConfiguration via env vars:
export OTEL_SERVICE_NAME=order-serviceexport OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317export OTEL_EXPORTER_OTLP_PROTOCOL=grpcThe Java 2.x agent sends http/protobuf by default. To target port 4317
(gRPC), declare grpc as above, or target port 4318 over HTTP.
The agent automatically instruments: Spring Boot, Quarkus, JAX-RS, JDBC, Kafka, Redis...
const { NodeSDK } = require('@opentelemetry/sdk-node');const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-grpc');
const sdk = new NodeSDK({ traceExporter: new OTLPTraceExporter(), instrumentations: [getNodeAutoInstrumentations()],});
sdk.start();# Installnpm install @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node @opentelemetry/exporter-trace-otlp-grpc
# RunOTEL_SERVICE_NAME=frontend \OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 \node --require ./tracing.js app.jsusing OpenTelemetry.Trace;using OpenTelemetry.Resources;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry() .ConfigureResource(r => r.AddService("my-service")) .WithTracing(tracing => tracing .AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation() .AddOtlpExporter());Configuration via env vars:
export OTEL_SERVICE_NAME=payment-apiexport OTEL_EXPORTER_OTLP_PROTOCOL=grpcexport OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317The .NET SDK exports over gRPC by default, whereas .NET auto-instrumentation
exports http/protobuf. Declaring the protocol avoids a mismatch between the
targeted port and the one used by either of them.
Go has no "magic" auto-instrumentation, you have to wrap the packages manually. Use the official instrumentations for net/http, database/sql, gRPC, etc.
import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
// Wrap the HTTP clientclient := &http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}
// Wrap the HTTP serverhandler := otelhttp.NewHandler(myHandler, "my-server")Manual instrumentation: business spans
Auto covers the "pipes" (HTTP, DB). To trace the business logic, add manual spans.
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
def process_checkout(cart_id: str, user_id: str): with tracer.start_as_current_span("checkout.process") as span: # Business attributes span.set_attribute("cart.id", cart_id) span.set_attribute("user.id", user_id) span.set_attribute("cart.items_count", 5)
# Child span with tracer.start_as_current_span("checkout.validate_payment"): validate_payment()
with tracer.start_as_current_span("checkout.reserve_stock"): reserve_stock()import io.opentelemetry.api.GlobalOpenTelemetry;import io.opentelemetry.api.trace.Span;import io.opentelemetry.api.trace.Tracer;
public class CheckoutService { private static final Tracer tracer = GlobalOpenTelemetry.getTracer("checkout-service");
public void processCheckout(String cartId) { Span span = tracer.spanBuilder("checkout.process").startSpan(); try (var scope = span.makeCurrent()) { span.setAttribute("cart.id", cartId); validatePayment(); reserveStock(); } finally { span.end(); } }}const opentelemetry = require('@opentelemetry/api');
const tracer = opentelemetry.trace.getTracer('checkout-service');
async function processCheckout(cartId, userId) { return tracer.startActiveSpan('checkout.process', async (span) => { span.setAttribute('cart.id', cartId); span.setAttribute('user.id', userId);
await tracer.startActiveSpan('checkout.validate_payment', async (paymentSpan) => { await validatePayment(); paymentSpan.end(); });
span.end(); });}import ( "context" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute")
var tracer = otel.Tracer("checkout-service")
func ProcessCheckout(ctx context.Context, cartID, userID string) error { ctx, span := tracer.Start(ctx, "checkout.process") defer span.End()
span.SetAttributes( attribute.String("cart.id", cartID), attribute.String("user.id", userID), )
if err := validatePayment(ctx); err != nil { span.RecordError(err) return err }
return reserveStock(ctx)}Handling errors
A span whose code raised an exception stays green by default: the SDK does
not guess that there was an incident. Two distinct calls are needed and
they do not do the same thing. set_status(StatusCode.ERROR) marks the span as
failed, which makes it stand out in red in the backend and is what your
alerts trigger on. record_exception() attaches the stack trace to the
span as an event, which gives the diagnostic context. The final raise is
essential: without it, you would have traced an error while hiding it from the
caller.
from opentelemetry.trace import Status, StatusCode
try: result = process_payment()except Exception as e: span.set_status(Status(StatusCode.ERROR, str(e))) span.record_exception(e) raiseUniversal configuration (env vars)
Do not hardcode endpoints. Use the standard OTel environment variables:
# Service identity (mandatory)OTEL_SERVICE_NAME=checkout-apiOTEL_RESOURCE_ATTRIBUTES=service.version=1.2.0,deployment.environment=production
# OTLP exportOTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317OTEL_EXPORTER_OTLP_PROTOCOL=grpc # or http/protobuf
# Sampling (production)OTEL_TRACES_SAMPLER=parentbased_traceidratioOTEL_TRACES_SAMPLER_ARG=0.1 # 10% of traces
# PropagationOTEL_PROPAGATORS=tracecontext,baggage
# Debug (dev only)OTEL_TRACES_EXPORTER=console # prints to stdoutOne nuance worth knowing: OTEL_SERVICE_NAME, OTEL_RESOURCE_ATTRIBUTES,
OTEL_TRACES_SAMPLER, OTEL_PROPAGATORS and the OTEL_*_EXPORTER variables
are specified and behave the same way in every language. Many other
variables that you will come across in blog posts, starting with
OTEL_LOG_LEVEL, are not in the specification and are only recognized by some
SDKs. Before putting one in a production manifest, check it in the
SDK configuration
of the language concerned.
Production: the 5 critical points
1. Sampling: do not trace 100%
In production, tracing 100% of requests is expensive in storage and adds
latency to every call. The point to understand is that the sampling decision is
made at the start of the trace and then propagated: that is the whole point
of the parentbased_ variant, which guarantees that a trace is complete or
absent, never cut off from its last services. A non-parentbased sampler
applied service by service produces holey traces, where the root span
exists but not the database call that took three seconds.
| Sampler | Description |
|---|---|
always_on | Everything (dev only) |
traceidratio | X% of traces |
parentbased_traceidratio | X% unless the parent has decided (recommended) |
OTEL_TRACES_SAMPLER=parentbased_traceidratioOTEL_TRACES_SAMPLER_ARG=0.1 # 10%2. Propagation: W3C Trace Context
Propagation transmits the trace-id between services. Without it, your traces are fragmented.
traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01By default, OTel uses W3C Trace Context. If you have legacy B3 (Zipkin):
OTEL_PROPAGATORS=tracecontext,baggage,b3multi3. Semantic Conventions: standard attributes
Semantic Conventions are the standardized list of attribute names. Their
value is not cosmetic: the prebuilt dashboards, alerting rules and anomaly
detection functions of backends rely on these exact names. An attribute
named http_status instead of http.response.status_code stays visible in the
trace, but no tool will use it automatically. The table below only gives the
most common domains; the full
specification covers several
dozen.
| Domain | Attributes |
|---|---|
| HTTP | http.request.method, url.path, http.response.status_code |
| Database | db.system.name, db.namespace, db.operation.name, db.query.text |
| Messaging | messaging.system, messaging.destination.name |
4. Logs: correlation with traces
Without correlation, an error log tells you that a payment failed but not in
which request nor after which calls. By injecting trace_id and span_id into
every log line, you make it possible to jump directly from the error message to
the full trace, and back. The condition is that the log is structured
(JSON or logfmt): a free-text message containing the identifier will not be
indexed as a field and will remain unusable by the backend.
{ "timestamp": "2026-02-09T10:30:00Z", "level": "ERROR", "message": "Payment failed: insufficient funds", "trace_id": "abc123def456...", "span_id": "789xyz...", "service.name": "payment-service"}5. Collector: decoupling and governance
In production, do not export directly to the backends. Go through a Collector:
App (SDK) → OTLP → Collector → BackendsWhy?
- Decoupling: change backend without recoding
- Resilience: the Collector buffers if the backend is down
- Governance: filtering, PII redaction, K8s enrichment
- Multiple destinations: traces → Tempo, metrics → Mimir
Anti-patterns (what NOT to do)
The first two rows of the table weigh directly on the observability bill. A unique identifier placed in an attribute multiplies the number of distinct series by the number of users, and this cardinality is what most backends charge for. The next two are security and architecture risks, the last three degrade operability without costing money. Handle them in that order.
| Anti-pattern | Consequence | Solution |
|---|---|---|
| Unique IDs in attributes | Cardinality explosion, costs | Use categories (status, region) |
| Tracing 100% in prod | Overhead, storage costs | Sampling 10-20% |
| PII/secrets in attributes | Data leak | Redaction via Collector |
| Exporting directly to the backend | Vendor lock-in, no governance | Go through a Collector |
No service.name | Anonymous, unusable traces | Always define OTEL_SERVICE_NAME |
| Ignoring propagation | Orphan spans, fragmented traces | Check propagators + headers |
| Overly verbose spans | Noise, hard to use | 5-10 attributes max per span |
Troubleshooting
Checklist: "I don't see my traces"
Follow these five points in order, from the closest to the code to the
closest to the backend. Each one isolates a link of the chain, and stopping
at the first one that fails saves you from hunting for a network problem when
the SDK produces nothing. Point 1 is checked first: if console shows no span,
the problem is in the instrumentation, not in the export.
-
Does the SDK generate spans?
Terminal window OTEL_TRACES_EXPORTER=console python app.py# → You must see spans in stdout -
Does the Collector receive the data?
Enable the debug exporter in the Collector:
exporters:debug:verbosity: detailed -
Is the network OK?
Terminal window # From the app containercurl -v http://otel-collector:4318/v1/traces# → Must answer (even with a 405 error) -
Are the ports correct?
- 4317 = gRPC
- 4318 = HTTP
Check that
OTEL_EXPORTER_OTLP_PROTOCOLmatches the targeted port. The Java 2.x agent sendshttp/protobufwithout any setting: towards port 4317, the connection is cut (Connection reset) until you setOTEL_EXPORTER_OTLP_PROTOCOL=grpc. -
Is propagation configured?
Without propagation, services do not share the
trace-id.Terminal window OTEL_PROPAGATORS=tracecontext,baggage
Common errors
These four symptoms are told apart by what you already see. If no data arrives, look at the first row: it is a transport problem. If spans arrive but do not attach to one another, it is rows 2 and 3: the trace context is lost, either between two services for lack of a propagator, or inside a single service when an asynchronous task starts without carrying the current context. If everything arrives but the backend cannot name the sender, it is the last row.
| Symptom | Likely cause | Solution |
|---|---|---|
Connection refused :4317 | Collector not started or wrong port | Check the container/service |
Connection reset towards port 4317 | HTTP protocol sent to a gRPC port (case of the Java 2.x agent without settings) | OTEL_EXPORTER_OTLP_PROTOCOL=grpc, or target port 4318 |
| Orphan spans (no parent) | Missing propagation | Check OTEL_PROPAGATORS |
| Fragmented traces | Context lost between async calls | Pass the context explicitly (trace.use_span() or trace.set_span_in_context() in Python, pass the ctx in Go) |
Unknown service in the backend | OTEL_SERVICE_NAME not set | Set the variable |
Metrics (quick overview)
OTel is not limited to traces: the same SDK also produces metrics, with the
same service.name and the same resource attributes, which lets you move from
a latency graph to the matching traces. The choice of instrument type is
not a matter of style, it determines what the backend can compute. A Counter
can only answer "how many since startup", a Histogram can answer "what is the
95th percentile", and only the latter lets you set a service level objective
on latency.
| Type | Use | Example |
|---|---|---|
| Counter | Cumulative values | Requests, errors |
| Gauge | Instantaneous value | Memory, active connections |
| Histogram | Distribution | Latency (p50, p95, p99) |
from opentelemetry import metrics
meter = metrics.get_meter(__name__)
# Counterrequest_counter = meter.create_counter("http.server.requests")request_counter.add(1, {"method": "GET", "status": "200"})
# Histogram (latency)latency_histogram = meter.create_histogram("http.server.duration", unit="ms")latency_histogram.record(45.2, {"method": "GET", "route": "/api/orders"})Resources
The official references that are authoritative, to consult before putting an environment variable or an attribute in production:
- Official documentation
- SDK Configuration (env vars)
- OTLP Exporter Configuration
- Semantic Conventions
- Specification Status, maturity of signals by language
- Registry (instrumentations)
Key takeaways
- OTel = CNCF standard for traces, metrics, logs, choose it by default
- Auto-instrumentation: common libraries without changing the code
- Manual spans for business logic (checkout, payment...)
- Configure with env vars (
OTEL_*), not hardcoded in the code - Go through a Collector in production (decoupling, governance)
- Sampling + redaction = mandatory in prod
FAQ: frequently asked questions
The questions below come up systematically on a first setup: where to start, how to balance auto and manual, which OTLP port to choose, and whether you really need to deploy a Collector.
OTEL_EXPORTER_OTLP_ENDPOINT, then add manual spans for the business logic that auto-instrumentation does not capture.