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

📚 Interview question

How do you set up OpenTelemetry in an ASP.NET Core service? Explain how logs, traces and metrics fit together, what the OTLP exporter and the Azure Monitor distro each do, and how you approach sampling so you keep the useful data without an enormous bill.

OpenTelemetry in ASP.NET Core on .NET 10: the three signals and how logs carry TraceId/SpanId, AddOpenTelemetry with WithTracing, WithMetrics and WithLogging, resource attributes, built-in ASP.NET Core and HttpClient instrumentation and meters, UseOtlpExporter vs the Azure Monitor distro (UseAzureMonitor, rate-limited sampling default since 1.5), head versus tail sampling in the Collector, and cost control.

Senior Theory Advanced aspnet-core azure-monitor distributed-tracing logging opentelemetry sampling

🎯 Key points

  • Three signals: traces (spans per operation), metrics (aggregated counters/histograms), logs (events); logs carry TraceId/SpanId so they join traces
  • builder.Services.AddOpenTelemetry().ConfigureResource(AddService(...)).WithTracing(...).WithMetrics(...).WithLogging(...)
  • .NET emits Activities and Meters natively (Microsoft.AspNetCore.Hosting, System.Net.Http); OpenTelemetry instrumentation subscribes to them, and W3C traceparent carries context between services
  • UseOtlpExporter registers OTLP export for traces, metrics and logs to one endpoint (OTEL_EXPORTER_OTLP_ENDPOINT or options): Collector, Aspire dashboard, vendors; UseAzureMonitor sends to Application Insights
  • Azure Monitor distro 1.5+ defaults to a rate-limited sampler (5 traces per second, ratio adapts to load); TracesPerSecond or SamplingRatio change it
  • Head sampling (ParentBased + TraceIdRatioBased) decides at the start and keeps traces whole; tail sampling in the Collector, with policies such as status_code ERROR and latency thresholds, decides after the trace completes
  • Metrics are not sampled and are the cheap way to watch rates and latency; sample traces, filter logs by level
  • Set resource attributes (service.name, deployment.environment) and keep data in Australia East where residency matters

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

🗣 Full answer (senior)

How I would answer this in an interview

"I think of OpenTelemetry as three signals sharing one context. Traces tell me what happened to a single request across services: each operation is a span, and spans share a trace id. Metrics tell me how the system behaves in aggregate: request rate, error rate, latency histograms, GC and thread pool counters, and they're cheap because they're pre-aggregated. Logs are the detailed events, and with OpenTelemetry every log record carries the current trace id and span id, so from a slow trace I can jump straight to the logs written during it.

In .NET most of the instrumentation is already built in: ASP.NET Core, HttpClient, SqlClient and the Azure SDKs emit Activity objects and Meter instruments. In Program.cs I call AddOpenTelemetry(), set the resource so everything is labelled with the service name and environment, turn on tracing, metrics and logging, add my own ActivitySource and Meter names, and pick an exporter. UseOtlpExporter() sends everything over OTLP to a Collector, the Aspire dashboard locally, or a vendor. On Azure I usually use the Azure Monitor distro, UseAzureMonitor(), which wires the same SDK to Application Insights. For example, at [company] we [moved from the classic Application Insights SDK to the distro and pointed local development at the Aspire dashboard, so developers saw the same traces locally as in production].

Sampling is where seniority shows. Metrics aren't sampled, so they're my source of truth for rates and percentiles. Traces are sampled at the head with a parent-based sampler so a trace is kept or dropped as a whole across services. The Azure Monitor distro changed its default in 1.5 to a rate limit of five traces per second, which surprises teams who expect 100%. If I need every failed or slow request, I add a Collector with tail sampling. And logs I control by level, not by sampling. The mistake I see is turning everything to 100% and Debug, then cutting it randomly when the bill arrives. Decide what each signal is for, then size it."


What each signal is for

Signal Answers Cost driver Sample?
Metrics Is it healthy? Rate, errors, latency percentiles Number of time series (dimensions) No
Traces Where did this request spend its time? Spans per request × requests Yes
Logs What exactly happened, with details? Lines × size Filter by level, not sampling

Exporter choice

