TL.Resilience 0.5.0

dotnet add package TL.Resilience --version 0.5.0
                    
NuGet\Install-Package TL.Resilience -Version 0.5.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TL.Resilience" Version="0.5.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TL.Resilience" Version="0.5.0" />
                    
Directory.Packages.props
<PackageReference Include="TL.Resilience" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add TL.Resilience --version 0.5.0
                    
#r "nuget: TL.Resilience, 0.5.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package TL.Resilience@0.5.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=TL.Resilience&version=0.5.0
                    
Install as a Cake Addin
#tool nuget:?package=TL.Resilience&version=0.5.0
                    
Install as a Cake Tool

🛡️ TL.Resilience

Módulo corporativo de resiliência e tolerância a falhas para microsserviços e Web APIs em .NET 8 e .NET 9 baseado em Polly v8.

.NET 8.0 .NET 9.0 License: MIT


📑 Sumário


🌟 Visão Geral

O TL.Resilience padroniza a implementação de políticas defensivas em chamadas externas e operações assíncronas utilizando a engine moderna do Polly v8 (Polly.Core):

  1. Backoff Exponencial com Decorrelated Jitter: Evita o efeito manada (thundering herd) espalhando temporalmente as retentativas.
  2. Resiliência Integrada em HttpClient: Extensão .AddStandardResilience() para IHttpClientBuilder que configura automaticamente retentativas para erros 5xx/408, circuit breaker e timeout.
  3. Cancelamento e Logs Estruturados: Respeito rigoroso a CancellationToken e alertas estruturados via ILogger.

📦 Instalação

Adicione o pacote ao seu projeto via .NET CLI:

dotnet add package TL.Resilience --version 0.4.0

🚀 Como Usar

1. Execução Resiliente com Backoff Exponencial e Jitter

Utilize ResilienceHelper.ExecuteWithRetryAsync para proteger chamadas assíncronas contra falhas transitórias:

using TL.Resilience;

var resultado = await ResilienceHelper.ExecuteWithRetryAsync(async ct =>
{
    return await servicoExterno.ConsultarDadosAsync(ct);
}, maxRetryAttempts: 3, initialDelay: TimeSpan.FromMilliseconds(200));

2. Suporte a CancellationToken e ILogger

Propague tokens de cancelamento e injete instâncias de telemetria estruturada:

using TL.Resilience;

await ResilienceHelper.ExecuteWithRetryAsync(async ct =>
{
    await servicoPagamento.ProcessarTransacaoAsync(dados, ct);
}, 
maxRetryAttempts: 3, 
initialDelay: TimeSpan.FromMilliseconds(300),
logger: _logger,
cancellationToken: cancellationToken);

3. Resiliência Padronizada em HttpClient (AddStandardResilience)

No Program.cs, registre clientes HTTP protegidos com uma única linha:

using TL.Resilience;

builder.Services.AddHttpClient("GatewayPagamentos", client =>
{
    client.BaseAddress = new Uri("https://api.gateway.com");
})
.AddStandardResilience();

Essa configuração ativa:

  • Retry Strategy: 3 tentativas com backoff exponencial e jitter para status 5xx, 408 (Request Timeout), HttpRequestException e TimeoutRejectedException.
  • Circuit Breaker Strategy: Interrupção temporária de tráfego se a taxa de falha atingir 50% em amostragem de 30s.
  • Timeout Strategy: Limite de 30 segundos por tentativa.

🏛️ Políticas Padronizadas

Estratégia Parâmetro Padrão Comportamento
Retry 3 tentativas, backoff exponencial + jitter Trata falhas de rede, 5xx e 408 com espaçamento decorrelacionado
Circuit Breaker 50% de falhas, quebra de 15s Bloqueia chamadas quando o destino estiver consistentemente indisponível
Timeout 30 segundos Evita retenção prolongada de threads e conexões em espera
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.5.0 114 9/28/2026
0.4.0 97 9/25/2026
0.3.1 107 9/22/2026
0.3.0 106 9/18/2026