Observability & OpenTelemetry
Observability means being able to ask new questions about a running system without shipping new code—usually by combining correlated traces, metrics, and structured logs.
Overview
Observability is the ability to explain unfamiliar production behavior from emitted evidence. OpenTelemetry gives .NET applications vendor-neutral APIs, SDKs, semantic conventions, context propagation, sampling, processing, and exporters for traces, metrics, and logs. Traces connect causally related spans, metrics summarize rate and distributions, and structured logs capture event detail; correlation turns them into one investigation path. Instrument service boundaries first, then add business spans and low-cardinality measurements that answer operational questions. Propagate W3C trace context across HTTP and message metadata, preserve baggage carefully, and never place secrets or unbounded identifiers in metric dimensions. Sampling and processors control cost but must preserve useful errors and exemplars. Collectors decouple applications from backends, add batching and routing, and become part of capacity planning. Define service-level indicators before dashboards, test telemetry shape, and alert on user-visible symptoms.
What you will learn
- Choose the right signal for an operational question.
- Create custom ActivitySource and Meter instrumentation.
- Propagate trace context across boundaries.
- Control metric cardinality and sensitive attributes.
- Design sampling and collector pipelines.
- Test telemetry contracts and service-level indicators.
Prerequisites
- Structured logging, async flows, HTTP or messaging boundaries.
- Basic latency percentiles and error-rate concepts.
- A telemetry backend or local collector plan for production use.
When to use Observability & OpenTelemetry
Good fit
- Distributed operations need causal correlation.
- Teams need vendor-neutral instrumentation.
- Service objectives require measurable indicators.
Choose another approach when
- Every object property becomes an attribute.
- Metrics use request IDs or user IDs as dimensions.
- Dashboards are built before operational questions are defined.
Key concepts
Traces explain a request path, metrics summarize populations, and logs preserve event detail.
ActivitySource creates timed operations with parent-child context, status, events, and bounded attributes.
Counters and histograms record totals and distributions using stable low-cardinality dimensions.
W3C trace context carries causal identity across HTTP, messaging, and background work.
Service name, version, environment, and instance attributes identify the telemetry producer.
Head or tail sampling controls volume while policy preserves errors and representative latency.
Receivers, processors, and exporters batch, enrich, filter, and route signals independently of application code.
Availability, latency, error, and saturation evidence become objectives and actionable symptom alerts.
Architecture
Instrumented code emits traces, metrics, and logs to a collector, which routes them to a backend where they can be correlated and queried.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The sample uses built-in ActivitySource and Meter APIs to emit a correlated operation, bounded attributes, an outcome counter, and a duration histogram.
- 01Define questions
List incidents, user journeys, and service objectives telemetry must explain.
- 02Set resource identity
Configure stable service name, version, environment, and instance metadata.
- 03Instrument boundaries
Enable framework HTTP, client, database, and messaging instrumentation.
- 04Add business context
Create custom spans and measurements only for decisions the framework cannot expose.
- 05Propagate context
Carry W3C trace metadata across every synchronous and asynchronous boundary.
- 06Control cost and privacy
Bound attributes, metric dimensions, sampling, retention, and redaction.
- 07Validate operations
Test signal shape, collector failure, dashboards, alerts, and trace-to-log navigation.
Code example
Registering OpenTelemetry once at startup instruments ASP.NET Core, HttpClient, and EF Core without touching business code.
builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService("orders-api"))
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddEntityFrameworkCoreInstrumentation()
.AddOtlpExporter())
.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddRuntimeInstrumentation()
.AddOtlpExporter());Testing strategy
Treat telemetry names, units, attributes, and propagation as versioned operational contracts.
- Listen for custom Activity names and tags.
- Capture Meter instruments and units.
- Assert independent root trace identifiers.
- Test propagation through HTTP and messages.
- Reject secret and high-cardinality dimensions.
- Load-test exporter and collector backpressure.
Security considerations
Telemetry often crosses trust boundaries and can silently become a sensitive-data store.
- Classify allowed attributes.
- Redact tokens, payloads, and personal data.
- Encrypt transport and backend storage.
- Restrict query and dashboard access.
- Set retention and deletion policy.
Performance and scalability
Instrumentation must remain bounded when traffic or the backend degrades.
- Prefer low-allocation APIs.
- Control span volume with sampling.
- Keep metric dimensions bounded.
- Batch exports.
- Plan collector queues and memory limits.
Deployment and operations
Ship collection and dashboards with the service so releases remain diagnosable.
- Version service resource attributes.
- Deploy collectors redundantly.
- Buffer and bound exporter retries.
- Validate dashboards after rollout.
- Alert on telemetry pipeline loss.
Common problems and fixes
Traces stop at a service.
Likely cause: Context was not propagated or extracted.
Fix: Inspect W3C headers or message metadata at the boundary.
Metrics backend explodes.
Likely cause: A dimension has unbounded cardinality.
Fix: Remove identifiers and keep them on sampled spans or logs.
Logs cannot join traces.
Likely cause: Trace and span identifiers are missing.
Fix: Enable correlated logging scopes and verify exporter fields.
Application slows during outage.
Likely cause: Exporter retries or queue is unbounded.
Fix: Batch asynchronously and cap queue, timeout, and retries.
Important failures are absent.
Likely cause: Sampling drops them.
Fix: Tune policy or use tail sampling that preserves errors.
Dashboard disagrees with traces.
Likely cause: Units, aggregation, or time windows differ.
Fix: Verify instrument units and query aggregation.
Best practices
- Start with user-visible questions.
- Instrument boundaries first.
- Follow semantic conventions.
- Propagate W3C context.
- Keep metric labels bounded.
- Redact sensitive data.
- Batch through collectors.
- Test alerts and correlation paths.
Production checklist
- Operational questions and SLIs are defined.
- Resource identity is stable.
- Trace context crosses every boundary.
- Custom attributes are bounded and reviewed.
- Metric dimensions are low cardinality.
- Sampling and retention budgets are explicit.
- Collector failure is bounded.
- Dashboards and alerts are release-tested.
Common interview questions
Why are logs alone insufficient for distributed requests?
They lack a causal operation graph unless trace context consistently correlates events across services.
Counter versus histogram?
A counter totals occurrences; a histogram records a value distribution such as duration or payload size.
Why is metric cardinality dangerous?
Every unique dimension combination creates a time series and can overwhelm cost and query capacity.
What does the collector provide?
A vendor-neutral place to batch, enrich, filter, route, and export telemetry.
Head versus tail sampling?
Head sampling decides near trace start; tail sampling decides after observing more of the completed trace.
What belongs in resource attributes?
Stable producer identity such as service name, version, environment, and instance.
How do traces and logs correlate?
Log records include the current trace and span identifiers from the active Activity context.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
OpenTelemetry Correlation Lab
A dependency-free .NET 10 instrumentation sample demonstrating ActivitySource traces, bounded tags, Meter counters and histograms, sampling, and focused listener tests.
- Run
dotnet run --project src/OtelCorrelationLab- Test
dotnet test OtelCorrelationLab.slnx