Auto vs manual instrumentation, and what auto misses
Auto-instrumentation sees every edge of your service and none of its meaning. Use it for the edges, write spans for the decisions
The gateway calls a function decide_tier(user) that does pure Python arithmetic for 80 ms, then calls orders over HTTP with httpx. The service runs under opentelemetry-instrument with the FastAPI and httpx instrumentations installed. What does the trace show for those 80 ms?
Auto-instrumentation and manual instrumentation are not rival schools. They answer different questions. Auto answers “which dependencies did this request touch, how long did each take, and did it fail”. Manual answers “what was this request, what did the code decide, and why was it slow”. You need both, and the craft is knowing where the line sits for your service.
How auto-instrumentation gets in
“Zero-code” is accurate about your source files and misleading about everything else. Something has to change what runs. There are three mechanisms in common use and each has its own failure modes.
Monkey-patching (Python, Node, Ruby). In Python, pip install opentelemetry-distro opentelemetry-exporter-otlp installs the SDK and two commands. opentelemetry-bootstrap -a install inspects your site-packages and installs a matching instrumentation package for each library it recognises: opentelemetry-instrumentation-fastapi for FastAPI, -httpx for httpx, -psycopg for psycopg, -redis for redis-py. opentelemetry-instrument uvicorn app:app then starts your program with a directory on PYTHONPATH that contains a sitecustomize.py. Python imports sitecustomize automatically at interpreter start. That module configures the SDK from OTEL_* environment variables and calls each instrumentor’s instrument(), which replaces functions in the target library with wrappers that start a span, call the original, record the result and end the span. The FastAPI instrumentor wraps the ASGI application; the httpx instrumentor wraps the transport’s request method; the psycopg instrumentor wraps cursor execution. Node does the same with require hooks that intercept module loading.
The wrapping happens at import time, which creates the most common Python failure: if your code imports and captures a reference to the library function before the instrumentor runs, your reference points at the unwrapped original. Pre-fork servers create a second one: a process that forks after the SDK starts a background export thread inherits a dead thread in the child. The Python troubleshooting docs say that more than one --workers may break metrics under auto-instrumentation, that reloaders (Flask’s debug mode, for example) can stop instrumentation happening at all, and that the preferred fix for Gunicorn is to initialise OpenTelemetry in a post-fork hook instead of with opentelemetry-instrument.
Bytecode injection (Java, .NET). The Java agent is one jar attached with -javaagent:path/to/opentelemetry-javaagent.jar. The JVM gives agents a hook to rewrite class bytes as they load, and the OTel agent uses it to inject advice into the methods of more than 150 supported libraries, frameworks and application servers: Servlet, Spring Web MVC, JDBC, Netty, OkHttp, gRPC, the Kafka client. Because it works at class-load time it does not depend on import order, and because it ships every instrumentation in one jar it does not need a bootstrap step. The cost is that every class load is inspected, which shows up as startup time, and that the agent carries its own classloader isolation, which occasionally collides with application frameworks that do their own classloading. .NET uses the CLR profiling API to the same end.
eBPF (Go and anything compiled). Compiled languages without a runtime hook are instrumented from outside the process. The OpenTelemetry Go instrumentation project and OpenTelemetry eBPF Instrumentation (OBI, donated by Grafana from Beyla in 2025) attach uprobes to known functions in the binary (the HTTP server’s handler entry, the gRPC client’s invoke) or to kernel network calls, read arguments and timings from registers and memory, and emit spans. It works on unmodified binaries on a Linux kernel above 4.4, and it is language-agnostic at the network layer. It is also the most limited: it needs privileges on the host, it can see only what is reachable from function arguments it knows the layout of, and propagating trace context into outbound requests means writing into the process’s memory, which is the hardest part and the least portable. The module on eBPF goes deeper.
What auto gives you for free
At the edges of a service the coverage is excellent and you should not write it by hand.
- Inbound HTTP and RPC. A
SERVERspan per request with method, route, status code, scheme, server address, and withOTEL_SEMCONV_STABILITY_OPT_IN=httpthe stable attribute names. The span name is{method} {route}(POST /orders), which keeps cardinality bounded. - Outbound HTTP and RPC. A
CLIENTspan per call, plus injection of thetraceparentheader so the next service continues the trace. This is the part that is hardest to do by hand and most valuable to get right: propagation bugs are what split traces. - Database and cache clients. A
CLIENTspan per statement or command with the database system, the database name, server address and, for SQL, the statement text with literals stripped or parameterised. The psycopg instrumentor can also append atraceparentcomment to each query (enable_commenter=True), so a slow query inpg_stat_statementspoints back to a trace. - Queue producers and consumers.
PRODUCERandCONSUMERspans for Kafka, RabbitMQ and SQS clients, with context carried in message headers. - Runtime metrics. In Java, JVM memory, GC and thread metrics; in Python, the
system-metricsinstrumentation gives CPU, memory and GC counts; HTTP server instrumentations emithttp.server.request.durationhistograms that are enough for a RED dashboard on day one.
That list is the entire network surface of a typical service. If you had nothing before, it turns a service map, per-dependency latency and error attribution into a one-day job.
What auto cannot see
Everything that happens between two library calls is invisible to a monkey-patch, a bytecode advice or a uprobe on a known library. There are four kinds of blind spot, and they are where most real performance bugs live.
Business logic boundaries. A pricing rule, a fraud score, a VIP branch, a template render, a JSON serialisation of a 4 MB payload. These are your functions. Auto-instrumentation does not wrap them, so the trace shows the time as self-time on the server span: a grey gap. A gap tells you something is slow; it does not tell you what. The fix is a span with a name that describes the operation (checkout.decide_tier, orders.price_items) and attributes that describe its inputs.
Async fan-out and joins. In Python, asyncio copies the current context into a task when the task is created, so spans started inside asyncio.gather children correctly parent to the caller. What auto does not give you is a span for the join itself: you see five parallel children and no parent that measures “waited for all five”, so you cannot tell whether the request was slow because of the slowest child or because of what happened after. Work handed to a thread pool via loop.run_in_executor does not carry the context by default (asyncio.to_thread does), so spans created there start new traces. Background jobs scheduled after the response is sent run after the server span has ended. Each of these needs either explicit context passing (contextvars.copy_context(), opentelemetry.context.attach) or a span link.
Batch internals. A consumer that pulls 500 messages and processes them in one function produces one CONSUMER span (or one per receive call) and no visibility into which of the 500 was slow. A nightly job that loops over a million rows is a single span of two hours. Batch work needs a span per item or per chunk, with links back to the producer contexts, and a deliberate decision about sampling because a million spans per run is its own cost problem.
The meaning of a request. Auto knows the route was POST /orders. It does not know the user was a VIP, the cart had 15 items, the A/B bucket was new-pricing, the tenant was acme, or the build was 1.4.2-rc3. Those attributes are what turn “p99 is high” into “p99 is high for VIP users with more than 10 items on the new pricing path”. Without them, the high-cardinality analysis that later chapters teach has nothing to group by. The best place to add most of them is the server span auto already created: trace.get_current_span().set_attribute("shop.user.vip", True) from inside the handler enriches it without adding a new span.
The costs of auto
Free coverage is not free.
Overhead. Every wrapped call costs a span: a few microseconds of CPU in Java or Go, tens of microseconds in Python where span creation, attribute dictionaries and context switches are interpreted code. A request that makes 40 database calls produces 40 spans, and the N+1 fault in this module’s demo app produces one per item. The Java agent documentation names JDBC and Redis as the instrumentations most likely to dominate overhead because of span volume, and the knob is -Dotel.instrumentation.jdbc.enabled=false (or the environment variable form). Python has OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=redis,kafka (entry-point names) and OTEL_PYTHON_EXCLUDED_URLS=health,metrics to stop health checks generating traces. Measure overhead under realistic load, not on one request, because the cost that matters is the batch processor’s export thread competing with your request threads.
Startup. The Java agent inspects every class as it loads. On a large Spring application that is seconds of added startup, which matters for autoscaling and serverless, where it lands on the first request. Python’s cost is smaller and comes from importing the SDK, exporters and every instrumentor at boot.
Version coupling. Each Python instrumentation package declares the versions of its library that it supports, and the contrib packages ship in lockstep with the SDK with beta version numbers: SDK 1.44.0 pairs with instrumentations 0.65b0. Upgrade FastAPI past the supported range and the instrumentor skips it with a debug-level log line: no error, no spans. The Java agent ships tested ranges and either applies or does not. Pin instrumentation versions with the SDK, and add a test that fails if a known span is missing.
Volume you did not choose. Auto creates spans for everything it recognises, including the ones you do not want: health checks, readiness probes, metrics scrapes, internal ASGI send and receive spans. These inflate span counts and storage. The FastAPI instrumentation can exclude the ASGI internal spans (exclude_spans=["receive", "send"]) and specific URLs; the collector chapter drops the rest centrally.
A strategy: auto for edges, manual for meaning
The pattern that works in practice has four steps.
- Turn on auto everywhere with the stable semantic conventions, and exclude health and metrics endpoints. You now have edges and propagation.
- Enrich the server span with the attributes that describe the request: tenant, user tier, plan, cart size, feature flags, build. Use a namespaced prefix (
shop.) and keep each attribute bounded: a user id is fine on a span, where it costs bytes; it is not fine as a metric label, where it costs a time series. - Add spans around decisions and loops that take more than a few milliseconds or that branch on business logic: the tier decision, the pricing loop, the fraud check, the cache-or-compute choice. Name them after the operation, not the function, so a refactor does not rename the span.
- Fix the blind spots in concurrency: pass context into thread pools and background jobs, link batch items to their producers.
You will know you have it right when the grey self-time on your server spans is small, and when the first question during an incident is answered by a group-by on an attribute rather than by reading code.
A manual span in Python is three lines and costs the same as an auto one:
from opentelemetry import trace
tracer = trace.get_tracer("shop.gateway")
with tracer.start_as_current_span("checkout.decide_tier") as span:
vip = user_id % 97 == 0
span.set_attribute("shop.user.vip", vip)
Put attributes you know at the start into start_as_current_span(..., attributes={...}) rather than set_attribute afterwards: samplers see only what is present at span creation, so an attribute added later cannot drive a head-sampling decision. Record exceptions with span.record_exception(e) and span.set_status(Status(StatusCode.ERROR)); the context manager does both automatically for an exception that escapes the with block.
You will list every span the auto-instrumentation produces for one checkout, add two manual spans with attributes, compare the trace before and after, and measure what the instrumentation costs under load.
1. Confirm how the services are instrumented.
cd labs/observability
OTEL_SDK_DISABLED=false OTEL_SEMCONV_STABILITY_OPT_IN=http/dup docker compose --profile telemetry up -d
docker compose exec gateway pip list 2>/dev/null | grep -i opentelemetry-instrumentation
grep -n 'Instrumentor' services/common/telemetry.py-fastapi, -asgi, -httpx, -psycopg, -dbapi and -redis, the same in all three services because they share one image. The services do not run under opentelemetry-instrument; they start with python -m gateway.app (and so on), and services/common/telemetry.py calls each instrumentor in code: HTTPXClientInstrumentor (skipped in orders, which propagates to payments by hand), PsycopgInstrumentor, RedisInstrumentor, and FastAPIInstrumentor.instrument_app with excluded_urls=“health,metrics” and exclude_spans=[“receive”, “send”].2. List the spans auto gives you for one checkout.
TID=$(openssl rand -hex 16)
curl -s -H "traceparent: 00-$TID-$(openssl rand -hex 8)-01" 'http://localhost:8080/checkout?user=194&items=4'
sleep 10
curl -s "http://localhost:3200/api/v2/traces/$TID" \
| jq -r '.. | objects | select(has("spanId")) | "\(.kind)\t\(.name)"' | sort | uniq -cUser 194 is VIP (194 = 2 × 97), so this checkout triples its items to 12. You send the traceparent yourself, as in the three-signals lab, so you know the trace id before you ask Tempo for it.
SPAN_KIND_SERVER GET /checkout, two SPAN_KIND_CLIENT POST (the gateway’s from httpx, and orders’ call to payments, which the lab writes by hand), one SPAN_KIND_SERVER POST /orders, three Postgres SPAN_KIND_CLIENT spans named after the statement (two INSERT, one UPDATE), one SPAN_KIND_SERVER POST /charge and two Redis client spans named after the commands (GET, SET): ten in all. There are no GET /checkout http send INTERNAL spans because the lab passes exclude_spans; remove it and each server span gains two or three. Every span is an edge: a request in, a request out, a query, a cache call. Nothing tells you this was a VIP order, that it had 12 items, or how long the gateway spent deciding that.3. See the gap. Open the trace in Grafana (Explore, Tempo data source, paste $TID). Click the gateway’s GET /checkout span and compare its duration with the sum of its children. Then do the same for POST /orders.
4. Add a span around the VIP decision in the gateway.
The decision is in services/gateway/app.py, in checkout(): vip = user % VIP_DIVISOR == 0 and effective_items = items * VIP_MULTIPLIER if vip else items. Wrap those two lines. trace is already imported; add a tracer below app, log = create_app(...):
tracer = trace.get_tracer("shop.gateway")
# inside checkout(), replacing the two lines that compute vip and effective_items
with tracer.start_as_current_span("checkout.decide_tier", attributes={"user.id": user}) as span:
vip = user % VIP_DIVISOR == 0
effective_items = items * VIP_MULTIPLIER if vip else items
span.set_attribute("user.vip", vip)
span.set_attribute("order.items", effective_items)The lines that follow in the handler already enrich the server span: span = trace.get_current_span() (the server span again, now the with block has closed) and span.set_attribute("user.vip", vip).
checkout.decide_tier is a new INTERNAL span that measures the decision, and the handler’s existing lines put user.vip on the SERVER span, because that is the span RED dashboards and group-by queries look at. In production you would prefix both attributes (shop.user.vip) because user.* is a semantic-convention namespace.5. Add a span around the order-items loop in orders.
In services/orders/app.py, create_order() writes the items in the if n_plus_one: ... else: ... block inside the transaction (with FAULT_N_PLUS_ONE=0 it is one statement; with the fault on it is a loop). The module already has a tracer; wrap the block with it:
with tracer.start_as_current_span("orders.write_items") as span:
span.set_attribute("order.items", order.items)
# ... the existing if n_plus_one / else block, unchanged ...Rebuild both services and turn on the N+1 fault so the loop has something to show:
OTEL_SDK_DISABLED=false OTEL_SEMCONV_STABILITY_OPT_IN=http/dup FAULT_N_PLUS_ONE=1 \
docker compose --profile telemetry up -d --build gateway orders
sleep 20
curl -s 'http://localhost:8080/checkout?user=194&items=4' && sleep 10
curl -G -s http://localhost:3200/api/search \
--data-urlencode 'q={ name = "GET /checkout" && span.user.vip = true } >> { name = "orders.write_items" && span.order.items >= 12 }' \
| jq -r '.traces[0].traceID'>> means “has a descendant”: the gateway server span you enriched with user.vip=true is an ancestor of an items write with 12 or more items in orders. You query the server span rather than checkout.decide_tier because the decision span ends before the httpx call, so the orders spans descend from the httpx CLIENT span, which is its sibling. Open the trace: the gateway shows checkout.decide_tier with user.vip=true and order.items=12, and orders shows orders.write_items with twelve Postgres spans as its children instead of twelve spans hanging directly off the server span. The trace from step 2 and this one have the same edges; only this one explains itself, and the question it answers was not expressible in step 2.6. Measure the overhead. Turn the fault off, raise load, and time 500 checkouts with telemetry on and off. Save as bench.py:
import time, urllib.request, statistics, concurrent.futures as cf
def one(i):
t = time.perf_counter()
urllib.request.urlopen(f"http://localhost:8080/checkout?user={i % 1000 + 1}&items=3").read()
return (time.perf_counter() - t) * 1000
with cf.ThreadPoolExecutor(8) as ex:
ms = sorted(ex.map(one, range(500)))
print(f"p50 {ms[249]:.1f} ms p99 {ms[494]:.1f} ms mean {statistics.mean(ms):.1f} ms")for sdk in false true; do
OTEL_SDK_DISABLED=$sdk FAULT_N_PLUS_ONE=0 LOADGEN_RPS=20 \
docker compose --profile telemetry up -d gateway orders payments loadgen
sleep 20; echo "OTEL_SDK_DISABLED=$sdk"; python3 bench.py
docker stats --no-stream --format '{{.Name}} {{.CPUPerc}}' | grep -E 'gateway|orders|payments'
doneOTEL_SDK_DISABLED=true makes services/common/telemetry.py return before it installs any instrumentor, so the difference between the two runs is the whole cost: the wrappers, span creation and export. Write both numbers down; you will reuse them in the cost chapter.FAULT_N_PLUS_ONE=1 and LOADGEN_RPS=50 and re-run the benchmark with the SDK on. Every item is now a query and every query is a span, so span volume grows with cart size: VIP checkouts produce three times as many. CPU on orders climbs faster than request rate, and if the collector cannot keep up the orders logs start showing export failures as the batch processor’s 2048-span queue fills and drops. Auto-instrumentation turned a database bug into a telemetry bug as well. Now switch off the Postgres instrumentation on orders. Under opentelemetry-instrument that is OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=psycopg; the lab calls the instrumentors in code, which ignores that variable, so comment out the PsycopgInstrumentor().instrument(…) line in services/common/telemetry.py and rebuild orders. Overhead falls, and your orders.write_items span still shows the loop’s duration and item count, which is enough to find the N+1 without a span per query. Put the stack back before the next chapter: git checkout – services/common/telemetry.py and FAULT_N_PLUS_ONE=0 LOADGEN_RPS=5 OTEL_SDK_DISABLED=false docker compose –profile telemetry up -d –build. The manual spans in gateway and orders can stay; later chapters do not depend on them.A platform team proposes rolling out an eBPF-based zero-code agent (OBI/Beyla style) to every node in the Kubernetes fleet and telling application teams they no longer need to add any OpenTelemetry SDK. The fleet is 60 services: 30 Go, 20 Java, 10 Python. What do you recommend?
- DOC Zero-code instrumentation: Python
The install and run commands for opentelemetry-distro, opentelemetry-bootstrap and opentelemetry-instrument, with the configuration options. Read the troubleshooting subpages before you put it behind gunicorn or uvicorn workers.
- DOC Java agent
How the agent attaches, how to configure and suppress instrumentations, and the performance page that names JDBC and Redis as the main overhead sources. The supported-libraries list on GitHub shows what you get for free.
- DOC Instrumentation concepts
The official framing of zero-code versus code-based instrumentation and why you combine them. Short; read it to align vocabulary with your team.
- DOC Instrumenting libraries
Written for library authors, useful for application teams: what a good span looks like, when to create one, and why libraries use only the API. Skip the packaging details.
- DOC OpenTelemetry FastAPI instrumentation
The knobs the lab touches: excluded URLs, server request hooks for enriching spans, header capture and the exclude_spans option for the ASGI send and receive spans.
- CODE OpenTelemetry Go instrumentation (eBPF)
The eBPF-based zero-code project for Go. Read the how-it-works document to see what reading function arguments from outside the process involves, and the compatibility list to see what it cannot cover.
- PAPER Dapper, a Large-Scale Distributed Systems Tracing Infrastructure Sigelman et al., 2010
The original argument for instrumenting a few shared libraries (RPC, threading, control flow) to get near-universal coverage, and its admission that application-level annotations were what made traces useful. Read: sections 1, 2.2 (instrumentation points) and 2.3 (annotations).
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.