Volume 7 · Chapter 6 — Advanced .NET Engineering, Performance & Production Excellence

Observability and Monitoring

Goutham Mayaluri 8 min read .NETC#ILPerformanceObservability

6.1 Introduction

Observability is the property of being able to ask new questions about a running system from the outside, using the telemetry it emits, without shipping new code to answer each question. In a distributed .NET estate where a single user action touches many services, this is not a nice-to-have - it is the difference between resolving an incident in minutes and staring at disconnected logs for hours. Observability rests on three complementary signals: metrics, logs, and traces.

6.2 The Three Pillars

Signal Answers Shape
Metrics Is something wrong? (rates, latencies, saturation) Cheap numeric time series
Traces Where is it wrong? (which service/span) Causal request timeline across services
Logs Why is it wrong? (detailed events) Structured, high-cardinality events

They work together: a metric alert tells you something is off, a trace localizes which hop is slow or failing, and logs for that trace explain the cause.

6.3 Metrics with OpenTelemetry

Metrics are aggregated numbers - request rate, error rate, latency percentiles, CPU, memory, queue depth. The RED method (Rate, Errors, Duration) for services and USE (Utilization, Saturation, Errors) for resources give a solid default set. .NET’sSystem.Diagnostics.MetricsAPI integrates with OpenTelemetry.


// Define a custom business metric alongside the automatic HTTP/runtime ones.
private static readonly Meter Meter = new("Bank.Payments");
private static readonly Counter<long> Payments =
    Meter.CreateCounter<long>("payments.processed");

public async Task ProcessAsync(Payment p)
{
    await _handler.HandleAsync(p);
    Payments.Add(1, new KeyValuePair<string, object?>("currency", p.Currency));
}

6.4 Distributed Tracing and Context Propagation

A trace follows one request across service boundaries as a tree of spans, each timed. The magic is context propagation: a trace id and span id travel with the request (via W3Ctraceparentheaders), so every service’s spans stitch into one timeline. This is how you see that a 900 ms request spent 820 ms in a downstream fraud call.

sequenceDiagram
  autonumber
  participant GW as Gateway (trace start)
  participant Pay as Payments
  participant Fraud as Fraud Service
  participant DB as Database
  GW->>Pay: request (traceparent: t1)
  Pay->>Fraud: check (traceparent: t1, parent span)
  Fraud->>DB: query (traceparent: t1)
  DB-->>Fraud: rows
  Fraud-->>Pay: score
  Pay-->>GW: result
  Note over GW,DB: One trace id t1 links every span into a single latency waterfall

// Wire up OpenTelemetry: automatic ASP.NET Core + HttpClient + EF instrumentation.
builder.Services.AddOpenTelemetry()
    .WithTracing(t => t
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddEntityFrameworkCoreInstrumentation()
        .AddOtlpExporter())
    .WithMetrics(m => m
        .AddAspNetCoreInstrumentation()
        .AddRuntimeInstrumentation()
        .AddOtlpExporter());

6.5 Structured Logs as the Third Signal

Logs provide the detail metrics and traces omit. Structured logging (Chapter 7) attaches machine-readable fields and, crucially, the trace id, so logs for a failing request are one query away. Logs are the most expensive signal, so they carry the “why,” not routine “it worked” chatter better served by metrics.

6.6 Health Checks and Probes

Health checks let orchestrators make decisions. Alivenessprobe answers “is the process wedged and in need of a restart?”; areadinessprobe answers “can it serve traffic right now?” (dependencies reachable, warm-up done). Conflating them causes cascading restarts - a brief database blip should fail readiness (stop routing traffic) but not liveness (do not kill the pod).


builder.Services.AddHealthChecks()
    .AddCheck("self", () => HealthCheckResult.Healthy(), tags: new[] { "live" })
    .AddSqlServer(connString, tags: new[] { "ready" })
    .AddRedis(redisConn, tags: new[] { "ready" });

app.MapHealthChecks("/health/live",  new() { Predicate = c => c.Tags.Contains("live") });
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });

6.7 Alerting on Symptoms, Not Causes

Good alerts are actionable and tied to user-facing symptoms - SLO burn rate, elevated error rate, latency breaching budget - rather than noisy low-level causes (a single high-CPU spike). Alert fatigue is a real failure mode: too many non-actionable pages train responders to ignore them. Page on what hurts users; dashboard the rest.

Senior Interview Question

Why are logs alone insufficient for a distributed system?

Logs are detailed but local and unaggregated: with dozens of services emitting millions of lines, logs alone cannot tell you the overall error rate or latency trend (that is metrics), nor reconstruct the path of one request across services (that is tracing). Searching logs to correlate a single user action across ten services by timestamp is slow and error-prone. You need metrics to know something is wrong and how bad, traces to localize where, and only then logs to explain why. The three are complementary; relying on logs alone leaves you blind to system -level behavior and cross-service causality.

Senior Interview Question

What is distributed tracing and how does context propagation work?

Distributed tracing records the journey of a single request as a tree of timed spans across services, so you can see exactly where time and failures occur. Context propagation is what links the spans: when a service calls another, it passes the trace id and current span id in headers (the W3Ctraceparentstandard), and the callee creates child spans under that same trace id. Every service exports its spans to a backend that reassembles them into one waterfall. In .NET this is largely automatic with OpenTelemetry’s ASP.NET Core and HttpClient instrumentation, which read and write the headers for you.

Senior Interview Question

What is the difference between a liveness and a readiness probe?

A liveness probe tells the orchestrator whether the process is fundamentally broken and should be restarted - it should check only the app itself, not dependencies, because restarting will not fix a downstream outage. A readiness probe tells the orchestrator whether the instance can currently serve traffic; it legitimately checks dependencies (database, cache) and warm-up state, and failing it removes the instance from the load balancer without killing it. Getting this wrong is dangerous: if liveness checks a shared database, a transient DB blip can trigger a cluster-wide restart storm that turns a small problem into an outage.

Senior Interview Question

What makes a good alert, and what is alert fatigue?

A good alert is actionable, tied to a user-facing symptom, and rare enough that responders trust it - typically driven by SLO burn rate or elevated error/latency against a budget. Alert fatigue is what happens when you page on every low-level anomaly (a CPU spike, a single failed request): responders receive so many non-actionable pages that they start ignoring all of them, including the real one. The remedy is to page only on symptoms that require human action now, route everything else to dashboards and tickets, and continuously prune alerts that fire without anyone doing anything.

Principal Engineer Question

How do you design observability for a large enterprise system from scratch?

I standardize the three signals across every service and make correlation the first-class requirement. Concretely: adopt OpenTelemetry everywhere so metrics, traces, and logs share a common trace id and consistent semantic conventions; mandate structured logging that always includes the trace id; instrument automatically (ASP.NET Core, HttpClient, EF, messaging) and add key business metrics. I define SLIs and SLOs per service so alerting is symptom- and budget-based, not noise. I ensure context propagates across async and messaging boundaries, not just HTTP. Dashboards follow RED/USE so any responder can navigate an unfamiliar service. And I treat telemetry cost and cardinality as a design constraint - sampling traces, keeping high-cardinality data out of metrics. The outcome I aim for is that any engineer can go from “an alert fired” to “this span in this service, here is the log line” in minutes.

Principal Engineer Question

An incident took hours to diagnose because telemetry was fragmented. What changes do you drive afterward?

The lesson is that observability is a platform capability, not each team’s side-project. I’d drive a common telemetry standard: one OpenTelemetry pipeline, mandatory trace-id-in-logs, shared semantic conventions, and correlation that survives async and queue hops - so a request can be followed end to end. I’d establish SLOs and symptom-based alerting so the next incident is detected by a meaningful signal, add runbooks linked from alerts, and ensure every service ships with baseline RED dashboards so responders are not learning bespoke telemetry mid-incident. I’d also invest in trace sampling and log hygiene so the signal is affordable and not drowned in noise. Finally, the post-incident review itself becomes an input: gaps found become required instrumentation, closing the loop so each incident makes the system more observable.

6.8 Banking Enterprise Scenario

A bank instruments every service with OpenTelemetry exporting metrics and traces to a central backend, with structured logs carrying the trace id. When customers report slow transfers, an SLO burn-rate alert fires; an engineer opens the trace for a slow request and sees 85% of the time in the fraud service’s database span, then jumps to that span’s logs and finds a missing index after a recent schema change. Because liveness and readiness are correctly separated, the degraded fraud dependency drops out of rotation without restart storms. Diagnosis takes minutes, not hours.

Chapter Revision Notes

  • Metrics say “something is wrong,” traces say “where,” logs say “why.”
  • Use OpenTelemetry for vendor-neutral, correlated telemetry across services.
  • Context propagation (traceparent) links spans into one request timeline.
  • Separate liveness (restart) from readiness (route traffic) probes.
  • Alert on user-facing symptoms and SLO burn; avoid alert fatigue.