Home› Blog› Week 10 — A Log Says 256ms. A Trace Says Where It …
Azure Weekly Lab Azure Terraform

Week 10 — A Log Says 256ms. A Trace Says Where It Went.

Two container apps, one HTTP hop between them, and one trace that crosses it — so the 256 ms a user waits can be attributed to the service that actually spent it.

Verified against current vendor documentation on 24 October 2026. Pricing, limits and API behaviour were checked against the official docs on that date. Cloud services change fast — if you are reading this much later, treat the specifics as a starting point and re-check the linked sources.
OpenTelemetry Application Insights Container Apps ACR Terraform
Azure Platform Engineering Lab · Week 10 of 53

Lab Overview

The problem. A page is slow and the log says the request took 256 milliseconds. That is true and almost useless: the request passed through more than one service, and the log was written by one of them. Logs record what each service did separately; a trace records what happened to one request as it moved between them, which is where the time usually goes. Week 9 measured a 16.94-second cold start — a number that says how long and nothing about where.

The objective. Deploy two containerised services, one public and one internal, and make a single request to the public one produce a single trace spanning both — with the time attributed to whichever service spent it, and both images pulled from a private registry with no password stored anywhere. Done right, Application Insights draws the two services as connected without ever being told they are related.

DifficultyIntermediate — assumes containers and Terraform; the tracing concepts are introduced here
Time to completeRoughly an evening. Deployed resources were up about two hours, which is what the bill reflects
Deployment methodTerraform (azurerm + azapi), state in HCP Terraform, local execution
Source and lab guideweek-10-opentelemetry on GitHub — exact prerequisites, variables, commands, expected outputs and cleanup

Cloud Services and Concepts

ServicePurpose hereWhat it is
OpenTelemetry The vocabulary for spans and traces A vendor-neutral standard. The SDK inside the application is what creates the telemetry.
Managed OpenTelemetry agent Routes telemetry; does not create it Azure runs it inside the Container Apps environment at no compute cost. Point it at an uninstrumented app and you get a correctly configured pipeline carrying nothing.
Application Insights Where traces are stored and read Workspace-based here, so the data lands in week 08's Log Analytics workspace and inherits its table plans, retention and daily cap.
Azure Container Registry Where both images come from A private image store. The admin user is disabled, so the pull uses a managed identity holding AcrPull and no password exists anywhere in that path.
traceparent What makes two spans one trace A W3C header passed on the outbound call. Without it the backend starts its own trace and the hop between the services becomes invisible.

Architecture and Workflow

Architecture diagram. Both container images are pulled from a Basic container registry using a user-assigned managed identity holding AcrPull, with the registry admin user disabled, so no password exists in the pull path. Inside the Container Apps environment a public frontend calls an internal-only backend, passing a traceparent header so the two spans belong to one trace. Both apps export spans over OTLP gRPC to the managed OpenTelemetry agent that Azure runs inside the environment at no compute cost. The agent forwards traces and logs to Application Insights, which is workspace-based and stores them in week 08's Log Analytics workspace. Measured: frontend p50 256.4 ms, backend p50 250.8 ms.
The whole week on one page. Both images come from the registry with no password in the pull path. The request crosses one hop carrying a traceparent, while the spans leave each app sideways to the agent rather than along the request — which is why one trace can span two services.

What happens when somebody loads the page:

  1. A request arrives over HTTPS at the frontend, the only app with external ingress.
  2. The frontend opens a span for the request, then calls the backend over plain HTTP inside the environment. The HTTP client library attaches a traceparent header carrying the active span's id.
  3. The backend reads that header, so its own spans become children of the frontend's — one trace, two processes. It then sleeps 250 ms on purpose, so there is something unambiguous to attribute.
  4. Both apps export finished spans over OTLP gRPC to the managed agent, at an endpoint the platform injected into them. The agent forwards traces and logs on to Application Insights — but not metrics, a documented limitation rather than a misconfiguration.
  5. Being workspace-based, it writes into week 8's Log Analytics workspace, queryable as AppRequests and AppDependencies.

The decisions behind that shape.

DecisionTakenWhy not the alternative
Backend ingressinternalA publicly reachable backend would make the word “distributed” meaningless here
Samplerparentbased_traceidratioIndependent per-service samplers keep half a trace, which looks complete and is worse than keeping none
Agent configurationazapiazurerm has no argument for openTelemetryConfiguration

Prerequisites

  • Permissions: Contributor and User Access Administrator on the workload subscription. The second is easy to miss — the lab creates an AcrPull role assignment, and Contributor alone cannot create role assignments.
  • An existing Log Analytics workspace. This week writes into the one week 8 built and never creates its own. One subscription works fine; the lab splits the workload and the workspace across two.
  • Terraform 1.10+, azurerm 5.x and azapi 2.x, with HCP Terraform for state in local execution mode — so Azure credentials never leave the machine. No local Docker daemon, because the images build in Azure.
  • Region: the managed OpenTelemetry agent is in preview and not available everywhere. This lab runs in South Central US; check availability before changing it.
  • Builds on week 8 (the workspace) and week 9 (the Container Apps environment pattern). Neither needs to still be deployed.