Exporter Goes to Fits Watch
UseOtlpExporter() Collector, Aspire dashboard, Grafana, Datadog, Elastic, Honeycomb Vendor-neutral, multi-cloud You run or buy the back end
UseAzureMonitor() (Azure.Monitor.OpenTelemetry.AspNetCore) Application Insights / Log Analytics Azure-hosted services Default rate-limited sampling, per-GB ingestion
Collector in between Anywhere, with processing Tail sampling, redaction, fan-out Another component to operate

Sampling options

Approach How Keeps Cost
Head, ratio ParentBasedSampler(TraceIdRatioBasedSampler(0.1)) 10% of whole traces Errors sampled at the same rate
Head, rate-limited Distro default (5/s) Fixed volume regardless of load Low-traffic paths still kept
Tail Collector tail_sampling processor All errors, slow traces, a % of the rest Collector must buffer whole traces

Production example

For an API at [1,500] requests a second, moving from 100% traces to the distro's rate-limited sampler plus tail sampling for errors in a Collector cut Application Insights ingestion from about [60] GB to [9] GB a day, while dashboards built on metrics stayed exact and every 5xx trace was still kept.

🔍 What the interviewer is checking

Checks whether the candidate can design production telemetry with OpenTelemetry, not just paste a set-up snippet.

Green flags

  • Explains the three signals and how logs join traces through trace and span ids.
  • Knows .NET's native Activity and Meter and what instrumentation adds.
  • Compares OTLP and the Azure Monitor distro and knows the distro's sampling default.
  • Distinguishes head and tail sampling and keeps metrics unsampled.

Red flags

  • Treats OpenTelemetry as only a logging library.
  • Proposes 100% of everything with no cost consideration.
  • Uses high-cardinality metric tags.

📚 Learn in depth

1. The architecture

  ASP.NET Core / HttpClient / SqlClient / Azure SDK / your code
        │ Activity (System.Diagnostics)   │ Meter (System.Diagnostics.Metrics)   │ ILogger
        ▼                                 ▼                                      ▼
  TracerProvider                     MeterProvider                         LoggerProvider
  (sampler, processors)              (views, aggregation)                  (processors)
        │                                 │                                      │
        └───────────────────────────────────┬───────────────────────────────────┘
                                           ▼
                         batch export processors (per signal)
                                           │
                ┌──────────────────────────┼──────────────────────────┐
                ▼                          ▼                          ▼
          OTLP exporter            Azure Monitor exporter        Console exporter
                │                          │
        OTel Collector             Application Insights
   (tail sampling, redaction)      (Australia East workspace)

.NET does not need a separate tracing API: Activity is the span and ActivitySource is the tracer. OpenTelemetry subscribes through ActivityListener and MeterListener.

2. Built-in instrumentation in modern .NET

Since .NET 8, ASP.NET Core and HttpClient publish metrics natively (meters such as Microsoft.AspNetCore.Hosting with http.server.request.duration, and System.Net.Http). .NET 9 added built-in runtime metrics (System.Runtime meter). The OpenTelemetry instrumentation packages add richer span attributes and filtering on top.

3. How logs join traces

The OpenTelemetry logging provider reads Activity.Current when a log is written and stamps the record with TraceId, SpanId and TraceFlags. In Application Insights these appear as operation_Id and operation_ParentId, so the end-to-end transaction view shows the logs under each span. Logs written outside any activity (start-up, background loops without your own activity) have no trace id, so start an activity per unit of work in workers.

4. Sampling mechanics

  • Head sampling runs when a root span starts. ParentBasedSampler respects the caller's sampled flag in traceparent, so a trace is all-or-nothing across services.
  • Rate-limited sampling (the Azure Monitor distro default since 1.5.0, 5 traces per second per instance) adapts the ratio to load. Set options.SamplingRatio with TracesPerSecond = null to go back to a fixed percentage, or use OTEL_TRACES_SAMPLER environment variables.
  • Tail sampling happens in the Collector after the whole trace has arrived, so it can keep traces with errors or high latency. It needs every span of a trace routed to the same Collector instance (load-balancing exporter by trace id).
  • Logs and sampling: recent Azure Monitor exporter versions can also drop log records that belong to sampled-out traces (trace-based log sampling). Check your version's behaviour, because it changes how complete your logs are.

5. Resource attributes and cardinality

service.name, service.version, deployment.environment and the cloud role instance identify where data came from. Every metric dimension multiplies time series: never use user ids or full URLs as metric tags; route templates (/orders/{id}) are fine.

6. Data residency

