Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 27 of 28
❮Prev Next❯

Distributed Tracing with OpenTelemetry

Module 4: Secure & Monitor ⏱ 11 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Follow one request with the application map and transaction details Open the application map and an end-to-end transaction.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. One call to configure_azure_monitor() sends traces, metrics and logs from every service to this resource.
    2. The application map draws every service and dependency from the traces. Most of the 2.4 s is the model call.
    3. In Transaction search, open the slow 6.8-second request.
    4. End-to-end transaction details puts every span from every service on one timeline, joined by the trace ID.
    5. The span attributes explain it: 3,900 output tokens. Lower max_tokens or stream the answer.
    6. 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.

    😟 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
    🛠️ Solved with: OpenTelemetry tracing

    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.

    ▶ Explainer video See it in motion 7 steps · 1 min 48 sec

    An animation of one chatbot request crossing a web API, Service Bus, a worker, Cosmos DB and a model. Each hop records a span sharing one trace ID carried in the W3C traceparent header, a waterfall timeline shows a slow 2.4-second Cosmos DB span, attributes such as tenant.id add context, spans land in the Application Insights requests and dependencies tables joined by operation_Id, and the application map shows each cloud role name.
    Read the video script
    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    6. 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.
    7. 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

    TermMeaningExample
    TraceOne request end to endA user’s question, from browser to answer
    SpanOne timed step, with a span ID and a parentPOST /ask, cosmos query, chat completion
    Trace ID32 hex characters shared by every span in the trace4bf92f3577b34da6a3ce929d0e0e4736
    Span kindServer, client, producer, consumer or internalIncoming HTTP is server; outgoing call is client
    AttributesKey-value detail on a spantenant.id = "contoso", http.route = "/ask"
    ResourceWho produced the telemetryservice.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:

    LibraryWhat you get for free
    Flask, FastAPI, DjangoA server span per incoming request
    requests, urllib, urllib3A client span per outgoing HTTP call, plus the traceparent header
    psycopg2A 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.1 keeps 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 the OTEL_TRACES_SAMPLER / OTEL_TRACES_SAMPLER_ARG environment variables win over code options.
    • Resource attributes identify the service. Set OTEL_SERVICE_NAME, or OTEL_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

    Insurance

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    You need to send traces, metrics, and logs from a Python FastAPI app to Application Insights by using OpenTelemetry. The solution must require the least amount of code. What should you do?

    Question 2

    Question 2 of 5

    A web API calls a retrieval service over HTTP. Both services are instrumented with OpenTelemetry. In Application Insights, the spans from both services appear in the same end-to-end transaction. What allows the spans to be correlated?

    Question 3

    Question 3 of 5

    A developer has obtained a tracer by calling tracer = trace.get_tracer(__name__). The developer wants a custom span named retrieve-context, and any calls made inside the block must appear as child spans.

    Which code should the developer use?

    Question 4

    Question 4 of 5

    Three Python services send telemetry to the same Application Insights resource by using the Azure Monitor OpenTelemetry Distro. On the application map, all three services appear as a single node. What should you configure so that each service appears as its own node?

    Question 5

    Question 5 of 5 · Select 2

    Inside a custom span, a call to a model deployment raises an exception. You need the span to show the failure and the exception details in Application Insights. Which TWO actions should you perform? Each correct answer presents part of the solution.

    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. 1.Which environment variable holds the Application Insights connection string?Show

      APPLICATIONINSIGHTS_CONNECTION_STRING.

    2. 2.Which method starts a custom span and makes it current?Show

      tracer.start_as_current_span().

    3. 3.Which header carries trace context over HTTP?Show

      traceparent (W3C Trace Context).

    4. 4.Which Application Insights view shows every service and the calls between them?Show

      The application map.

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.