HttpClientFactory: Managing HTTP Connections and Resilience :👈 👉:Multi Tenant Architecture

Building Resilient ASP.NET Core Applications Using Polly

Building Resilient ASP.NET Core Applications Using Polly

1. What is Polly?

Polly is a .NET resilience library that helps applications handle temporary failures when communicating with external services, databases, APIs, and other dependencies.

It provides resilience strategies such as:

  • Retry
  • Circuit Breaker
  • Timeout
  • Fallback
  • Rate Limiting
  • Concurrency Limiting

Polly is especially useful in distributed systems and microservices, where network failures and temporary service unavailability are normal possibilities.

Important: Modern Polly uses a resilience-pipeline model. ASP.NET Core applications commonly integrate it through Microsoft.Extensions.Http.Resilience for outgoing HTTP requests.

2. Why Do We Need Resilience?

Consider an e-commerce application that communicates with multiple services:

       E-Commerce API
              |
      +-------+-------+
      |       |       |
      v       v       v
   Product  Payment  Shipping
    API      API      API

Suppose the Payment API becomes temporarily unavailable.

Without resilience:

  • Requests may fail immediately.
  • Users may receive unnecessary errors.
  • Repeated requests may overload the failing service.
  • Failures can spread to other services.

With resilience:

  • Temporary failures can be retried safely.
  • Timeouts prevent requests from waiting indefinitely.
  • Circuit breakers stop repeatedly calling unhealthy services.
  • Fallbacks can provide an alternative response when appropriate.

3. Polly Architecture

ASP.NET Core Application Business Service HttpClient / HttpClientFactory Polly Resilience Pipeline Retry Timeout Circuit Breaker Fallback External API / Microservice

Polly executes resilience strategies around an operation. Depending on the configured strategy, it may retry an operation, stop waiting, or reject a call temporarily.

4. Install Polly Packages

For modern .NET applications, install the required packages.

dotnet add package Polly
dotnet add package Polly.Extensions

For HttpClientFactory integration, use:

dotnet add package Microsoft.Extensions.Http.Resilience

Note: The HTTP resilience package provides a convenient integration with Polly-based resilience pipelines. You do not need to manually construct every Polly strategy for common HTTP scenarios.

5. Retry Pattern

Retry means attempting an operation again when a temporary failure occurs.

Example:

  • Application sends a request to an external API.
  • The API temporarily returns HTTP 503.
  • The client waits for a configured delay.
  • The client retries the request.
  • If the retry succeeds, the application receives the response.
Send HTTP Request External API Request successful? Yes Return Response No Retry available? Yes Wait and Retry Retry request No Return Failure

Implementing Retry Using Polly

Example using the modern Polly resilience pipeline API:

using Polly;
using Polly.Retry;
var retryPipeline =
    new ResiliencePipelineBuilder<string>()
        .AddRetry(new RetryStrategyOptions<string>
        {
            MaxRetryAttempts = 3,
            Delay = TimeSpan.FromSeconds(2),
            BackoffType = DelayBackoffType.Exponential,
            UseJitter = true
        })
        .Build();
var result = await retryPipeline.ExecuteAsync(
    async cancellationToken =>
    {
        Console.WriteLine("Calling external service");
        // Replace with a real operation.
        return await CallExternalServiceAsync(
            cancellationToken);
    },
    cancellationToken);

Explanation:

  • MaxRetryAttempts: Maximum retry attempts after the initial execution.
  • Delay: Initial delay between retries.
  • BackoffType.Exponential: Increases the delay between attempts.
  • UseJitter: Adds random variation to retry delays.
  • Build(): Creates the resilience pipeline.
  • ExecuteAsync(): Executes the operation through the pipeline.

Important: Configure which exceptions and results should trigger retries. Do not retry every exception or every HTTP response.

6. Exponential Backoff

Exponential backoff increases the waiting time between retry attempts.

Retry Delay Progression Initial 0 sec Retry 1 ~1 sec Retry 2 ~2 sec Retry 3 ~4 sec Jitter adds random variation to the actual delays.

For example, with an initial delay of one second:

Attempt Approximate delay before attempt
Initial request 0 seconds
Retry 1 1 second
Retry 2 2 seconds
Retry 3 4 seconds

Actual delays can vary when jitter is enabled.

Why use jitter?

When many application instances fail at the same time, they might otherwise retry simultaneously. Jitter spreads out retry attempts and reduces sudden traffic spikes.

7. Circuit Breaker Pattern

Circuit Breaker prevents an application from continuously calling a service that is failing.