For Australian workloads that hold personal information, put the Log Analytics workspace behind Application Insights in Australia East or Southeast, and remember OpenTelemetry attributes can carry personal data: redact before export (Collector processors or Microsoft.Extensions.Compliance.Redaction).

Try it yourself

  1. Run the .NET Aspire dashboard in Docker (mcr.microsoft.com/dotnet/aspire-dashboard) and point UseOtlpExporter() at it; view traces, metrics and structured logs together.
  2. Call a second service with HttpClient and confirm both appear in one trace.
  3. Set SamplingRatio = 0.1 and load test with k6; compare request counts in traces versus the http.server.request.duration metric.
  4. Add a custom ActivitySource in a background worker and check its logs now have trace ids.
  5. Run a local OpenTelemetry Collector with the tail_sampling processor keeping status_code ERROR, and verify every failing request is kept.

💻 Code

One registration for all three signals, with OTLP locally and Azure Monitor in Azure.

// Program.cs
// Packages: OpenTelemetry.Extensions.Hosting, OpenTelemetry.Instrumentation.AspNetCore,
// OpenTelemetry.Instrumentation.Http, OpenTelemetry.Exporter.OpenTelemetryProtocol,
// Azure.Monitor.OpenTelemetry.AspNetCore
using System.Diagnostics;
using System.Diagnostics.Metrics;
using Azure.Monitor.OpenTelemetry.AspNetCore;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

var otel = builder.Services.AddOpenTelemetry()
    .ConfigureResource(r => r.AddService("orders-api", serviceVersion: "1.4.2")
        .AddAttributes([new("deployment.environment", builder.Environment.EnvironmentName)]))
    .WithTracing(t => t
        .AddAspNetCoreInstrumentation(o => o.Filter = ctx => ctx.Request.Path != "/healthz") // no health-probe noise
        .AddHttpClientInstrumentation()
        .AddSource(OrdersTelemetry.SourceName))
    .WithMetrics(m => m
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddRuntimeInstrumentation()
        .AddMeter(OrdersTelemetry.MeterName))
    .WithLogging(configureOptions: o => o.IncludeScopes = true);

