resilience
БесплатноБез исполняемых скриптовНе проверенResilience and HTTP clients for .NET 10: Polly v8, Microsoft.Extensions.Http.Resilience, retry, circuit breaker, timeout, hedging, IHttpClientFactory…
от codewithmukesh★ 858 звёзд на GitHubОб этом скилле
Resilience
Core Principles
- Polly v8 resilience pipelines, not v7 policies — Polly v8 replaced
PolicywithResiliencePipeline. Never usePolicyBuilder,Policy.Handle<>(), orISyncPolicy. The new API is composable, type-safe, and integrates natively withIHttpClientFactory. - Configure via
AddResilienceHandler, not manual wrapping — For HTTP calls, useMicrosoft.Extensions.Http.Resiliencewhich adds pipelines directly toHttpClientvia DI. No manualExecuteAsyncwrapping. - Compose strategies, don't nest them — A single
ResiliencePipelinecan chain retry + circuit breaker + timeout. Strategies execute outer-to-inner (first added = outermost). No need for nested try/catch or manual orchestration. - Always set timeouts — Every external call needs a timeout. Use Polly's
AddTimeout()as the innermost strategy so it applies per-attempt, and optionally an outer timeout for total elapsed time. - Clients come from the factory. Never
new HttpClient()per request; use typed or keyed clients and put resilience on every external one. Client wiring is inreferences/httpclient-factory.md. - Instrument everything — Polly v8 emits
Meteringevents and supportsTelemetryOptionsfor OpenTelemetry. Use them to monitor retry rates, circuit breaker state, and timeout frequency.
Patterns
Samples assume these namespaces: System.Net, Polly, Polly.Retry, Polly.CircuitBreaker, Polly.Fallback, Polly.Telemetry, Microsoft.Extensions.Http.Resilience, Microsoft.AspNetCore.RateLimiting, Microsoft.AspNetCore.Mvc (ProblemDetails) and OpenTelemetry.Metrics.
HTTP Client Resilience (Recommended Default)
builder.Services.AddHttpClient<IPaymentGateway, PaymentGatewayClient>(client =>
{
client.BaseAddress = new Uri("https://api.payments.example.com");
})
.AddStandardResilienceHandler();
dotnet add package Microsoft.Extensions.Http.Resilience. The standard handler chains a rate limiter (1000 concurrent), total timeout (30s), retry (3 attempts, exponential backoff with jitter), circuit breaker (10% failure ratio, 30s sampling) and per-attempt timeout (10s). Override only the thresholds you need:
.AddStandardResilienceHandler(options =>
{
options.Retry.MaxRetryAttempts = 5;
options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(15);
options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(60);
options.Retry.DisableForUnsafeHttpMethods(); // no retries for POST/PUT/PATCH/DELETE
})
Why: Production-ready defaults in one line. Keyed clients (.AddAsKeyed()), DelegatingHandlers for auth and correlation IDs, handler ordering, SocketsHttpHandler tuning and test stubs are in references/httpclient-factory.md.
Custom HTTP Resilience Configuration
builder.Services.AddHttpClient<ICatalogService, CatalogServiceClient>(client =>
{
client.BaseAddress = new Uri("https://api.catalog.example.com");
})
.AddResilienceHandler("catalog", builder =>
{
// Total timeout — outermost, caps total elapsed time
builder.AddTimeout(TimeSpan.FromSeconds(15));
// Retry — exponential backoff with jitter
builder.AddRetry(new HttpRetryStrategyOptions
{
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
Delay = TimeSpan.FromMilliseconds(500),
ShouldHandle = static args => ValueTask.FromResult(
args.Outcome.Result?.StatusCode is HttpStatusCode.RequestTimeout
or HttpStatusCode.TooManyRequests
or HttpStatusCode.ServiceUnavailable
|| args.Outcome.Exception is HttpRequestException)
});
// Circuit breaker — prevent cascading failures
builder.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.5,
SamplingDuration = TimeSpan.FromSeconds(10),
MinimumThroughput = 10,
BreakDuration = TimeSpan.FromSeconds(30)
});
// Per-attempt timeout — innermost
builder.AddTimeout(TimeSpan.FromSeconds(5));
});
Why: Named resilience handlers let you tune per-service. The order matters: total timeout > retry > circuit breaker > attempt timeout.
Non-HTTP Resilience Pipeline
// For database calls, message queues, or any non-HTTP operation
builder.Services.AddResiliencePipeline("database", builder =>
{
builder
.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Exponential,
Delay = TimeSpan.FromMilliseconds(200),
ShouldHandle = new PredicateBuilder()
.Handle<TimeoutException>()
.Handle<InvalidOperationException>(ex =>
ex.Message.Contains("deadlock", StringComparison.OrdinalIgnoreCase))
})
.AddTimeout(TimeSpan.FromSeconds(10));
});
// Inject and use
public sealed class OrderRepository(
AppDbContext d
Установить resilience в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл resilience?
Resilience and HTTP clients for .NET 10: Polly v8, Microsoft.Extensions.Http.Resilience, retry, circuit breaker, timeout, hedging, IHttpClientFactory, typed/named/keyed clients, DelegatingHandlers. Use for "Polly", "retry", "circuit breaker", "HttpClient", "IHttpClientFactory", "AddStandardResilienceHandler", "Refit". Do NOT use for caching (use caching) or inbound rate limiting (use rate-limiting).
Как установить скилл resilience?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл resilience запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic