Skip to content

Latest commit

 

History

History
267 lines (196 loc) · 15.4 KB

File metadata and controls

267 lines (196 loc) · 15.4 KB

MinimalLambda.OpenTelemetry

OpenTelemetry integration for distributed tracing and observability in AWS Lambda functions.

📚 View Full Documentation

Overview

An extension package for the MinimalLambda framework that provides comprehensive observability integration. This package enables:

  • Distributed Tracing: Automatic span creation and context propagation for Lambda invocations
  • Metrics Collection: Performance and business metrics exportable to standard observability backends
  • OpenTelemetry Integration: Built on the OpenTelemetry SDK for vendor-neutral instrumentation
  • AWS Lambda Instrumentation: Wraps OpenTelemetry.Instrumentation.AWSLambda for Lambda-specific insights
  • Lifecycle Integration: Seamless integration with Lambda cold starts, warm invocations, and error tracking

Note

Requires MinimalLambda – this package extends that framework and cannot be used standalone. Configure exporters to send traces and metrics to your observability backend (e.g., Datadog, New Relic, Jaeger, CloudWatch).

Installation

This package requires MinimalLambda to be installed and working in your project. It is an extension package and cannot function standalone.

First, install the core framework:

dotnet add package MinimalLambda

Then install this OpenTelemetry extension:

dotnet add package MinimalLambda.OpenTelemetry

Ensure your project uses C# 11 or later:

<PropertyGroup>
  <LangVersion>11</LangVersion>
  <!-- or <LangVersion>latest</LangVersion> -->
</PropertyGroup>

You'll also need additional OpenTelemetry packages depending on your use case:

dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol

Additional packages may include exporters (e.g., Jaeger, Datadog, AWS X-Ray), instrumentation libraries (e.g., for HTTP, database calls), and other extensions. See the AWS OTel Lambda .NET guide and OpenTelemetry.io .NET documentation for your specific observability backend and instrumentation needs.

Quick Start

Set up OpenTelemetry with the AWS Lambda instrumentation:

using MinimalLambda.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenTelemetry.Instrumentation.AWSLambda;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = LambdaApplication.CreateBuilder();

// Configure OpenTelemetry with tracing
builder
    .Services.AddOpenTelemetry()
    .WithTracing(configure =>
        configure
            .AddAWSLambdaConfigurations()
            .SetResourceBuilder(
                ResourceBuilder.CreateDefault().AddService("MyLambda", serviceVersion: "1.0.0")
            )
            .AddOtlpExporter(options =>
            {
                options.Endpoint = new Uri("http://localhost:4317");
            })
    );

var lambda = builder.Build();

// Enable automatic tracing for Lambda invocations
lambda.UseOpenTelemetryTracing();

lambda.MapHandler(([FromEvent] string input) => $"Hello {input}!");

// Flush traces on Lambda shutdown
lambda.OnShutdownFlushTracer();

await lambda.RunAsync();

Key Features

  • Automatic Root Span – Wraps Lambda invocations with OpenTelemetry spans via source generation and compile-time interceptors
  • AWS Lambda Context – Captures Lambda context information in spans (request IDs, function name, etc.)
  • Custom Instrumentation – Inject ActivitySource to create spans for your business logic
  • Multiple Exporters – OTLP, Jaeger, AWS X-Ray, Datadog, and more
  • AOT Compatible – Works with .NET Native AOT compilation
  • Graceful Shutdown – Ensures traces export before Lambda terminates

Core Concepts

Automatic Root Span Creation

When you call UseOpenTelemetryTracing(), the framework uses source generators and compile-time interceptors to inject tracing middleware into your handler pipeline. This middleware delegates to the OpenTelemetry.Instrumentation.AWSLambda wrapper functions to create root spans for each Lambda invocation. These root spans capture AWS Lambda context (request IDs, function name, etc.) and measure the entire invocation duration.