if (builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"] is { Length: > 0 })
{
    // Azure: distro defaults to rate-limited sampling (5 traces/s); make the choice explicit
    otel.UseAzureMonitor(o => o.TracesPerSecond = 5);
}
else
{
    // Local / other back ends: OTEL_EXPORTER_OTLP_ENDPOINT, e.g. the Aspire dashboard
    otel.UseOtlpExporter();
}

builder.Services.AddSingleton<OrdersTelemetry>();

var app = builder.Build();
app.MapPost("/orders", (OrdersTelemetry telemetry, ILogger<Program> logger) =>
{
    using var activity = OrdersTelemetry.Source.StartActivity("PlaceOrder");
    telemetry.OrdersPlaced.Add(1, new KeyValuePair<string, object?>("channel", "web")); // low-cardinality tag
    logger.LogInformation("Order placed"); // carries TraceId/SpanId of PlaceOrder
    return TypedResults.Accepted("/orders/1");
});
app.MapGet("/healthz", () => TypedResults.Ok());
app.Run();

public sealed class OrdersTelemetry(IMeterFactory meterFactory)
{
    public const string SourceName = "Shop.Orders";
    public const string MeterName = "Shop.Orders";
    public static readonly ActivitySource Source = new(SourceName);
    public Counter<long> OrdersPlaced { get; } = meterFactory.Create(MeterName).CreateCounter<long>("shop.orders.placed");
}

⚠ Common mistakes

  • Mistake: Assuming the Azure Monitor distro keeps 100% of traces. Why it is wrong: Since 1.5.0 the default is a rate-limited sampler (5 traces per second), so low-volume errors can be missing from traces. Instead: Set sampling explicitly and use metrics for rates.
  • Mistake: Sampling logs randomly to save money. Why it is wrong: You lose the lines you need for exactly the failing requests. Instead: Filter logs by level and category; sample traces.
  • Mistake: Using user ids, order ids or raw URLs as metric tags. Why it is wrong: Each unique value creates a time series, exploding cost and memory. Instead: Use low-cardinality tags such as route template, status code and channel.
  • Mistake: Not setting service.name. Why it is wrong: Data shows up as unknown_service, and application maps are useless. Instead: Set resource attributes for name, version and environment.
  • Mistake: Running the classic Application Insights SDK and the OpenTelemetry distro together. Why it is wrong: Duplicate telemetry and double cost. Instead: Migrate to one.
  • Mistake: Tracing health probes. Why it is wrong: Thousands of identical spans per hour fill the sampling budget. Instead: Filter /healthz in ASP.NET Core instrumentation.
  • Mistake: Background workers with no Activity. Why it is wrong: Their logs have no trace id and can't be correlated. Instead: Start an activity per message or job from your own ActivitySource.
  • Mistake: Tail sampling with several Collector replicas behind a round-robin load balancer. Why it is wrong: Spans of one trace land on different replicas and decisions are wrong. Instead: Route by trace id with the load-balancing exporter.

🏛 Senior insight: trade-offs

I design telemetry around questions: metrics answer "is it broken and for how many", traces answer "where", logs answer "why". That decides the budget: metrics complete and cheap, traces sampled but whole, logs filtered by level with redaction. OpenTelemetry's real value is that this design survives a vendor change; the exporter is a line in Program.cs or a Collector config.

Option When it fits Cost When not to
Azure Monitor distro Azure-hosted, Application Insights users Per-GB ingestion, distro defaults to learn Multi-cloud or non-Azure back end
OTLP direct to vendor Small estate, one back end Vendor lock-in at the back end only Need tail sampling or redaction centrally
OTLP via Collector Many services, tail sampling, redaction, fan-out Operating the Collector Single small service
100% traces Low traffic, early life of a service Scales linearly with load High-traffic APIs

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions trace ids joining logs across services. Why: Checks they understand trace context propagation, which OpenTelemetry depends on 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 says OpenTelemetry is the transport rather than the logging library. Why: Checks they can place OpenTelemetry relative to Serilog and NLog.
    How to answer

    Your code always logs through ILogger<T>; the choice is what sits underneath.

    • Serilog replaces the provider pipeline (AddSerilog). Destinations are sinks (Seq, files, Elastic, OTLP); enrichers add properties such as machine name or user id. It has rich destructuring and a bootstrap logger for start-up failures.
    • NLog (UseNLog) uses targets and layouts, configured in nlog.config, popular in older enterprise estates.
    • Built-in + OpenTelemetry: AddOpenTelemetry().WithLogging() exports to OTLP or Azure Monitor, with logs correlated to traces and metrics.

    For a new .NET 10 service on Azure I'd start with built-in + OpenTelemetry; I'd keep Serilog or NLog where a team already relies on their sinks. The trade-off is fewer moving parts versus richer formatting and sink choice.

🛠 Real-world problems: how you handle them

Errors missing from traces after upgrading the Azure Monitor distro
Situation
A payments API in [Azure Australia East] handling [400] requests a second upgraded `Azure.Monitor.OpenTelemetry.AspNetCore` as part of routine dependency updates. Support escalated a failed payment, but its trace couldn't be found.
Signals
Request count in Application Insights traces dropped by about [98%] after the deploy while the `http.server.request.duration` metric showed unchanged traffic; end-to-end transaction view empty for most failures; no errors in the app.
Investigation
Compared the `requests` table count with the metric-based request rate in a KQL query: a steady ratio implying sampling. Read the distro release notes: the default sampler had changed to rate-limited at 5 traces per second. Checked `itemCount` on stored requests: values around [80], confirming sampling weights.
Resolution
Immediate: set `TracesPerSecond` higher for the payments API while deciding policy. Long term: kept head sampling explicit in code, added an OpenTelemetry Collector with tail sampling to keep all error and slow traces, and moved dashboards and alerts to metrics so they no longer depended on trace counts.
Prevention
Pinned sampling settings explicitly in code with a comment linking the decision record; added a release-note check for telemetry packages to the dependency-update checklist; added an alert comparing trace counts with metric counts.

How to tell it (STAR)

**S:** At [company] a routine package upgrade on our payments API made most failed requests disappear from Application Insights, and support couldn't find a customer's failed payment. **T:** I needed to explain the gap and make sure we never lost error traces again. **A:** I compared trace counts with the request-duration metric, saw a constant ratio, and traced it to the distro's new rate-limited sampling default. I raised the limit straight away, then added a Collector with tail sampling to keep every error and slow trace, and moved our dashboards and alerts onto metrics. **R:** Every 5xx trace has been kept since, ingestion stayed about [40%] below the old 100% level, and our alerts became independent of sampling.

↩ Usually asked after

More in Logging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me