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

πŸ“š Interview question

How do you correlate all the logs for one request across services? Explain log scopes with BeginScope, how Activity and the W3C traceparent header give you a trace id, how that id propagates to HttpClient calls and message queues, and whether you still need a custom correlation ID.

Log scopes and correlation in ASP.NET Core: ILogger.BeginScope and scope providers, the hosting scope (RequestId, RequestPath), ActivityTrackingOptions adding TraceId and SpanId, System.Diagnostics.Activity and AsyncLocal flow, W3C Trace Context (traceparent, tracestate, baggage), automatic propagation through HttpClient, propagating through Azure Service Bus messages, and when a business correlation ID is still useful.

Mid-Level Theory Intermediate aspnet-core correlation-id distributed-tracing log-scopes logging w3c-trace-context

🎯 Key points

  • BeginScope(state) attaches properties to every log written inside the using block; providers must support scopes (IncludeScopes for console)
  • Scopes flow with the async context (AsyncLocal), so they follow awaits but not fire-and-forget work started elsewhere
  • ASP.NET Core opens a hosting scope per request with RequestId and RequestPath, and starts an Activity for each request
  • ActivityTrackingOptions (TraceId, SpanId, ParentId by default with the Generic Host) add trace context to every log scope
  • W3C traceparent header = version-traceid-parentid-flags; HttpClient adds it automatically and ASP.NET Core reads it
  • Messages need explicit propagation: Azure Service Bus SDK stores Diagnostic-Id/traceparent in application properties; for custom transports use the OpenTelemetry Propagator
  • Use the trace id as the correlation id; add a business id (OrderId) as a property or baggage instead of inventing X-Correlation-ID
  • Return the trace id to clients (ProblemDetails traceId) so support can find the logs

⏱ 30-second 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"For one service, the tool is the log scope. logger.BeginScope(...) pushes a set of properties onto an async-local stack, and every log written inside that using block, in any class, gets those properties if the provider supports scopes. ASP.NET Core already opens one per request with RequestId, RequestPath and the connection id. I add my own for business context, like OrderId in a message handler, so I don't have to repeat it in every template.

Across services, the standard is W3C Trace Context. Every incoming request gets an Activity, and if the caller sent a traceparent header, the activity continues that trace, same trace id, new span id. The Generic Host sets ActivityTrackingOptions to include TraceId, SpanId and ParentId, so every log line carries them. When my code calls another API with HttpClient, the handler adds traceparent automatically, so the downstream service logs under the same trace id. Messages are the gap: they're asynchronous, so the trace context has to travel inside the message. The Azure Service Bus SDK writes it into the message's application properties; for a custom transport I use OpenTelemetry's propagator to inject and extract it.

The mistake I see is teams inventing an X-Correlation-ID header with custom middleware, while the platform already propagates a trace id that Application Insights, Jaeger and Grafana understand. Then they have two ids that don't match. I use the trace id as the correlation id, return it in ProblemDetails so support can quote it, and put business identifiers in properties or baggage. One id, propagated by the platform, beats a home-made one every time."


The pieces

Piece Scope Set by Carries
Log scope One process, one async flow BeginScope, hosting Any properties
Activity One operation (span) ASP.NET Core, HttpClient, SDKs, your code TraceId, SpanId, tags, baggage
traceparent header Between processes HttpClient, gRPC, messaging SDKs Trace id, parent span id, sampled flag
baggage header Between processes Your code Small key/value pairs (tenant, region)
Business id Domain Your code OrderId, PaymentId as properties

Propagation by transport

Transport Automatic? How
Incoming HTTP Yes Hosting reads traceparent
HttpClient Yes DiagnosticsHandler writes traceparent
gRPC Yes Same HTTP mechanism
Azure Service Bus / Event Hubs Yes, in SDK Diagnostic-Id / traceparent application property
RabbitMQ, custom queues, background jobs No Inject/extract with Propagators.DefaultTextMapPropagator
Fire-and-forget Task.Run Partly Activity flows via ExecutionContext, but the request may end first