It has three states:

  • Closed: Requests are allowed and failures are monitored.
  • Open: Requests are rejected temporarily without calling the downstream service.
  • Half-open: A limited number of test requests are allowed to check whether the service has recovered.
CLOSED Requests allowed OPEN Requests blocked HALF-OPEN Test requests allowed Failure threshold Break duration ends Failure Successful test requests: return to Closed Circuit Breaker State Transitions

Implementing Circuit Breaker

using Polly;
using Polly.CircuitBreaker;
var circuitPipeline =
    new ResiliencePipelineBuilder<string>()
        .AddCircuitBreaker(
            new CircuitBreakerStrategyOptions
            {
                FailureRatio = 0.5,
                MinimumThroughput = 10,
                SamplingDuration =
                    TimeSpan.FromSeconds(30),
                BreakDuration =
                    TimeSpan.FromSeconds(15)
            })
        .Build();
try
{
    var result = await circuitPipeline.ExecuteAsync(
        async cancellationToken =>
        {
            return await CallExternalServiceAsync(
                cancellationToken);
        },
        cancellationToken);
}
catch (BrokenCircuitException)
{
    Console.WriteLine(
        "External service is temporarily unavailable.");
}

Configuration explanation:

  • FailureRatio = 0.5: A 50% failure ratio can trigger the breaker when other conditions are met.
  • MinimumThroughput = 10: At least 10 executions are needed in the sampling window before evaluating the ratio.
  • SamplingDuration: Period used to calculate the failure ratio.
  • BreakDuration: How long the circuit remains open.

These are example values. A circuit breaker only reacts to failures that its configured failure predicate considers relevant.

8. Timeout Strategy

Timeout limits how long an application waits for an operation to complete.

For example, if an external API does not respond within five seconds, the operation can be cancelled by the timeout strategy.

using Polly;
using Polly.Timeout;
var timeoutPipeline =
    new ResiliencePipelineBuilder<string>()
        .AddTimeout(TimeSpan.FromSeconds(5))
        .Build();
try
{
    var result = await timeoutPipeline.ExecuteAsync(
        async cancellationToken =>
        {
            return await CallExternalServiceAsync(
                cancellationToken);
        },
        cancellationToken);
}
catch (TimeoutRejectedException)
{
    Console.WriteLine("Operation timed out.");
}

Important: The operation must observe the cancellation token for cancellation to stop its underlying work. A timeout does not guarantee that a remote server has stopped processing the request.

9. Fallback Strategy

Fallback provides an alternative result when the original operation cannot produce a successful result.

Example: If a product recommendation service is unavailable, the application can show a predefined popular-products response.

using Polly;
using Polly.Fallback;
var fallbackPipeline =
    new ResiliencePipelineBuilder<string>()
        .AddFallback(new FallbackStrategyOptions<string>
        {
            ShouldHandle = args =>
                ValueTask.FromResult(
                    args.Outcome.Exception != null),
            FallbackAction = args =>
                Outcome.FromResultAsValueTask(
                    "Fallback response: Popular products")
        })
        .Build();
var result = await fallbackPipeline.ExecuteAsync(
    cancellationToken =>
        CallExternalServiceAsync(cancellationToken),
    cancellationToken);

Use fallback when:

  • A cached or default result is acceptable.
  • A non-critical feature can be temporarily degraded.
  • The application can provide a meaningful alternative response.

Do not return fake success for critical operations such as payment processing or order confirmation.

10. Rate Limiting Strategy

Rate limiting controls the number of operations allowed during a period.

It can protect downstream services from excessive outgoing traffic.

using Polly;
using Polly.RateLimiting;
var rateLimitPipeline =
    new ResiliencePipelineBuilder()
        .AddRateLimiter(
            new SlidingWindowRateLimiter(
                new SlidingWindowRateLimiterOptions
                {
                    PermitLimit = 100,
                    Window = TimeSpan.FromMinutes(1),
                    SegmentsPerWindow = 4,
                    QueueLimit = 0
                }))
        .Build();

This example limits the pipeline to 100 permits per one-minute sliding window. The limit applies to this limiter instance, not automatically to every application instance in a distributed deployment.

11. Combining Multiple Resilience Strategies

Real applications usually combine multiple resilience strategies.

For example:

HTTP Request
     |
     v
  Timeout
     |
     v
Circuit Breaker
     |
     v
   Retry
     |
     v
External API

The order of strategies matters. It determines whether a timeout applies to each attempt or to the entire operation, and which failures are observed by the circuit breaker.

Do not combine strategies without understanding their execution order and total time budget.

