liveBook · Manning

Polly

As explained in .NET in Action, Second Edition

Polly is a .NET resilience library for expressing policies such as retries, circuit breakers, timeouts, and fallbacks.

Polly is the de facto .NET resilience library for expressing retry and other error-handling policies outside or alongside EF Core. Microsoft.Extensions.Http.Polly integrates those policies with HttpClientFactory, so an HTTP client can retry without embedding try/catch logic in each request method. section 11.3 section 11.4

Listing 11.15 Registering HttpClient with a Polly policy
services.AddHttpClient<IXkcdClient, XkcdClient>(
  client => client.BaseAddress =
  new Uri(baseAddr!))                        #1
  .AddPolicyHandler(GetRetryPolicy());       #2

Register a typed HttpClient and attach a Polly policy through AddPolicyHandler. section 11.3

Listing 11.16 Polly policy that retries on invalid HTTP response codes
using Polly;                                                #1
using Polly.Extensions.Http;
  
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()   #2
  => HttpPolicyExtensions                                   #3
    .HandleTransientHttpError()                             #4
    .WaitAndRetryAsync(6, retryCount =>                     #5
      TimeSpan.FromMilliseconds(                            #6
        100 * Math.Pow(2, retryCount)));                    #7

Build an asynchronous HTTP retry policy that handles transient failures and waits with exponential back-off. section 11.3

Listing 11.17 Custom HTTP response-code retry policy
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
  => Policy<HttpResponseMessage>                          #1
    .HandleResult(r => r.StatusCode ==
      System.Net.HttpStatusCode.TooManyRequests)          #2
    .OrTransientHttpStatusCode()                          #3
    .WaitAndRetryAsync(6, retryCount =>                   #4
      TimeSpan.FromMilliseconds(
        100 * Math.Pow(2, retryCount)));

Customize the policy when retry conditions must include a specific response, such as HTTP 429 TooManyRequests. section 11.3

Polly extends beyond retries with resilience strategies for different failure patterns:

  • Timeouts stop operations from waiting indefinitely. section 11.3.2
  • Fallbacks return an alternative value when recovery is unlikely within a reasonable period. section 11.3.2
  • Circuit breakers pause calls after failures exceed a threshold, then test the resource before closing. section 11.3.2
  • Bulkheads limit concurrent requests and queue later work; rate limiting governs request volume over time. section 11.3.2

Testing an HTTP policy

Use a mocked HttpMessageHandler to simulate a 500 response and verify that the XkcdClient's policy retries as intended. section 11.3 section 11.4

How .NET in Action, Second Edition covers it

How deep it goes
Builds and registers retry policies, explains back-off and alternatives, then surveys timeouts, fallbacks, circuit breakers, bulkheads, and rate limiting.
Examples
Uses an XKCD API client, mocked HTTP handler, transient errors, HTTP 429 responses, and exponential retry delays.
What it assumes
Assumes C#, HttpClient registration, dependency injection, asynchronous methods, and familiarity with EF Core retry behavior.
What you can do after
Apply it via Microsoft.Extensions.Http.Polly to configure, customize, and test resilience policies for HttpClient operations.
How it connects
Connects retries with HttpClientFactory, dependency injection, EF Core, timeouts, fallbacks, circuit breakers, bulkheads, and rate limiting.

Also explained in

Compare how 2 books explain Polly →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.