Production example

In a checkout flow spanning [four] services and a Service Bus queue, support used to search five log stores by timestamp. After switching to trace context end to end and returning traceId in error responses, a support ticket with a trace id led to the full transaction in Application Insights in under [a minute], down from about [20 minutes].

πŸ” What the interviewer is checking

Checks whether the candidate can trace a request across services using the platform's built-in mechanisms rather than ad-hoc ids.

Green flags

  • Explains BeginScope, its async flow and IncludeScopes.
  • Knows Activity, traceparent format and automatic HttpClient propagation.
  • Identifies queues and background work as the places propagation breaks.
  • Returns the trace id to clients and keeps PII out of baggage.

Red flags

  • Builds a custom correlation middleware as the first answer.
  • Thinks scopes are global or thread-static.
  • Doesn't know how a trace continues through a message.

πŸ“š Learn in depth

1. How BeginScope works

ILogger.BeginScope<TState>(state) returns an IDisposable. The default LoggerFactoryScopeProvider keeps a linked stack of scopes in an AsyncLocal<Scope>. Providers that support scopes (ISupportExternalScope) walk the stack when writing a log. The console provider only prints them with IncludeScopes = true; OpenTelemetry includes them as attributes with IncludeScopes = true.

using (logger.BeginScope("{OrderId}", 42))          scope stack (AsyncLocal)
{                                                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    await repo.SaveAsync();  // logs here ────►    β”‚ OrderId = 42             β”‚
}                                                  β”‚ SpanId, TraceId, ParentIdβ”‚ ← ActivityTrackingOptions
                                                   β”‚ RequestId, RequestPath   β”‚ ← hosting scope
                                                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Passing a Dictionary<string, object> or a template with placeholders gives structured properties; passing a plain string gives one unnamed value.

2. Activity and W3C Trace Context

System.Diagnostics.Activity represents a span. Activity.Current is stored in an AsyncLocal, so it flows across await. The W3C traceparent header looks like:

traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             β”‚  β”‚                                β”‚                β”” flags (01 = sampled)
             β”‚  β”‚                                β”” parent span id (8 bytes)
             β”‚  β”” trace id (16 bytes)
             β”” version

ASP.NET Core's hosting diagnostics create an activity per request, using the incoming header as parent when present. Since .NET 5 the default id format is W3C.

3. Request flow across services

Browser ──► API Gateway ──► Orders API ──HttpClient──► Pricing API
            trace T, span A   trace T, span B           trace T, span C
                                   β”‚
                                   └── Service Bus message
                                       (application property traceparent = T-B)
                                                 β”‚
                                                 β–Ό
                                       Fulfilment worker: trace T, span D

All logs carry trace id T, so one query returns the whole transaction.

4. ActivityTrackingOptions

LoggerFactoryOptions.ActivityTrackingOptions decides which activity fields become scope properties: TraceId, SpanId, ParentId, TraceState, TraceFlags, Tags, Baggage. The Generic Host sets SpanId | TraceId | ParentId by default. You can add Baggage to log baggage items automatically.

5. Messaging and background work

For custom transports, inject the current context into message headers on send and extract it on receive:

Propagators.DefaultTextMapPropagator.Inject(new PropagationContext(Activity.Current!.Context, Baggage.Current), headers, setter);

then start a new Activity with the extracted parent context in the consumer. Hosted services have no ambient request, so start an activity per unit of work from your own ActivitySource.

6. Baggage and its risks

Baggage propagates key/value pairs to every downstream call, including third parties if you're careless. Keep it small and never put personal data or secrets in it.

Try it yourself

  1. Enable IncludeScopes on the JSON console and log inside a BeginScope; inspect the Scopes array.
  2. Call a second local API with HttpClient and compare the TraceId in both apps' logs.
  3. Send a request with a hand-written traceparent header via curl and confirm the API logs that trace id.
  4. Publish to a Service Bus queue (or the emulator) and check the Diagnostic-Id application property in Service Bus Explorer.
  5. Start a Task.Run without awaiting and log inside it after the request has finished; observe which scope values remain.

πŸ’» Code

Business scope in a handler, trace id returned to clients, and manual propagation for a custom queue.

// Program.cs
using System.Diagnostics;

var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddJsonConsole(o => o.IncludeScopes = true);

// Include baggage in log scopes as well as TraceId/SpanId/ParentId
builder.Logging.Configure(o => o.ActivityTrackingOptions =
    ActivityTrackingOptions.TraceId | ActivityTrackingOptions.SpanId |
    ActivityTrackingOptions.ParentId | ActivityTrackingOptions.Baggage);

builder.Services.AddHttpClient<PricingClient>(c => c.BaseAddress = new Uri("https://pricing.internal"));

// Put the trace id into every ProblemDetails response so support can find the logs
builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
    ctx.ProblemDetails.Extensions["traceId"] = Activity.Current?.TraceId.ToString() ?? ctx.HttpContext.TraceIdentifier);

var app = builder.Build();
app.UseExceptionHandler();

app.MapPost("/orders/{orderId:guid}/price", async (Guid orderId, PricingClient pricing, ILogger<Program> logger, CancellationToken ct) =>
{
    // Every log inside this block, in any class, gets OrderId
    using var _ = logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = orderId });

    logger.LogInformation("Pricing order");
    var total = await pricing.GetTotalAsync(orderId, ct); // HttpClient adds traceparent automatically
    logger.LogInformation("Order priced at {Total}", total);
    return TypedResults.Ok(total);
});

app.Run();

public sealed class PricingClient(HttpClient http)
{
    public async Task<decimal> GetTotalAsync(Guid orderId, CancellationToken ct) =>
        await http.GetFromJsonAsync<decimal>($"/totals/{orderId}", ct);
}

Propagating through a transport the SDKs don't cover (package OpenTelemetry.Api):

using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Context.Propagation;

public static class QueueTracing
{
    private static readonly ActivitySource Source = new("Shop.Queue");
    private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator;

    // Producer: copy traceparent/tracestate/baggage into message headers
    public static void Inject(IDictionary<string, string> headers) =>
        Propagator.Inject(new PropagationContext(Activity.Current?.Context ?? default, Baggage.Current),
            headers, static (h, key, value) => h[key] = value);

    // Consumer: continue the producer's trace
    public static Activity? StartProcessing(IReadOnlyDictionary<string, string> headers)
    {
        var parent = Propagator.Extract(default, headers,
            static (h, key) => h.TryGetValue(key, out var v) ? [v] : []);
        Baggage.Current = parent.Baggage;
        return Source.StartActivity("process message", ActivityKind.Consumer, parent.ActivityContext);
    }
}

⚠ Common mistakes

  • Mistake: Inventing an X-Correlation-ID header and middleware. Why it is wrong: It duplicates the trace id, doesn't interoperate with tracing tools, and often isn't propagated by every client. Instead: Use W3C Trace Context and the trace id.
  • Mistake: Calling BeginScope with a plain interpolated string. Why it is wrong: You get one unnamed value instead of queryable properties. Instead: Use a dictionary or a template with placeholders.
  • Mistake: Expecting scopes to appear in the console. Why it is wrong: The console provider hides them unless IncludeScopes = true. Instead: Enable scopes on the providers that should record them.
  • Mistake: Forgetting to dispose a scope (no using). Why it is wrong: The properties leak into unrelated later logs on that async flow. Instead: Always use using or using var.
  • Mistake: Assuming trace context crosses a message queue by magic. Why it is wrong: Only SDKs that implement propagation do it; custom transports lose the trace. Instead: Inject and extract with the OpenTelemetry propagator.
  • Mistake: Putting user emails or tokens into baggage. Why it is wrong: Baggage is sent to every downstream service, including external ones. Instead: Keep baggage to small, non-sensitive values.
  • Mistake: Returning nothing to the client on errors. Why it is wrong: Support can't find the logs for a complaint. Instead: Include traceId in ProblemDetails.