12. Using Polly with HttpClientFactory

In ASP.NET Core, the recommended approach for common outgoing HTTP resilience scenarios is to use Microsoft.Extensions.Http.Resilience.

Step 1: Install the package

dotnet add package Microsoft.Extensions.Http.Resilience

Step 2: Configure HttpClient

builder.Services
    .AddHttpClient<ProductApiClient>(client =>
    {
        client.BaseAddress =
            new Uri("https://products.example.com/");
        client.Timeout = Timeout.InfiniteTimeSpan;
    })
    .AddStandardResilienceHandler();

Here, the standard resilience handler manages the total and per-attempt timeout strategies. Setting HttpClient.Timeout to infinite avoids introducing an additional, competing timeout outside that pipeline.

Step 3: Create a typed client

public class ProductApiClient
{
    private readonly HttpClient _httpClient;
    public ProductApiClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
    public async Task<List<Product>?> GetProductsAsync(
        CancellationToken cancellationToken)
    {
        return await _httpClient.GetFromJsonAsync<List<Product>>(
            "api/products",
            cancellationToken);
    }
}
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Step 4: Use the client in a controller

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    private readonly ProductApiClient _client;
    public ProductsController(ProductApiClient client)
    {
        _client = client;
    }
    [HttpGet]
    public async Task<IActionResult> Get(
        CancellationToken cancellationToken)
    {
        var products = await _client.GetProductsAsync(
            cancellationToken);
        return Ok(products);
    }
}

The standard handler configures a set of resilience strategies. Review its defaults and customize them according to the downstream API's behavior and your application's requirements.

13. Customizing HTTP Resilience

You can customize the standard resilience handler.

builder.Services
    .AddHttpClient("InventoryApi", client =>
    {
        client.BaseAddress =
            new Uri("https://inventory.example.com/");
        client.Timeout = Timeout.InfiniteTimeSpan;
    })
    .AddStandardResilienceHandler(options =>
    {
        options.TotalRequestTimeout.Timeout =
            TimeSpan.FromSeconds(20);
        options.AttemptTimeout.Timeout =
            TimeSpan.FromSeconds(5);
        options.Retry.MaxRetryAttempts = 2;
        options.CircuitBreaker.FailureRatio = 0.5;
        options.CircuitBreaker.MinimumThroughput = 10;
        options.CircuitBreaker.SamplingDuration =
            TimeSpan.FromSeconds(30);
        options.CircuitBreaker.BreakDuration =
            TimeSpan.FromSeconds(15);
    });

Remember:

  • Total timeout includes the complete execution and retry delays.
  • Attempt timeout limits an individual attempt.
  • Retry attempts should be limited.
  • Circuit-breaker thresholds should reflect real traffic patterns.

14. Handling HTTP Status Codes Correctly

Not every HTTP error should be retried.

Status code Meaning Typical handling
400 Bad Request Fix the request; normally do not retry.
401 Unauthorized Check authentication and credentials.
403 Forbidden Check permissions; normally do not retry.
404 Not Found Check the resource; normally do not retry.
408 Request Timeout May be transient; retry only when safe.
429 Too Many Requests Respect Retry-After and service limits.
500 Internal Server Error Retry only when considered transient and safe.
502 Bad Gateway May be transient.
503 Service Unavailable May be transient; consider Retry-After.
504 Gateway Timeout May be transient; retry only when safe.

HTTP status code alone does not always tell you whether an operation is safe to retry. Consider the operation's semantics and whether the server may already have processed it.

15. Idempotency and Retry Safety

Idempotency means that repeating an operation produces the same intended effect as performing it once.

For example:

  • GET requests are generally safe to retry.
  • PUT requests are generally designed to be idempotent.
  • DELETE requests are generally idempotent in their intended effect.
  • POST requests are not automatically idempotent.

Imagine a payment request:

  1. The application sends a payment request.
  2. The payment provider processes the payment.
  3. The response is lost due to a network failure.
  4. The application assumes the payment failed and retries.

This could cause duplicate processing if the payment provider does not support deduplication.

Solution: Use an idempotency key supported by the payment provider, and verify the operation's status before attempting an unsafe retry.

16. Polly in Microservices Architecture

API Gateway Order Service Inventory API Downstream service Payment API Downstream service Shipping API Downstream service Polly Pipeline Retry + Timeout + Breaker Polly Pipeline Safe retries + Timeout Polly Pipeline Retry + Fallback Each downstream integration has its own resilience configuration.

Each service integration can have its own resilience configuration.

