Skip to content

Swevo/Polly-Contrib-OpenTelemetry

Repository files navigation

PollyOpenTelemetry

NuGet NuGet Downloads CI License: MIT

OpenTelemetry instrumentation for Polly v8 resilience pipelines.

Emits distributed trace spans (Activity) and metrics for retry, circuit breaker, and timeout strategies — giving you full observability into your resilience layer.

Polly ships built-in logging and basic metrics via ConfigureTelemetry(ILoggerFactory).
This package adds the missing piece: OpenTelemetry-native traces and enriched metrics.


Installation

dotnet add package PollyOpenTelemetry

Quick Start

1. Register with the OpenTelemetry SDK

services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddPollyInstrumentation()          // register the "Polly" ActivitySource
        .AddOtlpExporter())
    .WithMetrics(metrics => metrics
        .AddPollyInstrumentation()          // register the "Polly" Meter
        .AddOtlpExporter());

2. Add to your resilience pipeline

var pipeline = new ResiliencePipelineBuilder()
    .AddPollyOpenTelemetry()                // ← one call enables both traces + metrics
    .AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 3,
        BackoffType = DelayBackoffType.Exponential,
    })
    .AddCircuitBreaker(new CircuitBreakerStrategyOptions
    {
        FailureRatio = 0.5,
        MinimumThroughput = 10,
    })
    .AddTimeout(TimeSpan.FromSeconds(30))
    .Build();

With Dependency Injection

services.AddResiliencePipeline("my-http-client", builder =>
{
    builder
        .AddPollyOpenTelemetry()
        .AddRetry(new RetryStrategyOptions { MaxRetryAttempts = 3 })
        .AddTimeout(TimeSpan.FromSeconds(30));
});

Emitted Telemetry

Activities (Traces)

Activity name When emitted
polly.attempt Each individual execution attempt
polly.retry Each retry decision
polly.circuit_breaker.opened Circuit breaker transitions to open
polly.circuit_breaker.closed Circuit breaker transitions to closed
polly.circuit_breaker.half_opened Circuit breaker transitions to half-open
polly.timeout Operation cancelled due to timeout

Common Activity Tags

Tag Value
polly.pipeline.name ResiliencePipelineBuilder.Name
polly.pipeline.instance_name ResiliencePipelineBuilder.InstanceName
polly.strategy.name Name of the individual strategy
polly.outcome success, failure, or unknown
error.type Exception type (on failure)

Additional Tags per Activity

polly.attempt: polly.attempt.number, polly.attempt.handled
polly.retry: polly.attempt.number, polly.retry.delay_ms
polly.circuit_breaker.opened: polly.circuit_breaker.break_duration_ms, polly.circuit_breaker.is_manual
polly.timeout: polly.timeout_ms

Metrics

Metric name Type Unit Description
polly.attempt.duration Histogram ms Duration of each individual execution attempt
polly.retry.count Counter {attempt} Number of retry decisions made
polly.circuit_breaker.open Counter {open} Number of times circuit breaker opened
polly.timeout.count Counter {timeout} Number of operations cancelled due to timeout

Options

builder.AddPollyOpenTelemetry(options =>
{
    options.EnableTracing = true;   // default: true
    options.EnableMetrics = true;   // default: true

    // Enrich activities with custom tags
    options.EnrichActivity = (activity, resilienceEvent, source) =>
    {
        activity.SetTag("my.custom.tag", "value");
    };
});

Composing with Polly's Built-in Logging

AddPollyOpenTelemetry() is safe to combine with Polly's built-in ConfigureTelemetry(ILoggerFactory) — both listeners are composed automatically:

var pipeline = new ResiliencePipelineBuilder()
    .ConfigureTelemetry(loggerFactory)    // Polly structured logging + basic metrics
    .AddPollyOpenTelemetry()              // OpenTelemetry traces + enriched metrics
    .AddRetry(...)
    .Build();

Sample Trace Output

▶ polly.attempt   [polly.pipeline.name=payment-api] [polly.attempt.number=0] [polly.outcome=failure]
  ✗ error.type=System.Net.Http.HttpRequestException
