Mediator in .NET :👈 👉:EF Core vs Dapper

OpenTelemetry in .NET

OpenTelemetry in .NET

1. What is OpenTelemetry?

OpenTelemetry (OTel) is an open-source, vendor-neutral framework used to collect, process, and export application telemetry data.

It helps developers understand:

  • Why an API is slow.
  • Which microservice is causing errors.
  • How many requests an application processes.
  • How much CPU and memory an application consumes.
  • How requests travel between microservices.

OpenTelemetry supports three main signals: Traces, Metrics, and Logs.

2. Three Main Signals

2.1 Traces

A trace represents the complete journey of a request across an application or multiple microservices.

A trace contains multiple spans. Each span represents an individual operation, such as an API call, database query, or service call.

Example:

API Gateway
    |
    v
Order Service
    |
    +----> Payment Service
    |
    +----> Inventory Service

Important terms:

  • Trace ID: Identifies the complete request journey.
  • Span ID: Identifies an individual operation.
  • Parent Span: Connects related operations.
  • Attributes: Additional information about a span.

Distributed Tracing

One Distributed Trace API Gateway Span A Order Service Span B Payment Service Span C - 6 seconds Inventory Service Span D - 300 ms All spans belong to the same trace

This helps identify which service is responsible for request delays.

2.2 Metrics

Metrics are numerical measurements that show application performance over time.

Examples:

  • HTTP request count.
  • API response time.
  • Error count.
  • CPU and memory usage.
  • .NET garbage collection activity.

2.3 Logs

Logs are timestamped records of events occurring inside an application.

10:15:20 Information - Order processing started.
10:15:21 Information - Payment service called.
10:15:27 Error       - Payment processing failed.

Signal Comparison

Signal Purpose
Traces Track request journeys across services.
Metrics Measure application performance.
Logs Record application events and errors.

3. OpenTelemetry Architecture

OpenTelemetry consists of these main components:

  • Instrumentation: Captures application operations automatically or through developer-written code.
  • API: Provides interfaces for generating telemetry.
  • SDK: Processes telemetry, applies sampling, and manages exporting.
  • Exporter: Sends telemetry to a destination.
  • Collector: Receives, processes, and exports telemetry independently.
  • Backend: Stores, analyzes, or visualizes telemetry.

OpenTelemetry Architecture

OpenTelemetry Data Flow .NET Application Instrumentation + OpenTelemetry SDK OTLP Exporter OpenTelemetry Collector (Optional) Jaeger Prometheus / Grafana Azure Monitor

The Collector is optional. An application can export telemetry directly to a compatible backend.

4. Implementing OpenTelemetry in ASP.NET Core

Step 1: Install Packages

dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.Http
dotnet add package OpenTelemetry.Instrumentation.Runtime
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol

Step 2: Configure Program.cs

using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource =>
        resource.AddService("OrderService"))
    .WithTracing(tracing =>
    {
        tracing
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddOtlpExporter();
    })
    .WithMetrics(metrics =>
    {
        metrics
            .AddAspNetCoreInstrumentation()
            .AddHttpClientInstrumentation()
            .AddRuntimeInstrumentation()
            .AddOtlpExporter();
    });
var app = builder.Build();
app.MapControllers();
app.Run();

This configuration collects HTTP traces and application metrics and exports them through OTLP. The OTLP endpoint must be configured for your environment.

Step 3: Create a Custom Span

Automatic instrumentation captures supported operations. Use ActivitySource to trace custom business operations.

using System.Diagnostics;
public class OrderService
{
    private static readonly ActivitySource Source =
        new ActivitySource("OrderService");
    public async Task<string> CreateOrderAsync()
    {
        using var activity =
            Source.StartActivity("CreateOrder");
        activity?.SetTag("order.type", "Online");
        await Task.Delay(100);
        activity?.AddEvent(
            new ActivityEvent("OrderCreated"));
        return "Order Created";
    }
}

Register the custom ActivitySource:

.WithTracing(tracing =>
{
    tracing
        .AddSource("OrderService")
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddOtlpExporter();
})
  • ActivitySource: Creates custom spans.
  • Activity: Represents an individual traced operation.

5. Context Propagation

Context propagation transfers trace information between services so that operations can be connected to the same distributed trace.

OpenTelemetry commonly uses the W3C Trace Context standard. Its important HTTP headers are:

  • traceparent: Carries trace ID, parent span ID, and trace flags.
  • tracestate: Carries optional vendor-specific trace information.

Context Propagation

Order Service Creates Trace ID HTTP Header traceparent 00-ABC123-DEF456-01 Illustrative values Payment Service Continues same trace Related service operations can be viewed in one trace.

Supported HTTP instrumentation normally propagates trace context automatically when correctly configured.

6. OpenTelemetry Collector

The Collector is an optional independent service that receives telemetry from applications, processes it, and sends it to monitoring platforms.

Its three main components are:

  • Receivers: Accept telemetry.
  • Processors: Batch, filter, or modify telemetry.
  • Exporters: Send telemetry to destinations.

Example Collector Configuration

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318
processors:
  batch:
exporters:
  debug:
    verbosity: basic
service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [debug]
    metrics:
      receivers: [otlp]
      processors: [batch]
      exporters: [debug]

This example uses a debug exporter. Production deployments should configure appropriate destination exporters, authentication, and network security.

7. OpenTelemetry and Monitoring Tools

Technology Purpose
OpenTelemetry Instrumentation and telemetry collection.
Jaeger Distributed tracing.
Prometheus Metrics collection and storage.
Grafana Dashboards and visualization.
Azure Monitor / Application Insights Azure application monitoring and analysis.
Serilog Structured logging for .NET.

OpenTelemetry can export telemetry to compatible monitoring backends. It does not replace those backends or necessarily replace logging frameworks.

8. OpenTelemetry Best Practices

  • Use consistent service names and resource attributes.
  • Use automatic instrumentation for supported operations.
  • Add custom spans for important business operations.
  • Configure sampling and batching to control telemetry volume.
  • Never record passwords, tokens, or sensitive customer information.
  • Avoid unique IDs as metric labels because they create high cardinality.
  • Secure Collector endpoints and monitor export failures.
  • Configure appropriate telemetry retention policies.

9. OpenTelemetry Interview Questions

Q1. What is OpenTelemetry?

An open-source framework for generating, collecting, processing, and exporting traces, metrics, and logs.

Q2. What is a trace?

A complete record of a request's journey across an application or multiple services.

Q3. What is a span?

An individual operation within a trace.

Q4. What is OTLP?

OpenTelemetry Protocol, used to transport telemetry between applications, Collectors, and supported backends.

Q5. What is context propagation?

Transferring trace information between services to connect related operations.

Q6. What is the OpenTelemetry Collector?

A service that receives, processes, and exports telemetry data.

Q7. What is ActivitySource in .NET?

A .NET API used to create custom activities (spans) for distributed tracing.

Q8. Is OpenTelemetry a replacement for Application Insights?

No. OpenTelemetry provides instrumentation and telemetry collection; Application Insights provides monitoring and analysis. They can work together.

10. Quick Summary

Concept Meaning
OpenTelemetry Observability framework.
Traces Request journey.
Metrics Numerical performance measurements.
Logs Application events.
ActivitySource Creates custom spans in .NET.
OTLP Telemetry transport protocol.
Collector Receives, processes, and exports telemetry.
🔙
Mediator in .NET :👈 👉:EF Core vs Dapper