For example:

  • Inventory calls may use short timeouts.
  • Payment calls may require strict idempotency and carefully controlled retries.
  • Recommendation calls may use cached fallback results.
  • Shipping calls may use a circuit breaker to prevent repeated failures.

17. Polly Best Practices

  • Use bounded retries instead of unlimited retries.
  • Use exponential backoff and jitter where appropriate.
  • Set realistic timeout values.
  • Use circuit breakers for dependencies that can remain unhealthy.
  • Do not retry permanent failures such as validation errors.
  • Use idempotency protection for operations that may cause duplicate effects.
  • Propagate CancellationToken through the entire operation.
  • Use fallback only when an alternative response is valid.
  • Monitor retries, timeouts, and circuit-breaker events.
  • Avoid stacking multiple retry policies without calculating the total number of attempts.
  • Consider an overall request deadline across all downstream calls.
  • Test failure scenarios, not just successful responses.

18. Common Mistakes

Mistake Why it is a problem Better approach
Unlimited retries Can overload a failing service. Use bounded retries.
Retrying every exception Permanent failures will not recover through retries. Retry only transient failures.
Retrying payment POST blindly May cause duplicate transactions. Use idempotency keys and safe retry rules.
No timeout Requests may wait too long. Configure operation deadlines.
Very short circuit-breaker duration May repeatedly call an unhealthy service. Choose a suitable break duration.
Fallback with fake success Can hide important business failures. Return only valid alternative results.
Ignoring cancellation Unnecessary work continues. Pass CancellationToken.

19. Polly vs Microsoft.Extensions.Http.Resilience

Polly Microsoft.Extensions.Http.Resilience
Provides general-purpose resilience pipelines. Integrates resilience with HttpClientFactory.
Can be used for HTTP and non-HTTP operations. Designed for outgoing HTTP communication.
Allows custom strategy composition. Provides standard HTTP resilience configuration.
Useful for application-specific operations. Useful for external API and microservice calls.

20. Interview Questions and Answers

Q1. What is Polly?

Polly is a .NET resilience library that provides strategies such as retry, circuit breaker, timeout, fallback, and rate limiting.

Q2. Why do we need Polly?

It helps applications handle transient failures and improves reliability when communicating with external services.

Q3. What is the Retry pattern?

It attempts an operation again after an eligible temporary failure.

Q4. What is exponential backoff?

It increases the delay between successive retry attempts.

Q5. What is jitter?

Jitter adds random variation to retry delays to prevent many clients from retrying simultaneously.

Q6. What is Circuit Breaker?

It temporarily blocks requests to an unhealthy dependency to prevent repeated failures.

Q7. Explain the three Circuit Breaker states.

Closed allows requests, Open blocks requests, and Half-open allows limited test requests to check recovery.

Q8. What is the difference between Retry and Circuit Breaker?

Retry attempts an operation again. Circuit Breaker stops calls temporarily when a dependency is failing.

Q9. What is a Timeout strategy?

It limits the time allowed for an operation to complete.

Q10. What is Fallback?

It provides an alternative result when the original operation fails in a way covered by the fallback policy.

Q11. What is idempotency?

It means repeating an operation has the same intended effect as performing it once.

Q12. Can we retry POST requests?

Only when the operation is safe to repeat, such as when the server supports idempotency keys or reliable deduplication.

Q13. What is Microsoft.Extensions.Http.Resilience?

It integrates Polly-based resilience strategies with HttpClientFactory.

Q14. Can Polly be used outside HTTP calls?

Yes. Polly pipelines can protect database-related operations, messaging integrations, and other application operations when the chosen strategy is appropriate.

Q15. How do you test resilience?

Simulate timeouts, transient errors, repeated failures, rate limits, and service recovery. Verify retry counts, circuit-breaker behavior, fallback results, and cancellation.

21. Final Summary

  • Polly: .NET resilience library.
  • Retry: Attempts an operation again after eligible failures.
  • Exponential Backoff: Increases retry delays.
  • Jitter: Randomizes delays to reduce synchronized retries.
  • Circuit Breaker: Temporarily blocks calls to failing services.
  • Timeout: Limits operation duration.
  • Fallback: Provides a valid alternative result.
  • Rate Limiting: Controls the number of permitted operations.
  • Idempotency: Helps make retries safe for operations that may otherwise create duplicate effects.
  • HttpClientFactory Integration: Use Microsoft.Extensions.Http.Resilience for outgoing HTTP calls.
🔙
HttpClientFactory: Managing HTTP Connections and Resilience :👈 👉:Multi Tenant Architecture