Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

resilience

БесплатноБез исполняемых скриптовНе проверен

Resilience and HTTP clients for .NET 10: Polly v8, Microsoft.Extensions.Http.Resilience, retry, circuit breaker, timeout, hedging, IHttpClientFactory…

codewithmukeshот codewithmukesh★ 858 звёзд на GitHub

Об этом скилле

Resilience

Core Principles

  1. Polly v8 resilience pipelines, not v7 policies — Polly v8 replaced Policy with ResiliencePipeline. Never use PolicyBuilder, Policy.Handle<>(), or ISyncPolicy. The new API is composable, type-safe, and integrates natively with IHttpClientFactory.
  2. Configure via AddResilienceHandler, not manual wrapping — For HTTP calls, use Microsoft.Extensions.Http.Resilience which adds pipelines directly to HttpClient via DI. No manual ExecuteAsync wrapping.
  3. Compose strategies, don't nest them — A single ResiliencePipeline can chain retry + circuit breaker + timeout. Strategies execute outer-to-inner (first added = outermost). No need for nested try/catch or manual orchestration.
  4. 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.
  5. 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 in references/httpclient-factory.md.
  6. Instrument everything — Polly v8 emits Metering events and supports TelemetryOptions for 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
Полный SKILL.md на GitHub

Установить resilience в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/httpclient-factory.md

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), без исполняемых скриптов.

Похожие скиллы

Сравнить resilience с