πŸ› Senior insight: trade-offs

Correlation is a platform concern: if every team builds its own, nothing lines up. I standardise on W3C Trace Context and OpenTelemetry, verify propagation at every hop that isn't plain HTTP (queues, scheduled jobs, third-party webhooks), and use scopes only for business context. The test I use is simple: pick a random error from yesterday and see whether one query, keyed on its trace id, shows every service it touched.

Option When it fits Cost When not to
Trace id as correlation id Any HTTP/gRPC/messaging system Needs propagation at custom hops –
Log scopes with business ids Group logs by order, tenant, job IncludeScopes, disposal discipline Data that should be on the trace as tags
Baggage Small values needed downstream Sent everywhere, size limits Personal data, large values
Custom correlation header Legacy partner that can't send traceparent Two ids to map New systems

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate says scopes flow across await. Why: Checks they understand AsyncLocal and ExecutionContext, which scopes and Activity.Current rely on.
    How to answer

    Thread-local storage gives each thread its own copy of a value. [ThreadStatic] marks a static field as per-thread (fast, but the field initialiser runs only once, so other threads see the default). ThreadLocal<T> adds a per-thread factory, optional tracking of all values and Dispose. Both are tied to the thread, so they break across await, where the continuation may run on another thread. AsyncLocal<T> is tied to the logical async flow instead: it is stored in the ExecutionContext and flows into awaited continuations and Task.Run, which is how Activity.Current and logging scopes work.

  2. When: Candidate mentions returning the trace id in error responses. Why: Checks they connect correlation with global exception handling and ProblemDetails.
    How to answer

    In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.

  3. When: Candidate mentions OpenTelemetry propagators or Application Insights transaction views. Why: Checks they can set up OpenTelemetry so trace ids reach every log and span.
    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.

πŸ›  Real-world problems: how you handle them

Orders lost between API and worker with no way to follow them
Situation
A checkout API in [Azure Australia East] published orders to a [RabbitMQ] queue read by a fulfilment worker. Customers reported paid orders that never shipped, about [30] a week out of [50,000].
Signals
Support tickets with order numbers but no error responses; API logs showed 'order published'; worker logs had no matching entries that could be tied back; Application Insights showed the API and worker as separate, unconnected operations.
Investigation
Checked the application map in Application Insights: no dependency edge from the API to the worker. Inspected messages with the RabbitMQ management UI: no `traceparent` header. The custom publisher didn't propagate context and the worker started a new trace per message. Added a temporary `OrderId` scope in the worker and found the missing orders failed deserialisation after a contract change, logged with no order id or trace link.
Resolution
Immediate: replayed the [dead-lettered] messages after fixing the contract. Long term: injected trace context into message headers with the OpenTelemetry propagator, started a consumer `Activity` with the extracted parent, and added an `OrderId` scope in the handler.
Prevention
Integration test asserting the worker's activity has the API's trace id; dashboard alert on dead-letter count; checklist item that every new transport must propagate `traceparent`.

How to tell it (STAR)

**S:** At [company] customers reported paid orders that never shipped, about [30] a week, and nobody could follow an order from the checkout API into the fulfilment worker. **T:** I had to find where the orders went and make that kind of problem traceable in future. **A:** I saw in Application Insights that the API and worker traces weren't connected, confirmed the queue messages had no traceparent header, and added an order-id scope to the worker, which showed the missing orders failing deserialisation after a contract change. We replayed them, then I added trace propagation through the queue with the OpenTelemetry propagator and a test that checks the trace id survives the hop. **R:** Lost orders went to [zero], and support can now go from an order's trace id to every log across both services in [under a minute].

↩ Usually asked after

More in Logging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me