Search Sreeni's Insights

Filter by content type
crafting October 3, 2017 8 min read

Resilient HTTP calls with Polly - retry, timeout and circuit breaker

Polly 5.x adds retry, timeout and circuit breaker policies around HTTP calls, with guidance on composition, transient failures, idempotency and safe handling of writes.

Share:

Resilient HTTP calls with Polly - retry, timeout and circuit breaker

An HTTP call crosses a boundary which our process does not control. The remote service can be slow, temporarily unavailable or returning a server error, and the network can fail while the request is in transit. If every caller handles these situations differently, customers see random failures and operators do not have a consistent way to protect the application.

In this article, we are going to discuss how Polly 5.x can add retry, timeout and circuit breaker policies around a shared HttpClient. We will see how to compose policies with Policy.WrapAsync, why the order matters, and why retrying a non-idempotent POST needs special care. Last year, in the idempotency article, we discussed why repeating a business command can create duplicate effects; refer that article before adding retries to writes.

TL;DR Summary

  • Retry transient failures only, with a bounded count and exponential back-off.
  • Use a timeout so one slow dependency cannot hold request resources forever.
  • Use a circuit breaker to stop calling a dependency which is repeatedly failing.
  • Wrap policies deliberately: the outer policy sees the result of the inner policy.
  • Retry idempotent operations more safely than non-idempotent POST operations.
  • Polly 5.x policies can be used with a shared static HttpClient; do not create a new client for every request.

Challenges

Transient failures

A price service can fail for a few seconds while a node is restarting or while the network route is recovering. Returning an error immediately is making a temporary problem visible to every customer. A bounded retry can recover the request without asking the customer to try again.

Retry is not correct for every failure. A 400 response is normally a caller error, and a 404 response may be a valid business result. Retrying those responses is adding load without improving the result.

Slow dependencies

A remote API may accept a request but not return a response in a reasonable time. Without a timeout, every incoming request is holding a thread, socket or other resource while waiting. A small number of slow calls can then make our own API look unavailable.

Repeated failures

When a dependency is down, retrying every request is making the outage worser. The remote service is receiving more traffic while it is recovering, and our own application is spending resources on calls which are very likely to fail. A circuit breaker can fail fast for a period and give the dependency time to recover.

What is Polly?

Polly is a .NET resilience and transient-fault-handling library which allows us to define policies for retries, timeouts, circuit breaking and other failure handling.

In simple terms, Polly is giving a caller a repeatable rule for what to do when an HTTP dependency is failing. It is not making a failed service healthy, and it is not replacing good API design or operational monitoring.

The following diagram depicts the circuit breaker states.

Polly circuit breaker states
Polly circuit breaker states

The circuit is normally Closed and requests are flowing to the dependency. After the configured number of handled failures, it opens and calls fail fast. After the break duration, it moves to Half-open and allows a probe request. A successful probe closes the circuit; another handled failure opens it again.

Why resilience policies are important?

Resilience policies are important because they are limiting the ripple effect of a dependency failure. A fund API should not consume all its request capacity while a market-data provider is unavailable. With a timeout, retry and breaker, we can make a bounded attempt, record the failure and keep resources available for other operations.

The policies must be based on the dependency contract. A retry can hide an outage if it is too broad, and a breaker can reject valid traffic if its thresholds are too sensitive. We should measure failures and tune the policy over the period.

Handle only transient results

Install the Polly package which was used by the application,

dotnet add package Polly

Define what should be handled,

var transientHttp = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(response =>
        (int)response.StatusCode >= 500);

This policy handles network exceptions and server responses from 500 onwards. Add 408 or 429 only when the dependency contract says they are transient and the caller is respecting any Retry-After guidance. Do not handle every Exception, because programming errors should not be hidden as transient failures.

Add a bounded retry

Use WaitAndRetryAsync with a small number of attempts and exponential back-off,

var retry = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(response =>
        (int)response.StatusCode >= 500)
    .WaitAndRetryAsync(
        3,
        attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
        (outcome, delay, attempt, context) =>
        {
            Log.Warning(
                "HTTP retry {Attempt} after {Delay} seconds",
                attempt,
                delay.TotalSeconds);
        });

The delays are increasing instead of sending all retries immediately. In a busy system, add jitter when the Polly version and policy design support it, so many callers are not retrying at exactly the same time. Keep the total wait within the user-facing timeout.

The retry callback should not write the complete response body or request headers to the log. Add a dependency name, operation name and correlation id, but follow the logging rules about secrets and PII.

Add a timeout

A timeout limits how long the HTTP execution is allowed to run,

var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
    TimeSpan.FromSeconds(5));

Polly’s optimistic timeout cancels through the cancellation token, so HttpClient must receive it, otherwise the timeout will not fire.

Choose the timeout from the business operation, not only from the network. A report which can take a minute has a different budget from a price pulse check. The timeout should be visible in metrics and logs, otherwise operators cannot distinguish a slow dependency from a returned 500.

Add a circuit breaker

