Distributed Tracing with OpenTelemetry
30-second answer
Distributed tracing follows one request across every service it touches. OpenTelemetry records each step as a span, and every span in the request shares one trace ID, passed between services in the W3C traceparent header. In Python, install azure-monitor-opentelemetry and call configure_azure_monitor() with your Application Insights connection string. Requests, Flask, FastAPI, Django, psycopg2 and Azure SDK calls are traced automatically, and tracer.start_as_current_span() adds your own spans.
Exam objective: 4.2.1 Trace distributed systems by using OpenTelemetry SDKs. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
One call to <code>configure_azure_monitor()</code> sends traces, metrics and logs from every service to this resource.
👆 Click the glowing item in the portal to continue
Read the steps as text
- One call to configure_azure_monitor() sends traces, metrics and logs from every service to this resource.
- The application map draws every service and dependency from the traces. Most of the 2.4 s is the model call.
- In Transaction search, open the slow 6.8-second request.
- End-to-end transaction details puts every span from every service on one timeline, joined by the trace ID.
- The span attributes explain it: 3,900 output tokens. Lower max_tokens or stream the answer.
- Failures groups exceptions by type. Each sample opens the same end-to-end view, so you see what led up to the error.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
A trace across services
One user question goes web API → queue → worker → Cosmos DB → model. OpenTelemetry gives every hop a span that shares one trace ID, so you see the whole journey. The Azure Monitor OpenTelemetry Distro sends it to Application Insights.
🤔 What happens if…
Read this tour as text
- Secrets don’t belong in code. A connection string in
config.pyends up in git, in screenshots and in old laptops. Azure Key Vault stores secrets, keys and certificates. The app reads them at run time with a managed identity, so there’s no password to steal. - Versions and rotation. Each time you set a secret, Key Vault keeps a new version. Apps that ask for the secret without a version get the latest. Rotation creates a new version: for keys, a rotation policy does it on a schedule; for secrets, Key Vault raises a
SecretNearExpiryevent through Event Grid and your function sets the new value. Apps pick it up without a redeploy. - App Configuration. Azure App Configuration holds settings as key-values with optional labels (dev, prod) and feature flags. It can point at Key Vault with Key Vault references. Apps refresh settings without restarting, often by watching a sentinel key.
- A trace across services. One user question goes web API → queue → worker → Cosmos DB → model. OpenTelemetry gives every hop a span that shares one trace ID, so you see the whole journey. The Azure Monitor OpenTelemetry Distro sends it to Application Insights.
- Find the slow span. The trace shows each span’s duration. Here the model call is fine, but a Cosmos DB query without a partition key takes 2.4 seconds. Custom spans and attributes (like
tenant.id) make the story even clearer. - Logs live in tables. Application Insights and Log Analytics store telemetry in tables:
requests,dependencies,exceptions,traces, plus metrics. Container Apps logs land inContainerAppConsoleLogs_CL, AKS inContainerLogV2. - Ask with KQL. Kusto Query Language (KQL) reads top to bottom through pipes:
requests | where success == false | summarize count() by bin(timestamp, 5m) | render timechart.wherefilters,summarizeaggregates,projectpicks columns,joincombines tables. - Turn a query into an alert. A log search alert runs a KQL query on a schedule and fires when the result crosses a threshold. A metric alert watches a number like CPU or queue length. Either can email the team or call a webhook.
A user says "the chat hung". Instrument the app with OpenTelemetry, find the failed request with KQL, follow its operation_Id to the slow model call, measure dependencies and set an alert so you hear about it first next time.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
Answers are slow and five services each blame another.
😊 THE SOLUTION
Trace one request across every service with OpenTelemetry.
- No shared view✓ One trace ID end to end
- Unknown slow step✓ Span durations
- Missing context✓ Custom attributes
Start with a question
The chatbot takes nine seconds to answer. Five services are involved. Which one is slow?
The web team says the API is fine. The data team says Cosmos DB is fine. The AI team says the model replies in two seconds. Everyone shows you their own logs, and none of them line up.
What you need is one view of one request: when it hit the API, when it went on the queue, how long the worker spent in Cosmos DB, how long the model took. That’s distributed tracing, and OpenTelemetry is the standard way to collect it. In Azure, the data lands in Application Insights, where you can see the whole journey on one screen.
Explain it like I’m 10
Visual: distributed tracing in motion
Follow one request through five services and watch the trace ID turn scattered logs into one timeline.
Read the video script
- One question, five stopsOne chatbot question goes through five places. The web API, a Service Bus queue, a worker, Cosmos DB and the model. Each team has its own logs, and every team says their part is fast.
- One trace ID rides alongOpenTelemetry gives the request a trace ID, thirty-two hex characters, and passes it on in the traceparent header. The Azure SDK even carries it through the Service Bus message, so the trace survives the queue.
- Every hop records a spanAt every hop, a span gets recorded. A span is one timed step, with its own ID and a parent. All five share the same trace ID, so they line up as one story.
- The waterfall shows the slow hopPut the spans on one timeline and the answer jumps out. The Cosmos DB query takes two point four seconds. That's most of the wait, and nobody has to argue about it.
- Attributes add the whyAdd attributes to your spans, like tenant dot id. Now you can check whether it's slow for everyone or only for one customer. Just keep prompts, personal data and secrets out of them.
- Spans land in two tablesIn Application Insights, server and consumer spans become rows in the requests table. Client and producer spans go into dependencies. Both carry operation underscore Id, which is the trace ID, so one query joins the lot.
- The application mapLast, the application map. Each service shows up under its cloud role name, which comes from O T E L service name. You see call times on every node, and the slow one is red before you open a single log.
The technical explanation
The words you need
| Term | Meaning | Example |
|---|---|---|
| Trace | One request end to end | A user’s question, from browser to answer |
| Span | One timed step, with a span ID and a parent | POST /ask, cosmos query, chat completion |
| Trace ID | 32 hex characters shared by every span in the trace | 4bf92f3577b34da6a3ce929d0e0e4736 |
| Span kind | Server, client, producer, consumer or internal | Incoming HTTP is server; outgoing call is client |
| Attributes | Key-value detail on a span | tenant.id = "contoso", http.route = "/ask" |
| Resource | Who produced the telemetry | service.name = "chat-api" |
Context propagation is what links services. When chat-api calls retriever over HTTP, OpenTelemetry adds a W3C traceparent header:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
ver trace ID (32 hex) parent span (16) flags (01 = sampled)
The receiving service reads it and starts its span as a child of 00f067aa0ba902b7, in the same trace. Azure SDK instrumentation does the same for Service Bus and Event Hubs messages, so a trace survives a queue.
Turn it on with the Azure Monitor OpenTelemetry Distro
pip install azure-monitor-opentelemetry
export APPLICATIONINSIGHTS_CONNECTION_STRING="InstrumentationKey=...;IngestionEndpoint=https://...;ApplicationId=..."
export OTEL_SERVICE_NAME="chat-api" # becomes the cloud role name on the application map
# app.py: configure BEFORE importing and creating the web app
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor(
# connection_string=... is optional when the environment variable is set
logger_name="chat", # send logs from this logger to Application Insights too
sampling_ratio=1.0, # keep every trace in dev; lower it in production
)
from flask import Flask
import requests
app = Flask(__name__)
That one call sets up traces, metrics and logs and switches on the bundled automatic instrumentation:
| Library | What you get for free |
|---|---|
| Flask, FastAPI, Django | A server span per incoming request |
| requests, urllib, urllib3 | A client span per outgoing HTTP call, plus the traceparent header |
| psycopg2 | A span per PostgreSQL query |
| Azure SDK (azure-core) | Spans for Cosmos DB, Service Bus, Storage, Key Vault and other Azure client calls |
Add your own spans
Automatic spans show where time went. Custom spans and attributes say what the app was doing.
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
tracer = trace.get_tracer(__name__)
@app.post("/ask")
def ask():
with tracer.start_as_current_span("retrieve-context") as span:
span.set_attribute("tenant.id", tenant_id)
span.set_attribute("retrieval.top_k", 5)
chunks = search(question) # Cosmos DB call: an automatic child span
with tracer.start_as_current_span("generate-answer") as span:
span.set_attribute("gen_ai.request.model", deployment)
try:
answer = call_model(chunks, question)
except Exception as ex:
span.record_exception(ex)
span.set_status(Status(StatusCode.ERROR))
raise
return {"answer": answer}
start_as_current_span makes the new span the current one, so anything called inside it (including automatic spans) becomes its child. Keep prompts, personal data and secrets out of attributes: they’re stored and searchable.
Where you read it in Application Insights
- Application map: one node per cloud role name, with call counts, failure rates and average durations on the arrows.
- Transaction search and the end-to-end transaction details view: every span of one trace as a timeline, so the 2.4-second Cosmos DB query stands out.
- Failures and Performance: grouped by operation, with drill-down into sample traces.
Server spans become rows in the requests table, client and internal spans in dependencies, recorded exceptions in exceptions, and logs in traces. They’re joined by operation_Id, which is the trace ID.
Sampling and naming
- Sampling keeps a share of traces.
sampling_ratio=0.1keeps about 10%. The decision travels in the trace flags, so a kept trace is kept by every service and stays complete. If you don’t set anything, current versions of the distro use a rate-limited sampler of about 5 traces per second, and theOTEL_TRACES_SAMPLER/OTEL_TRACES_SAMPLER_ARGenvironment variables win over code options. - Resource attributes identify the service. Set
OTEL_SERVICE_NAME, orOTEL_RESOURCE_ATTRIBUTES="service.name=chat-api,service.namespace=tailspin,service.instance.id=pod-7". Application Insights uses them for the cloud role name and role instance.
Architect level Why the distro and not the raw OpenTelemetry SDK?
You could install the OpenTelemetry SDK, the Azure Monitor exporter and each instrumentation library yourself, then wire up tracer, meter and logger providers. The distro does that in one call with sensible defaults, adds live metrics and Microsoft Entra ID authentication for ingestion, and stays on supported versions. Because it’s still OpenTelemetry underneath, your custom spans use the standard opentelemetry API, so moving to another backend later means changing the exporter, not your code. If you need an instrumentation the distro doesn’t bundle (say, Redis), install the community package and it plugs into the same pipeline.
Real-world business scenario
Fabrikam Insurance (fictional)
- The problem
- A claims assistant took up to 12 seconds to answer. The API, retrieval worker and model gateway each had separate logs, and every team believed its part was fast.
- What they used
- The Azure Monitor OpenTelemetry Distro in all three Python services, a distinct OTEL_SERVICE_NAME per service, custom spans for retrieval and generation with tenant.id attributes, and 25% sampling in production.
- Why that choice
- One trace ID joined the spans across the HTTP call and the Service Bus queue, and the end-to-end transaction view showed the timeline in one place.
- The result
- The trace showed a Cosmos DB query with no partition key taking 7 seconds. Fixing the query brought answers under 3 seconds, and the team now watches the application map instead of arguing in chat.
When to use it and when not to
✓ Use it when…
- A request crosses more than one service, queue or database.
- You need to find which step is slow or failing, not just that something is.
- You want vendor-neutral instrumentation that sends to Application Insights today and could send elsewhere later.
✕ Think twice when…
- Logging every user prompt and answer in spans. Use a proper, governed store for that.
- Keeping 100% of traces for a busy production service. Turn on sampling.
↔ Alternatives to consider
- KQL in Log Analytics to query the same telemetry and build alerts.
- Azure Monitor metrics for cheap, always-on numbers like request rate and CPU.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner What's the difference between a trace and a span?
Model answer
A span is one step, like "call Cosmos DB" or "POST /ask", with a start time and a duration. A trace is the whole request: all the spans that share one trace ID, arranged as a tree of parents and children.
Intermediate How does the trace ID get from the web API to the worker?
Model answer
Through context propagation. For HTTP, OpenTelemetry adds the W3C traceparent header to the outgoing call, and the instrumentation on the receiving side reads it and continues the same trace. For messaging, the Azure SDK instrumentation puts the context in the message properties.
Interviewer follows up
What's in the traceparent header?
You
A version, the 32-character trace ID, the 16-character parent span ID and trace flags, such as 00-4bf92f35...-00f067aa...-01. The last part says whether the trace was sampled.
Experienced developer What does configure_azure_monitor() give you out of the box in Python?
Model answer
It wires up the OpenTelemetry SDK with the Azure Monitor exporter for traces, metrics and logs, and turns on the bundled instrumentations: Django, FastAPI, Flask, requests, urllib and urllib3, psycopg2 and Azure SDK tracing. I add custom spans only for the business steps I care about, like retrieval and the model call.
Scenario Every service appears as the same node on the application map. Why?
Model answer
They're not setting a service name, so the cloud role name is a default for all of them. I'd set OTEL_SERVICE_NAME, or service.name in OTEL_RESOURCE_ATTRIBUTES, to a different value per service, like chat-api and summary-worker.
Architecture & design Tracing costs are climbing. What would you change?
Model answer
Turn on sampling, for example sampling_ratio=0.2 in configure_azure_monitor, so about one trace in five is kept but each kept trace stays whole across services. I'd also drop noisy spans and big attributes, and keep alerts on metrics, which aren't affected by trace sampling in the same way.
Quick revision
Key points
- A trace is one request; spans are its steps; all spans share a trace ID.
- W3C traceparent carries the trace ID and parent span ID between services.
- pip install azure-monitor-opentelemetry, then configure_azure_monitor() at startup.
- The connection string comes from APPLICATIONINSIGHTS_CONNECTION_STRING or the connection_string argument.
- Automatic instrumentation covers Flask, FastAPI, Django, requests, urllib, psycopg2 and Azure SDK calls.
- Custom spans use trace.get_tracer(__name__) and start_as_current_span, with set_attribute and record_exception.
- service.name sets the cloud role name on the application map.
Important terminology
- OpenTelemetry
- An open, vendor-neutral standard and set of SDKs for collecting traces, metrics and logs from applications.
- Trace
- The full record of one request as it moves through every service, made of spans that share a trace ID.
- Span
- One timed operation inside a trace, such as an HTTP request, a database query or a model call, with a span ID and a parent.
- traceparent
- The W3C Trace Context HTTP header that carries the trace ID and parent span ID from one service to the next.
- Azure Monitor OpenTelemetry Distro
- Microsoft's packaged OpenTelemetry setup (azure-monitor-opentelemetry for Python) that sends telemetry to Application Insights.
- Cloud role name
- The service name Application Insights shows on the application map, taken from the service.name resource attribute.
- Sampling
- Keeping only a share of traces to cut cost and volume, while keeping each kept trace complete.
Common mistakes
- Calling configure_azure_monitor() after the web framework is already imported and serving, so early requests aren't traced.
- Putting user prompts or secrets in span attributes.
- Leaving every service with the default service name, so the application map is useless.
Exam tips
- "Send OpenTelemetry data from Python to Application Insights with least code" = azure-monitor-opentelemetry + configure_azure_monitor().
- "Correlate a request across services" = shared trace ID via traceparent.
- "Add business detail to a span" = set_attribute.
- "Name each service on the application map" = service.name resource attribute.
Five quick revision questions
-
1.Which environment variable holds the Application Insights connection string?Show
APPLICATIONINSIGHTS_CONNECTION_STRING.
-
2.Which method starts a custom span and makes it current?Show
tracer.start_as_current_span().
-
3.Which header carries trace context over HTTP?Show
traceparent (W3C Trace Context).
-
4.Which Application Insights view shows every service and the calls between them?Show
The application map.
-
5.Which span method attaches an exception to the span?Show
record_exception().
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: KQL Queries for Logs and Metrics
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.