Skip to main content

Lesson 5 of 8

IHttpClientFactory & Polly Resilience

IHttpClientFactory manages HttpClient lifetimes properly - avoiding socket exhaustion and DNS staleness. Polly adds retry, circuit breaker, timeout, and fallback policies to handle transient failures in downstream services gracefully.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Typed HttpClient with Polly Resilience

Typed HttpClient with Polly Resilience
// dotnet add package Microsoft.Extensions.Http.Polly

// ━━ Typed HttpClient - encapsulates API-specific config ━━
public class StripePaymentClient(HttpClient httpClient)
{
    public async Task<PaymentResult> ChargeAsync(ChargeRequest charge, CancellationToken ct)
    {
        var response = await httpClient.PostAsJsonAsync("/v1/payment_intents", charge, ct);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<PaymentResult>(cancellationToken: ct)
               ?? throw new InvalidOperationException("Empty response from Stripe");
    }
}

// ━━ Registration with retry + circuit breaker ━━
builder.Services
    .AddHttpClient<StripePaymentClient>(client =>
    {
        client.BaseAddress = new Uri("https://api.stripe.com/");
        client.DefaultRequestHeaders.Add("Authorization",
            $"Bearer {builder.Configuration["Stripe:SecretKey"]}");
        client.Timeout = TimeSpan.FromSeconds(30);
    })
    // ━━ Polly: retry transient failures 3 times with exponential back-off ━━
    .AddTransientHttpErrorPolicy(policy =>
        policy.WaitAndRetryAsync(
            retryCount: 3,
            sleepDurationProvider: attempt =>
                TimeSpan.FromSeconds(Math.Pow(2, attempt)) // 2s, 4s, 8s
                + TimeSpan.FromMilliseconds(new Random().Next(0, 100)), // jitter
            onRetry: (outcome, delay, attempt, ctx) =>
                Console.WriteLine($"Retry {attempt} after {delay.TotalSeconds}s: {outcome.Exception?.Message}")))
    // ━━ Polly: circuit breaker - fail fast when service is down ━━
    .AddTransientHttpErrorPolicy(policy =>
        policy.CircuitBreakerAsync(
            handledEventsAllowedBeforeBreaking: 5,   // open after 5 consecutive failures
            durationOfBreak: TimeSpan.FromSeconds(30), // stay open for 30s
            onBreak: (result, breakDelay) =>
                Console.WriteLine($"Circuit OPEN - Stripe unreachable. Break for {breakDelay.TotalSeconds}s"),
            onReset: () => Console.WriteLine("Circuit CLOSED - Stripe reachable again"),
            onHalfOpen: () => Console.WriteLine("Circuit HALF-OPEN - testing Stripe")));

// ━━ Named client for simpler cases ━━
builder.Services.AddHttpClient("github", c =>
{
    c.BaseAddress = new Uri("https://api.github.com");
    c.DefaultRequestHeaders.UserAgent.ParseAdd("MyApp/1.0");
});

// Usage:
var factory = app.Services.GetRequiredService<IHttpClientFactory>();
var github = factory.CreateClient("github");
var repos = await github.GetFromJsonAsync<object>("/users/dotnet/repos");

record ChargeRequest(decimal Amount, string Currency, string CustomerId);
record PaymentResult(string Id, string Status);

Tip

Tip

Practice IHttpClientFactory Polly Resilience in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of IHttpClientFactory Polly Resilience from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with IHttpClientFactory Polly Resilience is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done