A circuit breaker opens after a configured number of handled failures,

var breaker = Policy
    .Handle<HttpRequestException>()
    .OrResult<HttpResponseMessage>(response =>
        (int)response.StatusCode >= 500)
    .CircuitBreakerAsync(
        exceptionsAllowedBeforeBreaking: 2,
        durationOfBreak: TimeSpan.FromSeconds(30),
        onBreak: (outcome, breakDuration) =>
        {
            Log.Error(
                "Price service circuit opened for {Seconds} seconds",
                breakDuration.TotalSeconds);
        },
        onReset: () =>
        {
            Log.Information("Price service circuit closed");
        });

With this configuration, two handled failures open the circuit for 30 seconds. The exact values are examples, not universal numbers. A shared breaker should be scoped to the dependency and meaningful operation, otherwise one failing fund request can unnecessarily block unrelated calls.

Wrap policies and understand the order

Compose the policies with Policy.WrapAsync,

var policy = Policy.WrapAsync(
    retry,
    timeout,
    breaker);

The order matters. The first policy is the outer policy and the last policy is the inner policy. In this example, the execution is entering retry, then timeout, then breaker, and finally HttpClient.

The following diagram explains the policy wrap order.

Polly policy wrap order
Polly policy wrap order

The outer retry sees the result of the inner timeout and breaker. A single attempt is protected by the timeout, and the breaker records the handled result of that attempt. When the breaker is open, the inner execution fails fast and the outer retry should not blindly turn that fast failure into more calls. The exact interaction depends on the policy predicates, so test the chosen order with the failure cases we care about.

Some teams prefer timeout outside retry, which gives one total timeout budget for all attempts. Other teams use retry outside a per-attempt timeout, which allows each attempt its own budget. The correct choice depends on the user-facing SLA, but it must be deliberate and documented.

Use a shared HttpClient

Create and reuse one HttpClient for the lifetime of the process,

using System.Threading;

public static class PriceClient
{
    private static readonly HttpClient Client = new HttpClient
    {
        BaseAddress = new Uri("https://prices.example.com")
    };

    private static readonly IAsyncPolicy<HttpResponseMessage> PricePolicy =
        CreatePolicy();

    public static Task<HttpResponseMessage> GetAsync(
        string fundId)
    {
        return PricePolicy.ExecuteAsync(
            ct => Client.GetAsync("/prices/" + fundId, ct),
            CancellationToken.None);
    }

    private static IAsyncPolicy<HttpResponseMessage> CreatePolicy()
    {
        var retry = Policy
            .Handle<HttpRequestException>()
            .OrResult<HttpResponseMessage>(r => (int)r.StatusCode >= 500)
            .WaitAndRetryAsync(3, attempt =>
                TimeSpan.FromSeconds(Math.Pow(2, attempt)));

        var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(5));

        var breaker = Policy
            .Handle<HttpRequestException>()
            .OrResult<HttpResponseMessage>(r => (int)r.StatusCode >= 500)
            .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));

        return Policy.WrapAsync(retry, timeout, breaker);
    }
}

Creating a new HttpClient for each request can exhaust sockets and can prevent connection reuse. Reuse the client for the lifetime of the application. Make the base address and timeout configuration visible, and keep one policy per dependency rather than copying slightly different policies into every controller.

Retry and idempotency

GET is normally idempotent, but “normally” is not a guarantee. Verify the dependency contract. A POST which creates a fund document may have completed on the server even when the response was lost. Retrying it can create two documents.

For a write, use an idempotency key when the server supports it, or design the operation so the same business command can be safely repeated. If neither is possible, do not add an automatic retry just because the network exception looks transient. Refer the idempotency article before deciding.

Must Do / Should / Don’t

Must Do

  • Must handle only known transient exceptions and status codes.
  • Must bound retries and use back-off, otherwise a failure will create a retry storm.
  • Must configure a timeout for every remote call.
  • Must use a shared HttpClient, otherwise repeated construction can lead to socket exhaustion.
  • Must decide policy order and test its observable behaviour.

Should

  • Should emit metrics for attempts, retries, timeouts, open circuits and final failures.
  • Should include dependency and operation context in logs without logging secrets.
  • Should use idempotency keys or another safe design before retrying a POST.
  • Should keep policy configuration close to the dependency contract and review it as traffic changes.

Don’t

  • Don’t retry 400-level validation errors by default.
  • Don’t retry forever or use a fixed immediate retry for every failure.
  • Don’t catch every exception and call it transient.
  • Don’t create a new HttpClient for each request.
  • Don’t assume a circuit breaker removes the need for an alert; an open circuit is an operational event.

Wrap up

In this article, we have looked at Polly 5.x retry, timeout and circuit breaker policies, transient result handling, Policy.WrapAsync, shared HttpClient and the idempotency concern for POST operations.

I really appreciate that you took the time to read this article.

I hope this article provided you some insights into building resilient HTTP calls. In the next article, I will walk you through secure coding basics using the OWASP Top 10 (2017) for .NET developers.

Related Posts