Exact versions, the five resource providers the deploy script registers, the full variable list and the role scopes are in the lab guide on GitHub, which is the reproducible half of this write-up.

Implementation

Eleven resources, deployed in three passes — because a container app cannot reference an image tag that does not resolve yet. The registry must exist before a build can push to it, and the images must exist before the apps can pull them. One terraform apply from empty cannot work; the deploy script runs the three passes in order, and the guide lists every resource.

1. Create the state workspace first

Why it is required: the execution mode is fixed when the workspace is created — changing it later means re-authorising everything.

HCP Terraform workspace azure-week-10-dev showing execution mode Local, 11 resources, 8 outputs, and the resource list including the azapi_update_resource that configures the OpenTelemetry agent
Checkpoint: the workspace reports Local execution and, once deployed, 11 resources — including the azapi_update_resource that turns the agent on.

2. Write the code, split by decision

Why it is required: the application is the only thing that can create a span — so it lives in its own directory, away from the Terraform.

Repository structure for week 10: an app directory holding otel_setup.py plus the frontend and backend services, a terraform directory with registry.tf, observability.tf and apps.tf, and a scripts directory, each directory annotated with what it is responsible for
How the implementation is organised. app/ is the only code that knows what a span is; terraform/ is split by the decision each file makes. Full source on GitHub.

One setting in otel_setup.py is worth reading twice:

provider = TracerProvider(
    resource=Resource.create({"service.name": service_name}),
    sampler=ParentBasedTraceIdRatio(ratio),      # parentbased, deliberately
)
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))

OTLPSpanExporter() takes no endpoint argument. It reads one the platform injects — which is step 4.

3. Build the images in Azure

Why it is required: the build should not depend on what a particular laptop has installed. In production it runs in CI under week 7's federated credential rather than from a workstation at all.

Terminal output of az acr build with --no-logs, followed by az acr task list-runs showing Succeeded and az acr repository show-manifests showing the sha256 digest and the v2 tag
Checkpoint: az acr task list-runs reports Succeeded and show-manifests returns a digest for the expected tag. The run status is the truth here, not the CLI's exit code — see Troubleshooting.

4. Turn the agent on, and let it hand the app its destination

Why it is required: the apps must not hardcode where telemetry goes, so the same image works unchanged in an environment pointing somewhere else.

$ curl https://frontend.<env>.azurecontainerapps.io/otel-config

OTEL_EXPORTER_OTLP_ENDPOINT   http://k8se-otel.k8se-apps.svc.cluster.local:4317
OTEL_EXPORTER_OTLP_PROTOCOL   grpc
OTEL_RESOURCE_ATTRIBUTES      service.instance.id=frontend--0000001-…

Expected result: those three variables are present without Terraform ever setting them — which is why setting OTEL_EXPORTER_OTLP_ENDPOINT yourself sends spans nowhere.

5. Make a request, and look for one trace across two services

Application Insights application map showing two nodes, the frontend and the backend, joined by an arrow labelled 257.1 ms and 43 calls
Checkpoint: the application map shows two nodes joined by an arrow. Azure was never told these services are related — the traces say so.
Logs query on week 8's workspace showing five spans for one OperationId: frontend GET slash at 255.32 ms, frontend assemble-page at 254.654, frontend outbound GET at 254.256, backend GET slash api slash items at 250.844 whose ParentId equals the frontend outbound span id, and backend query-items at 250.139
Checkpoint, and the week's whole point: one operation, five spans, two services. The backend's ParentId is the frontend's outbound span Id. That is context propagation as data rather than as a diagram.

Validation and Evidence

A successful apply proves the resources exist. It says nothing about whether a trace crosses the process boundary, so that is tested separately. validate.sh runs 6 checks and 9 assertions against the live deployment, querying week 8's workspace directly — 9 passed / 0 failed on 2026-10-23.

TestExpectedActualStatus
Frontend GET /200 with backend data200, carrying the backend's payloadPASS
Backend reached from the internetnot reachable404 — internal ingressPASS
Registry admin userdisableddisabledPASS
App's registry credentialnonenone — identity onlyPASS
Request spans in week 8's workspacemore than zero663PASS
Operations containing both servicesmore than zero74PASS
Frontend GET / p50backend plus a little overhead256.4 msPASS
Backend GET /api/items p50about 250 ms, its deliberate sleep250.8 msPASS
Traces kept at sampler 0.2about 20 of 10016 of 100PASS
Half-traces at sampler 0.2none0PASS

What the latency rows prove. Of the 256.4 ms a user waits, 250.8 is the backend; the frontend's own work is about 5.6 ms. A log line had that 256 ms all along and could not say whose it was.