How it works:

  • Compile Time: Source generators analyze your handler signature and create a compile-time interceptor that injects middleware into the pipeline
  • Startup: The middleware extracts a TracerProvider from the dependency injection container
  • Per Invocation: The middleware calls the appropriate AWS Lambda instrumentation wrapper function with the correct type information (event and response types), which uses the TracerProvider to create the root span

This happens at compile time with zero runtime reflection overhead. The actual span creation is delegated to the AWS Lambda OpenTelemetry instrumentation package.

Important

A TracerProvider must be registered in the dependency injection container before calling UseOpenTelemetryTracing(). If it's missing, an InvalidOperationException is thrown at startup. See the Quick Start section above for configuration details.

Note

This package creates the root invocation span automatically via the AWS instrumentation. If you want to instrument specific handlers, functions, or business logic within your Lambda, you create and manage those spans yourself using a custom ActivitySource (see below).

Custom Instrumentation with ActivitySource

To add traces for specific operations within your handler (database queries, API calls, business logic), create a custom ActivitySource. See the OpenTelemetry.io guide on setting up an ActivitySource for detailed information.

using System.Diagnostics;

internal class Instrumentation : IDisposable
{
    public const string ActivitySourceName = "MyLambda";
    public const string ActivitySourceVersion = "1.0.0";

    public ActivitySource ActivitySource { get; } =
        new(ActivitySourceName, ActivitySourceVersion);

    public void Dispose() => ActivitySource.Dispose();
}

Register it with the TracerProvider and inject it into your handler:

builder.Services.AddSingleton<Instrumentation>();

var lambda = builder.Build();

// In your handler:
lambda.MapHandler(([FromEvent] Request request, Instrumentation instrumentation) =>
{
    using var activity = instrumentation.ActivitySource.StartActivity("ProcessRequest");
    activity?.SetAttribute("request.name", request.Name);

    return ProcessRequest(request);
});

Custom spans created with your ActivitySource automatically link to the root Lambda invocation span, creating a complete trace of your function's execution. This is your responsibility—this package only provides the root invocation span.

Graceful Shutdown

Ensure all traces and metrics are exported before Lambda terminates:

lambda.OnShutdownFlushOpenTelemetry();

This registers shutdown handlers that force flush both the TracerProvider and MeterProvider with a configurable timeout (default: infinite):

lambda.OnShutdownFlushOpenTelemetry(timeoutMilliseconds: 5000);

You can also flush individually:

lambda.OnShutdownFlushTracer();
lambda.OnShutdownFlushMeter();

Example Project

A complete, runnable example with Docker Compose setup is available in examples/MinimalLambda.Example.OpenTelemetry.

The example demonstrates:

  • Full OpenTelemetry configuration with OTLP export
  • Custom instrumentation and metrics in a real handler
  • Jaeger tracing backend setup via Docker Compose
  • Running locally with AWS Lambda Test Tool
  • Viewing traces and metrics in the Jaeger UI

Documentation

Other Packages

Additional packages in the minimal-lambda framework for abstractions, observability, and event source handling.

Package NuGet Downloads
MinimalLambda NuGet Downloads
MinimalLambda.Abstractions NuGet Downloads
MinimalLambda.OpenTelemetry NuGet Downloads
MinimalLambda.Testing NuGet Downloads
MinimalLambda.Envelopes NuGet Downloads
MinimalLambda.Envelopes.Sqs NuGet Downloads
MinimalLambda.Envelopes.ApiGateway NuGet Downloads
MinimalLambda.Envelopes.Sns NuGet Downloads
MinimalLambda.Envelopes.Kinesis NuGet Downloads
MinimalLambda.Envelopes.KinesisFirehose NuGet Downloads
MinimalLambda.Envelopes.Kafka NuGet Downloads
MinimalLambda.Envelopes.CloudWatchLogs NuGet Downloads
MinimalLambda.Envelopes.Alb NuGet Downloads

License

This project is licensed under the MIT License. See LICENSE for details.