ZeroAlloc.Resilience by Marcel Roozekrans
NuGet / site data
Details
Info
Name: ZeroAlloc.Resilience
Source-generated, zero-allocation resilience policies for .NET. Add [Retry], [Timeout], [RateLimit], and [CircuitBreaker] to an interface; the generator emits a proxy composing all policies in declaration order. AOT-safe.
Author: Marcel Roozekrans
NuGet: https://www.nuget.org/packages/ZeroAlloc.Resilience/
You can find more details at https://github.com/ZeroAlloc-Net/ZeroAlloc.Resilience
Source: https://github.com/ZeroAlloc-Net/ZeroAlloc.Resilience
Author
Marcel Roozekrans

Original Readme
ZeroAlloc.Resilience
Retry, timeout, rate limiting and circuit breaking for .NET, declared as attributes on an interface and compiled into a proxy: a source-generated alternative to Polly with no allocation on the happy path.
Why ZeroAlloc.Resilience
- 0 B per successful call through
[Retry]and[CircuitBreaker], asserted by tests on every run. Polly v8 allocates a 64 BResilienceContextper call. - 20× and 23× faster than Polly v8 on the retry and circuit-breaker happy paths, and 7.7× faster with all four policies stacked, measured in the same run.
- Works under NativeAOT and trimming. The proxy is plain generated code with no reflection, published as a NativeAOT app in CI.
- Mistakes surface at compile time. A misspelled fallback, an invalid attribute value or a timeout on a method without a
CancellationTokenis a compiler diagnostic.
Install
dotnet add package ZeroAlloc.Resilience
dotnet add package Microsoft.Extensions.DependencyInjection
Targets .NET 10 and .NET 11. The generated Add\{Name}\}Resilience registration methods appear when the project references Microsoft.Extensions.DependencyInjection.Abstractions, which ASP.NET Core and generic-host apps already do; the package does not bring it. The second command adds the container the quick start below uses, and the abstractions with it.
Quick start
using Microsoft.Extensions.DependencyInjection;
using ZeroAlloc.Resilience;
var services = new ServiceCollection();
services.AddWeatherClientResilience<FlakyWeatherClient>(); // generated: registers the proxy
var client = services.BuildServiceProvider().GetRequiredService<IWeatherClient>();
Console.WriteLine(await client.GetForecastAsync("Amsterdam", CancellationToken.None));
// Amsterdam: sunny, after 3 attempts
[Retry(MaxAttempts = 3, BackoffMs = 100, Jitter = true)]
[Timeout(Ms = 5_000)]
[CircuitBreaker(MaxFailures = 5, ResetMs = 30_000)]
public interface IWeatherClient
{
ValueTask<string> GetForecastAsync(string city, CancellationToken ct);
}
public sealed class FlakyWeatherClient : IWeatherClient
{
private int _calls;
public ValueTask<string> GetForecastAsync(string city, CancellationToken ct)
=> ++_calls < 3
? throw new HttpRequestException($"attempt {_calls} failed")
: ValueTask.FromResult($"{city}: sunny, after {_calls} attempts");
}
The first two calls throw, the proxy retries, and the caller only sees the result. Callers inject IWeatherClient as usual.
What you get
- Retry with exponential backoff, jitter, a per-attempt timeout and a cap on the delay.
- Timeout over the whole operation, retries and backoff included.
- Rate limiting with a lock-free token bucket, shared per interface or per proxy.
- Circuit breaker with half-open probing and an optional fallback method.
- A fixed, predictable order: rate limit, circuit breaker, timeout, retry, whatever order you write the attributes in.
- Exceptions or Results: return a ZeroAlloc.Results
Result<T>and policy failures come back as a failure instead of a throw. - Result-aware retry: retry only the failures you call transient, and honour
Retry-Afterhints. - Per-method overrides of the interface-level policies, for example one attempt for a non-idempotent POST.
- One-line DI registration through a generated
Add{Service}Resilience<TImpl>()extension. - Compile-time diagnostics ZR0001–ZR0015: the full list. Every attribute property: attribute reference.
Performance
Against Polly.Core 8.8.0 on .NET 10.0.13, measured 2026-10-21. Allocations are exact; speed is a same-run ratio.
| Operation | ZA vs Polly | Polly alloc | ZA alloc |
|---|---|---|---|
| Retry, happy path | 20.0× faster | 64 B | 0 B |
| CircuitBreaker, closed | 23.3× faster | 64 B | 0 B |
| All-policies stacked, happy path | 7.7× faster | 104 B | 144 B |
With all policies stacked, the 144 B is the linked CancellationTokenSource and timer that [Timeout] needs; without [Timeout] the proxy allocates nothing. Polly walks a delegate chain per call; ZA emits one method with the policy checks inline. Failure paths, an open circuit and the full method: docs/performance.md.
Learn more
- Documentation: resilience.zeroalloc.net
- Getting started, execution order, Result return types and migrating to 4.0
- Related packages: ZeroAlloc.Rest for source-generated HTTP clients, ZeroAlloc.Cache for caching proxies, ZeroAlloc.Telemetry for tracing and metrics proxies
- Contributing: issues and pull requests are welcome on GitHub
- License: MIT
About
Generating resilience proxies with retry, timeout, rate limiting, and circuit-breaker policies
How to use
Example (source csproj, source files)
- CSharp Project
- Program.cs
This is the CSharp Project that references ZeroAlloc.Resilience
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ZeroAlloc.Resilience" Version="4.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.15" />
</ItemGroup>
</Project>
This is the use of ZeroAlloc.Resilience in Program.cs
using Microsoft.Extensions.DependencyInjection;
using ZeroAlloc.Resilience;
var services = new ServiceCollection();
services.AddWeatherClientResilience<FlakyWeatherClient>();
using var provider = services.BuildServiceProvider();
var client = provider.GetRequiredService<IWeatherClient>();
Console.WriteLine(await client.GetForecastAsync("Amsterdam", CancellationToken.None));
[Retry(MaxAttempts = 3, BackoffMs = 100, Jitter = true)]
//[Timeout(Ms = 5_000)]
//[RateLimit(MaxPerSecond = 100, BurstSize = 10)]
//[CircuitBreaker(MaxFailures = 5, ResetMs = 30_000)]
public interface IWeatherClient
{
ValueTask<string> GetForecastAsync(string city, CancellationToken ct);
}
public sealed class FlakyWeatherClient : IWeatherClient
{
private int _calls;
public ValueTask<string> GetForecastAsync(string city, CancellationToken ct)
=> ++_calls < 2
? throw new HttpRequestException($"attempt {_calls} failed")
: ValueTask.FromResult($"{city}: sunny, after {_calls} attempts");
}
Generated Files
Those are taken from $(BaseIntermediateOutputPath)\GX
- IWeatherClient.Resilience.g.cs
// <auto-generated />
#nullable enable
using System.Threading;
using System.Threading.Tasks;
using ZeroAlloc.Resilience;
using Microsoft.Extensions.DependencyInjection;
public sealed class WeatherClientResiliencePolicies
{
public global::ZeroAlloc.Resilience.RetryPolicy Retry \{ get; set; \} = new global::ZeroAlloc.Resilience.RetryPolicy(3, 100, true, 0);
}
internal sealed class IWeatherClientResilienceProxy : global::IWeatherClient
{
private readonly global::IWeatherClient _inner;
private readonly global::ZeroAlloc.Resilience.RetryPolicy _retry;
public IWeatherClientResilienceProxy(global::IWeatherClient inner, WeatherClientResiliencePolicies policies)
{
global::System.ArgumentNullException.ThrowIfNull(inner);
global::System.ArgumentNullException.ThrowIfNull(policies);
_inner = inner;
_retry = (policies.Retry ?? throw new global::System.ArgumentException("WeatherClientResiliencePolicies.Retry is null.", nameof(policies)));
}
public async global::System.Threading.Tasks.ValueTask<string> GetForecastAsync(string city, global::System.Threading.CancellationToken ct)
{
global::System.Exception? __lastEx = null;
for (int __attempt = 0; __attempt < _retry.MaxAttempts; __attempt++)
{
using var __attemptCts = _retry.PerAttemptTimeoutMs > 0
? global::System.Threading.CancellationTokenSource.CreateLinkedTokenSource(ct)
: null;
__attemptCts?.CancelAfter(_retry.PerAttemptTimeoutMs);
var __ct = __attemptCts?.Token ?? ct;
try
{
var __result = await _inner.GetForecastAsync(city, __ct).ConfigureAwait(false);
return __result;
}
catch (global::System.OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (global::System.Exception __ex)
{
__lastEx = __ex;
if (__attempt == _retry.MaxAttempts - 1) break;
await global::System.Threading.Tasks.Task.Delay(_retry.GetBackoffMs(__attempt), ct).ConfigureAwait(false);
}
}
// All attempts exhausted
throw new global::ZeroAlloc.Resilience.ResilienceException(global::ZeroAlloc.Resilience.ResiliencePolicy.Retry, "All retry attempts failed.", __lastEx);
}
}
public static partial class ResilienceServiceCollectionExtensions
{
public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddWeatherClientResiliencePolicies(
this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services,
global::System.Action<global::System.IServiceProvider, WeatherClientResiliencePolicies>? configure = null)
{
global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton<WeatherClientResiliencePolicies>(services, sp =>
{
var policies = new WeatherClientResiliencePolicies();
configure?.Invoke(sp, policies);
return policies;
});
return services;
}
public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddWeatherClientResilience<
[global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(
global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
TImpl>(
this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services)
where TImpl : class, global::IWeatherClient
{
services.AddTransient<TImpl>();
services.AddWeatherClientResiliencePolicies();
services.AddTransient<global::IWeatherClient>(sp => new IWeatherClientResilienceProxy(
sp.GetRequiredService<TImpl>(), sp.GetRequiredService<WeatherClientResiliencePolicies>()));
return services;
}
public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddWeatherClientResilience<
[global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(
global::System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)]
TImpl>(
this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services,
global::System.Action<global::System.IServiceProvider, WeatherClientResiliencePolicies> configure)
where TImpl : class, global::IWeatherClient
{
global::System.ArgumentNullException.ThrowIfNull(configure);
services.AddTransient<TImpl>();
services.AddWeatherClientResiliencePolicies(configure);
services.AddTransient<global::IWeatherClient>(sp => new IWeatherClientResilienceProxy(
sp.GetRequiredService<TImpl>(), sp.GetRequiredService<WeatherClientResiliencePolicies>()));
return services;
}
}
Useful
Download Example (.NET C#)
Share ZeroAlloc.Resilience
https://ignatandrei.github.io/RSCG_Examples/v2/docs/ZeroAlloc.Resilience
Category "AOP" has the following generators:
1 Splice
2026-11-20
2 WhatIAmDoing
2024-01-28
3 ZeroAlloc.Resilience
2026-11-17