What the sampling rows prove. 100 requests at a 0.2 ratio kept 16 traces, every one containing both services and none half-captured — the keep decision taken once at the frontend and respected downstream.

Security and Cost

Security

  • No password exists in the image pull. The registry's admin user is off and the apps reference a managed identity rather than a credential — asserted by checking passwordSecretRef is absent, not assumed from the Terraform.
  • Least privilege on the role assignment: AcrPull, at the registry rather than the subscription, and pull only. Pushing is done by az acr build under a separate identity.
  • Network exposure: one app has external ingress. The backend has none, so the service-to-service hop is genuinely internal, and the 404 from outside is that control working.
  • One accepted trade-off. Application Insights has local authentication enabled — the argument week 8 deliberately disabled on the workspace. The managed agent authenticates with a connection string and Microsoft documents no ARM-authenticated alternative, so the choice is between having the agent and keeping the control. Two Microsoft-recommended controls pulling against each other in the same estate, three weeks apart.
  • What production adds: building in CI under a federated credential, Premium ACR for private endpoints, a sampler well below 1.0, and alerting on trace-derived metrics rather than only collecting them.

Cost

The agent itself is free: Microsoft provisions 0.5 vCPU and 1.5 GB inside the environment at no compute charge. You pay for the destination. ACR Basic at $0.1666/day, read from the retail price API, is the only standing charge; the container apps fell inside the monthly free grant, and traces land in week 8's workspace at its ingestion rate — which is why the sampler is a cost control and not a detail.

Measured: $0.0142 — read from Cost Management after teardown, not estimated. All of it is Container Registry, and at $0.1666/day that is about two hours of it, which is how long the lab was up.

Azure portal subscription overview for sub-lab-dev after teardown, showing current cost of one cent and a costs-by-resource chart naming acrwk10devscus001 as the only resource that cost anything
The whole bill, after teardown. One resource appears: the registry. The container apps, the environment and the OpenTelemetry agent cost nothing.

Troubleshooting and Lessons

A full table that read as empty.

  • Problem: validation reported zero traces for twenty minutes while 663 spans sat in the workspace.
  • Root cause: the managed agent writes AppRoleName as <environment>.<service>, not the bare OTEL_SERVICE_NAME, so a filter on 'frontend' matched nothing.
  • Resolution: match on the suffix — split(AppRoleName, '.')[-1] — rather than on the whole value.
  • Lesson learned: an empty result from a correct-looking query is indistinguishable from no telemetry at all. I theorised a gunicorn fork bug and rebuilt both images before running AppRequests | summarize count() with no filter, which would have settled it in thirty seconds. Count the rows before explaining why there are none.

A build that succeeded and reported failure.

  • Problem: az acr build exited 1 with UnicodeEncodeError, and the image was in the registry anyway.
  • Root cause: the CLI streams the build agent's log back to the console, and pip's progress bar is not encodable in cp1252. The crash is in the client's output handling, after the remote build has finished and pushed.
  • Resolution: queue with --no-logs and read az acr task list-runs for the outcome.
  • Lesson learned: when the work happens remotely, the server's recorded status is the result. The local exit code only describes the local process.

A latency number that was really about the health probe.

  • Problem: the first p50 came out at 0.7 ms for a service that sleeps 250 ms on purpose.
  • Root cause: liveness probes were 78% of all requests at 0.6 ms each, and a percentile over that population is a percentile about the probe.
  • Resolution: exclude probe paths from the latency query explicitly.
  • Lesson learned: excluding them is not tidying the data. Including them was measuring a different thing and calling it application latency.

Cleanup and Key Takeaways

Cleanup

$ ./scripts/cleanup.sh
   resource groups named rg-tracing-lab-dev-scus-001 : 0
   Microsoft.ContainerRegistry/registries            0
   Microsoft.App/managedEnvironments                 0
   Microsoft.Insights/components                     0
   week 08's workspace still there                   log-platform-prod-scus-001

The script deletes the resource group and then counts what is left, which is the difference between tearing down and believing you did. The registry and its images go with the group; they rebuild from app/ with one command, which is the test of whether a registry holds anything irreplaceable.

Preserve week 8's workspace — read, never owned, by this week, and the last line of the script exists to prove the teardown did not reach it. Still charging afterwards: nothing, though the traces already ingested sit in that workspace until its retention expires.

Key takeaways

  • The agent routes; the SDK creates. Enable the managed agent against an uninstrumented application and you get a correctly configured pipeline carrying nothing — every component healthy, no data.
  • One HTTP header is the whole mechanism. The backend's ParentId is the frontend's outbound span id. Nothing else joins the two processes, and nothing in Azure was told they were related.
  • Sample per trace, not per service. 16 of 100 kept, and not one of them half, because the decision was taken once and propagated.
  • An empty result is not evidence of an empty table. Twenty minutes went into a bug I invented because I trusted a filter instead of counting rows first.

References

Comments

How was your experience?
Your feedback helps improve this site.
PoorExcellent