📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is distributed tracing? Explain traces, spans and parent/child relationships, what a trace id and span id are, and why logs alone aren't enough to understand a request that crosses several services.

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.

Junior Theory Beginner distributed-tracing observability opentelemetry spans trace-context

🎯 Key points

  • A trace is one end-to-end operation; a span is one timed unit of work inside it
  • Trace id = 16 bytes (32 hex characters) shared by every span; span id = 8 bytes (16 hex characters) unique per span
  • Parent span id builds the tree; root span has no parent
  • Span carries name, kind (Server, Client, Producer, Consumer, Internal), start/end time, attributes, events and status
  • Context propagates in the W3C traceparent header, with vendor data in tracestate
  • Logs say what happened; traces show causality and where the time went (waterfall view)
  • In .NET a span is a System.Diagnostics.Activity; OpenTelemetry exports it
  • Logs carry the trace id so you can jump from a span to its logs and back

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, HttpClient starts a child for every outgoing call and writes the traceparent header, 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."


The vocabulary

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

Logs vs metrics vs traces

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

What a waterfall shows you

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.

Production example

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.

🔍 What the interviewer is checking

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

  • Defines trace, span, parent id and trace id precisely
  • Mentions traceparent propagation and Activity in .NET
  • Explains causality and timing as what logs lack
  • Knows built-in instrumentation produces most spans

Red flags

  • "Tracing is just logging with an id"
  • Can't say how the context gets to the next service
  • Thinks every request must be traced in production

📚 Learn in depth

1. The data model

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.

2. How context crosses a process boundary

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.

3. How .NET produces spans for free

  • ASP.NET Core creates an Activity per request and reads traceparent.
  • HttpClient (through SocketsHttpHandler) creates a child activity per call and injects traceparent.
  • EF Core and SqlClient emit diagnostics that OpenTelemetry instrumentation turns into spans.
  • Since .NET 5 the default id format is W3C, so ids are interoperable with other languages.

An Activity is only created when a listener (such as the OpenTelemetry SDK) is interested, so tracing costs almost nothing when it is off.

4. Why logs alone fall short

A correlation id lets you group log lines. It does not record:

  • causality: which call triggered which;
  • duration of each hop in a common time base;
  • concurrency: which calls ran in parallel and which in sequence.

You could reconstruct this from logs with enough discipline, but you would be rebuilding tracing by hand.

5. Cost

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.

Try it yourself

  1. Create two minimal APIs where A calls B with HttpClient. Add AddOpenTelemetry().WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddConsoleExporter()) to both and compare the trace ids printed.
  2. Log Activity.Current?.TraceId in both services and confirm it matches the incoming traceparent header.
  3. Run Jaeger locally (docker run -p 16686:16686 -p 4317:4317 jaegertracing/jaeger) and switch to the OTLP exporter to see the waterfall.
  4. Add a Task.Delay(500) in B and find it in the waterfall.
  5. Make A call B five times in a loop, then with Task.WhenAll, and compare the two waterfalls.

💻 Code

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

⚠ Common mistakes

  • Mistake: Treating a correlation id in logs as distributed tracing. Why it is wrong: it groups lines but records no causality, duration or parallelism. Instead: emit spans and put the trace id in every log line.
  • Mistake: Confusing the trace id with the span id. Why it is wrong: searching by span id finds one operation, not the whole request. Instead: search by the 32-hex trace id (operation_Id in Application Insights).
  • Mistake: Inventing a custom 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.
  • Mistake: Thinking tracing must be added by hand to every method. Why it is wrong: ASP.NET Core, HttpClient, SqlClient and EF Core already produce spans. Instead: turn on instrumentation first and add custom spans only for business steps.
  • Mistake: Expecting every request to be in the tracing backend. Why it is wrong: production tracing is usually sampled. Instead: use metrics for counts and rates, traces for examples.
  • Mistake: Reading a long parent span as the slow part. Why it is wrong: a parent's time includes its children. Instead: look for the span with the most self time, or the gap between a client span and its server span.

🏛 Senior insight: trade-offs

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)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions putting the trace id in logs or correlation ids Why: Checks they know how scopes, Activity and traceparent correlate logs across services
    How to answer

    Two mechanisms work together.

    • Log scopes: 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.
    • Distributed tracing: each request runs inside an 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.

  2. When: Candidate mentions OpenTelemetry or exporting to Application Insights Why: Checks they can set up the SDK, exporters and sampling end to end
    How to answer

    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.

  3. When: Candidate says they would follow a request by its trace id Why: Checks they can actually query a trace in KQL during an incident
    How to answer

    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.

↩ Usually asked after

More in Tracing

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me