Covers what distributed tracing is, the trace and span model with parent/child links and ids, and why correlated logs alone can't show where time goes across services.
Distributed tracing records the path of one request through every service it touches. A trace is the whole operation; a span is one timed piece of work inside it, such as an incoming HTTP request, a SQL query or a Service Bus send. Every span in a trace shares a trace id (16 bytes, written as 32 hex characters), has its own span id (8 bytes, 16 hex characters), and points to its parent span id, so the spans form a tree you can view as a waterfall.
The ids travel between services in the W3C traceparent header, with optional vendor-specific data in tracestate. In .NET a span is a System.Diagnostics.Activity, and OpenTelemetry exports it.
Logs alone tell you what happened in each service, but not which call caused which or where the 2 seconds went. Traces give you causality and timing; logs give you detail. The trade-off is volume: traces are expensive, so you sample them.
"Distributed tracing follows a single request as it moves through all the services involved. The unit is the span: a named, timed operation with a start and end time, attributes like the HTTP route or the SQL statement, and a status. Spans in the same request share a trace id, and each span records its parent span id, so together they form a tree. The root span is usually the first incoming HTTP request; children are the outgoing HTTP calls, database queries and messages it triggers.
In .NET the span type is
System.Diagnostics.Activity. ASP.NET Core starts an activity for every request,HttpClientstarts a child for every outgoing call and writes thetraceparentheader, and the receiving service reads that header and continues the same trace. OpenTelemetry collects those activities and exports them to Application Insights, Jaeger or any OTLP backend, where you see a waterfall: the order of calls, how long each took, and which one failed.The mistake I see is thinking correlated logs are enough. If every log line carries a correlation id you can find all the lines for a request, but you still can't see that the checkout took 2.4 seconds because the pricing service made 40 sequential calls to the stock service. Logs give you events; traces give you causality and timing. In practice you want both, linked by the trace id, so you can go from a slow span straight to its logs. Traces show you where to look; logs tell you what happened there."
| Term | What it is | .NET type |
|---|---|---|
| Trace | One end-to-end operation, identified by a 16-byte trace id | ActivityTraceId |
| Span | One timed unit of work in the trace | Activity |
| Span id | 8-byte id unique to the span | ActivitySpanId |
| Parent span id | The span that caused this one; empty for the root | Activity.ParentSpanId |
| Span kind | Server, Client, Producer, Consumer or Internal | ActivityKind |
| Attributes | Key/value data such as http.route, db.system |
Activity.SetTag |
| Events | Timestamped points inside a span, such as an exception | Activity.AddEvent |
| Status | Unset, Ok or Error | Activity.SetStatus |
| Signal | Answers | Weakness |
|---|---|---|
| Metrics | Is something wrong? How much? | No detail about any single request |
| Logs | What exactly happened in this service? | No timing tree across services |
| Traces | Where did this request spend its time, and which call failed? | High volume, so usually sampled |
POST /checkout [=============================] 2,400 ms
GET pricing/quote [==========================] 2,150 ms
GET stock/item/1 [=] 50 ms
GET stock/item/2 [=] 50 ms
... 38 more sequential calls
INSERT Orders [=] 30 ms
No log query shows the N+1 call pattern this clearly.
A checkout endpoint had a p95 of 2.4 s while every service's own logs showed nothing slower than 60 ms. The trace waterfall showed 40 sequential calls from pricing to stock, about 50 ms each. Replacing them with one batch call dropped checkout p95 to 280 ms.
Checks that the candidate understands the trace and span model well enough to read a waterfall and knows what tracing adds over logs.
Green flags
traceparent propagation and Activity in .NETRed flags
OpenTelemetry defines a span as: trace id, span id, parent span id, name, kind, start and end timestamps, attributes, events, links and status. A trace is not a stored object; it is just all the spans that share a trace id. The backend reassembles the tree from the parent ids.
trace 4bf92f35...
span a1 (root, Server) POST /checkout
span b2 (Client) GET pricing parent=a1
span c3 (Server) GET /quote parent=b2 <- in the pricing service
span d4 (Client) SQL SELECT parent=c3
Note the pair at each hop: a Client span in the caller and a Server span in the callee. The gap between them is network and queueing time.
Inside a process, the current span lives in Activity.Current, which is backed by an AsyncLocal<Activity> so it flows across await. Across processes it must be written into the request. The W3C Trace Context standard uses:
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
| | | |
version trace id (32 hex) parent span id flags (01 = sampled)
The callee reads the header, creates its server span with the same trace id and with 00f067aa0ba902b7 as the parent.
Activity per request and reads traceparent.HttpClient (through SocketsHttpHandler) creates a child activity per call and injects traceparent.SqlClient emit diagnostics that OpenTelemetry instrumentation turns into spans.An Activity is only created when a listener (such as the OpenTelemetry SDK) is interested, so tracing costs almost nothing when it is off.
A correlation id lets you group log lines. It does not record:
You could reconstruct this from logs with enough discipline, but you would be rebuilding tracing by hand.
Each span is roughly 0.5–2 KB once exported. A request touching 6 services with 20 spans at 500 requests per second is about 10,000 spans per second. That is why production tracing uses sampling, and why metrics (cheap, pre-aggregated) stay the primary alerting signal.
HttpClient. Add AddOpenTelemetry().WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddConsoleExporter()) to both and compare the trace ids printed.Activity.Current?.TraceId in both services and confirm it matches the incoming traceparent header.docker run -p 16686:16686 -p 4317:4317 jaegertracing/jaeger) and switch to the OTLP exporter to see the waterfall.Task.Delay(500) in B and find it in the waterfall.Task.WhenAll, and compare the two waterfalls.Minimal tracing for a service that calls another one. Everything here produces spans without custom code.
// Program.cs (.NET 10). Packages: OpenTelemetry.Extensions.Hosting,
// OpenTelemetry.Instrumentation.AspNetCore, OpenTelemetry.Instrumentation.Http,
// OpenTelemetry.Exporter.OpenTelemetryProtocol
using System.Diagnostics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry()
.ConfigureResource(r => r.AddService("checkout-api")) // service.name groups spans per service
.WithTracing(t => t
.AddAspNetCoreInstrumentation() // Server span per incoming request, reads traceparent
.AddHttpClientInstrumentation() // Client span per outgoing call, writes traceparent
.AddOtlpExporter()); // OTEL_EXPORTER_OTLP_ENDPOINT decides where
builder.Services.AddHttpClient("pricing", c => c.BaseAddress = new Uri("http://pricing"));
var app = builder.Build();
app.MapPost("/checkout", async (IHttpClientFactory factory, ILogger<Program> logger, CancellationToken ct) =>
{
// The same trace id appears in this log line, so logs and traces join up.
logger.LogInformation("Checkout started, trace {TraceId}", Activity.Current?.TraceId);
var quote = await factory.CreateClient("pricing").GetStringAsync("/quote", ct);
return Results.Ok(quote);
});
app.Run();
# Run Jaeger v2 locally; it accepts OTLP on 4317 (gRPC) and 4318 (HTTP)
docker run --rm -p 16686:16686 -p 4317:4317 -p 4318:4318 jaegertracing/jaeger:latest
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
operation_Id in Application Insights).X-Correlation-Id header and ignoring traceparent. Why it is wrong: no tooling understands it, and it breaks at every library boundary. Instead: use W3C Trace Context, which .NET writes by default.Tracing is the signal that answers where, so it earns its keep in systems with more than two or three hops or with asynchronous messaging. In a single monolith with one database, good request logging and a profiler often give you the same answers more cheaply. What makes tracing work is less the SDK and more the discipline: one context format (W3C) everywhere, a service.name on every service, and the trace id stamped on every log line.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Correlated logs only | Monolith, few hops | Low | Many services or queues |
| OpenTelemetry auto-instrumentation | Any ASP.NET Core service | Low setup, moderate data volume | Never a bad start |
| Auto + custom business spans | Complex flows, messaging | More code to maintain | Spans for every method (noise) |
Two mechanisms work together.
using (logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = id })) adds properties to every log inside the block, flowing across await via AsyncLocal. ASP.NET Core already opens a scope per request with RequestId and RequestPath.Activity whose trace id comes from the incoming W3C traceparent header or is created new. With ActivityTrackingOptions (on by default in the Generic Host) every log carries TraceId and SpanId. HttpClient propagates traceparent automatically; message queues need it copied into message properties (the Azure Service Bus SDK does this).So the trace id is your correlation id; add business ids as properties. The trade-off: custom correlation headers are easy but don't interoperate with tracing tools.
OpenTelemetry gives you three correlated signals: traces (a span per operation, linked by trace id), metrics (cheap aggregated counters and histograms) and logs (events that carry the TraceId and SpanId of the span they were written in).
In .NET the runtime already emits Activity and Meter data; you call AddOpenTelemetry() with WithTracing, WithMetrics and WithLogging, set a resource (service.name), and choose an exporter: UseOtlpExporter() for any OTLP back end or Collector (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT or options), or the Azure Monitor distro (UseAzureMonitor()) for Application Insights.
For cost: metrics for rates and latency (never sampled), sampled traces (the distro now defaults to a rate-limited sampler of 5 traces per second, which adapts the kept percentage to load; you can change the rate or switch to a fixed SamplingRatio), level-filtered logs, and tail sampling in a Collector, configured with policies to keep errors and slow traces. The trade-off is completeness versus ingestion cost.
I start from AppRequests for the time window and compute the failure rate by OperationName in 5-minute bins, rendered as a timechart, to see which endpoint broke and when. Then I break failures down by ResultCode, AppRoleName and, from AppExceptions, by ProblemId/ExceptionType, and check AppDependencies for the downstream Target that failed. To follow one request, I take its OperationId, which is the W3C trace id, and union requests, dependencies, exceptions and traces filtered on it, ordered by time. Finally I compare with a baseline and save the useful query as an alert. The trade-off: KQL lets you answer almost anything, but only if the telemetry is structured and correlated in the first place.
Last updated 23 Nov 2026.