▶ polly.retry     [polly.retry.delay_ms=200] [polly.attempt.number=0]
▶ polly.attempt   [polly.pipeline.name=payment-api] [polly.attempt.number=1] [polly.outcome=success]

Requirements

  • .NET 8.0+
  • Polly 8.x
  • OpenTelemetry 1.x

Publishing

This package is published to NuGet.org via GitHub Actions using NuGet trusted publishing — no API key secret is stored in the repository.

Setup (one-time)

  1. On nuget.org, go to your package → ManageTrusted PublishersAdd a publisher
  2. Choose GitHub Actions and enter:
    • Owner: Sweevo
    • Repository: Polly-Contrib-OpenTelemetry
    • Workflow: build.yml
  3. Push a v* tag to trigger the publish workflow:
    git tag v1.0.0
    git push --tags

The workflow requests a short-lived OIDC token from GitHub (audience api.nuget.org) and uses it as the push credential — no NUGET_API_KEY secret required.


Support

If PollyOpenTelemetry improves your observability, consider supporting the project:

Sponsor

💼 Need .NET observability or resilience help? Visit solidqualitysolutions.com for consulting and architecture services.

Related Packages

Package Downloads Description
PollyHealthChecks Downloads ASP.NET Core health checks for Polly v8 circuit breakers — expose circuit-breaker state (Closed, HalfOpen, Open, Isolated) as /health endpoint responses
PollyBackoff Downloads Backoff delay strategies for Polly v8 resilience pipelines
PollyGrpc Downloads Polly v8 resilience interceptor for gRPC
PollyEFCore Downloads Polly v8 resilience pipelines for Entity Framework Core — wrap every EF Core query and SaveChanges with retry, timeout and circuit-breaker via a single AddPollyResilience() call
PollyRabbitMQ Downloads Polly v8 resilience for RabbitMQ.Client v7+ — retry, circuit-breaker, and timeout for IChannel operations, with built-in RabbitMqTransientErrors predicate covering AlreadyClosedException, BrokerUnreachableException, OperationInterruptedException, and ConnectFailureException
PollyOpenAI Downloads Polly v8 resilience for OpenAI and Azure OpenAI API calls
PollySignalR Downloads Polly v8 reconnect policy for SignalR
PollyMediatR Downloads Polly v8 resilience pipelines for MediatR — add retry, timeout, circuit-breaker, rate-limiting, hedging, and chaos engineering to any MediatR request handler with a single line of DI registration
PollyRedis Downloads Polly v8 resilience for StackExchange.Redis
PollyAzureServiceBus Downloads Polly v8 resilience for Azure Service Bus — retry, circuit breaker, and timeout for sending and receiving messages
PollyKafka Downloads Polly v8 resilience for Confluent.Kafka — retry, circuit breaker, and timeout for producers and consumers
PollyRateLimiter Downloads Convenience extension methods for Polly v8 resilience pipelines: AddFixedWindowRateLimiter, AddSlidingWindowRateLimiter, and AddTokenBucketRateLimiter
PollyCaching Downloads A caching resilience strategy for Polly v8 pipelines
PollyChaos Downloads Chaos engineering and fault-injection resilience strategies for Polly v8 pipelines
PollyBulkhead Downloads Bulkhead isolation strategy for Polly v8 resilience pipelines

Also by the same author

🌐 swevo.github.io

Package Description
AutoLog.Generator Compile-time high-performance logging — [Log(Level, Message)] generates LoggerMessage.Define. AOT-safe.
AutoHttpClient.Generator Compile-time typed HTTP client — [HttpClient] on an interface generates a strongly-typed client. AOT-safe Refit alternative.
AutoDispatch.Generator Compile-time CQRS dispatcher — [Handler] generates a strongly-typed IDispatcher. MediatR alternative.
AutoWire Compile-time DI auto-registration — [Scoped]/[Singleton]/[Transient] generates IServiceCollection registration code.
AutoMap.Generator Compile-time object mapping — [Map(typeof(Dto))] generates ToDto() extension methods. AutoMapper alternative.

License

MIT — Copyright © 2025 Justin Bannister

About

OpenTelemetry instrumentation for Polly v8 resilience pipelines.

Topics

Resources

License

Stars

2 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages