Modern .NET applications frequently communicate with external services through HTTP APIs. An ASP.NET Core application may call payment gateways, authentication services, cloud APIs, inventory systems, or other microservices. These services can become temporarily unavailable, respond slowly, return server errors, or reject requests when they receive too much traffic.
If an application does not handle these failures properly, a temporary problem in one dependency can affect the entire system. Requests may remain pending, application threads and connections may stay occupied, and repeated calls can increase the load on an already unhealthy service.
.NET provides resilience pipelines to handle these situations. With the Microsoft.Extensions.Http.Resilience package, developers can configure retry, timeout, circuit breaker, and rate-limiting strategies for HttpClient without implementing every mechanism manually.
These capabilities are built on Polly, a popular .NET resilience library. The standard HTTP resilience handler provides a ready-to-use combination of strategies, while custom pipelines allow developers to control the behavior of individual HTTP clients.
This article explains how resilience pipelines work, how to configure them in ASP.NET Core, how to customize retry and timeout behavior, and how to apply production-oriented practices when communicating with external APIs.
What Are Resilience Pipelines in .NET?
A resilience pipeline is a sequence of strategies that controls how an operation behaves when failures or delays occur.
For an HTTP request, a pipeline can decide whether to retry a failed operation, stop waiting after a timeout, temporarily block requests to an unhealthy service, or limit the number of concurrent requests.
The main purpose is to prevent temporary failures from becoming larger application problems.
For example, consider an e-commerce application that calls an external payment API. The payment service may return HTTP 503 because it is temporarily unavailable. Instead of immediately failing every order, the application can retry the request when the failure is likely to be temporary.
However, retrying every failed request is not always safe. If the payment service already processed a payment but the response was lost, sending the same payment request again could charge the customer twice. Resilience strategies must therefore be configured according to the operation's behavior.
Microsoft.Extensions.Http.Resilience
The Microsoft.Extensions.Http.Resilience package provides resilience capabilities specifically for HttpClient.
Install it using the .NET CLI:
dotnet add package Microsoft.Extensions.Http.Resilience
The package integrates with IHttpClientFactory, which manages the creation and configuration of HTTP clients.
It provides several useful extension methods:
Extension method | Purpose |
|---|
AddStandardResilienceHandler()
| Adds a predefined combination of HTTP resilience strategies |
AddStandardHedgingHandler()
| Adds a standard hedging pipeline for requests that may be sent to alternative endpoints |
AddResilienceHandler()
| Allows developers to create a custom HTTP resilience pipeline |
For most applications, the standard resilience handler is a good starting point. Use a custom pipeline when the default behavior does not match the requirements of a particular dependency.
Understand the Main Resilience Strategies
Before configuring a pipeline, understand what each strategy does and when it should be used.
Retry
Retry attempts an operation again when it encounters a failure considered temporary.
For example, an external API may return HTTP 503 because its service is temporarily unavailable. A retry strategy can wait for a short period and send the request again.
A retry strategy normally includes:
Exponential backoff increases the waiting period between attempts. Jitter introduces randomness into the delay so that many application instances do not retry at exactly the same time.
Retry is useful for transient network failures and temporary server-side problems. It should not be used blindly for operations that may produce duplicate side effects.
Circuit breaker
A circuit breaker prevents an application from repeatedly calling a dependency that is already experiencing problems.
It has three main states:
Closed: Requests are allowed to reach the dependency.
Open: Requests are blocked temporarily because the failure threshold has been reached.
Half-open: A limited number of requests are allowed to check whether the dependency has recovered.
For example, if a payment service repeatedly returns server errors, the circuit breaker can temporarily stop requests to that service.
This prevents the application from wasting resources on requests that are unlikely to succeed.
The circuit breaker is especially useful when an application depends on multiple external services. A problem in one dependency should not consume all the resources required by the rest of the application.
Timeout
A timeout limits how long an operation can run.
There are two important timeout concepts in the standard HTTP resilience handler:
Total request timeout: Limits the entire operation, including retry attempts.
Attempt timeout: Limits the duration of an individual request attempt.
For example, suppose an application allows a total of 30 seconds for an HTTP operation and permits multiple attempts. The total timeout prevents the combined operation from continuing indefinitely.
An attempt timeout ensures that one individual request does not consume the entire available time.
Timeouts are important because an external service may accept a request but take too long to respond.
Rate limiter
The rate limiter controls how many concurrent requests can be sent to a dependency.
For example, an application may receive thousands of incoming requests while an external API allows only a limited number of concurrent operations.
A rate limiter can restrict the number of requests sent to that dependency.
The standard HTTP resilience handler uses a concurrency limiter with a default permit limit of 1,000 and no queue. This is a concurrency limit, not a general requests-per-second quota.
Hedging
Hedging sends additional requests when the original request takes longer than expected. It is useful when an application has multiple equivalent endpoints and can route requests to another healthy endpoint.
Unlike ordinary retries, hedging can execute requests in parallel.
For example, a service may have multiple regional read endpoints. If one endpoint is slow, the application can send another request to a different endpoint and use the first successful response.
Hedging can improve response times, but it also increases traffic. It should only be used when the dependency supports the required routing and duplicate-request behavior.
Configure the Standard HTTP Resilience Handler
The standard resilience handler combines multiple strategies into one pipeline.
Create an ASP.NET Core application and configure an HTTP client in Program.cs.
using Microsoft.Extensions.Http.Resilience;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddHttpClient("PaymentApi", client =>
{
client.BaseAddress =
new Uri("https://api.example.com/");
client.Timeout = Timeout.InfiniteTimeSpan;
})
.AddStandardResilienceHandler();
var app = builder.Build();
app.MapGet("/", () => "Resilience pipeline configured.");
app.Run();
The important part is:
.AddStandardResilienceHandler();
This adds the standard HTTP resilience pipeline to the named client.
The example sets HttpClient.Timeout to infinite because the resilience handler manages the request timeout. Keeping both timeout mechanisms active can create confusing timeout behavior.
Understand the default configuration
The standard resilience handler applies five strategies in a specific order.
Order | Strategy | Default configuration |
|---|
1 | Rate limiter | 1,000 concurrent requests, no queue |
2 | Total request timeout | 30 seconds |
3 | Retry | 3 retries with exponential backoff and jitter |
4 | Circuit breaker | 10% failure ratio, minimum throughput of 100 |
5 | Attempt timeout | 10 seconds |
The circuit breaker also uses a 30-second sampling duration and a 5-second break duration by default.
These values are starting defaults, not universal production recommendations. A payment API, internal microservice, and public read-only API may require very different timeout and concurrency limits.
The order matters because each strategy wraps the strategies inside it. The total timeout includes the retry operation, while the attempt timeout applies to an individual attempt.
Customize Retry and Timeout Settings
The standard handler allows developers to customize individual strategies.
For example, an application may need a shorter total timeout and a smaller number of retry attempts when calling a low-latency internal service.
using Microsoft.Extensions.Http.Resilience;
builder.Services
.AddHttpClient("InventoryApi", client =>
{
client.BaseAddress =
new Uri("https://inventory.example.com/");
client.Timeout = Timeout.InfiniteTimeSpan;
})
.AddStandardResilienceHandler(options =>
{
options.Retry.MaxRetryAttempts = 2;
options.Retry.Delay =
TimeSpan.FromMilliseconds(500);
options.Retry.BackoffType =
DelayBackoffType.Exponential;
options.Retry.UseJitter = true;
options.TotalRequestTimeout.Timeout =
TimeSpan.FromSeconds(15);
options.AttemptTimeout.Timeout =
TimeSpan.FromSeconds(5);
options.CircuitBreaker.FailureRatio = 0.2;
options.CircuitBreaker.MinimumThroughput = 20;
options.CircuitBreaker.BreakDuration =
TimeSpan.FromSeconds(10);
});
This configuration makes several changes:
The client performs at most two retries.
The initial retry delay is 500 milliseconds.
Exponential backoff increases the delay between subsequent attempts.
Jitter reduces synchronized retries.
The complete operation cannot exceed 15 seconds.
Each attempt is limited to five seconds.
The circuit breaker opens when the configured failure threshold is reached, subject to its sampling and throughput requirements.
Remember that MaxRetryAttempts means the number of retries after the original attempt. A setting of two means the request can be attempted up to three times in total.
Choose timeout values based on the actual dependency's response characteristics. Setting an extremely short timeout can cause healthy requests to fail unnecessarily.
Prevent Unsafe HTTP Requests From Being Retried
One of the most important production considerations is retrying HTTP methods that produce side effects.
The standard HTTP resilience handler retries all HTTP methods by default. This can be dangerous for operations such as POST, PATCH, PUT, and DELETE when the server may have processed the request before the client received an error.
Consider this example:
await client.PostAsJsonAsync(
"payments",
paymentRequest);
The payment service may successfully process the payment, but the response may be lost because of a network failure.
If the client retries the request, the payment may be processed again.
To avoid automatic retries for unsafe methods, configure the standard handler:
builder.Services
.AddHttpClient("PaymentApi")
.AddStandardResilienceHandler(options =>
{
options.Retry.DisableForUnsafeHttpMethods();
});
This disables retries for POST, PATCH, PUT, DELETE, and CONNECT.
You can also disable retries for selected methods:
builder.Services
.AddHttpClient("PaymentApi")
.AddStandardResilienceHandler(options =>
{
options.Retry.DisableFor(
HttpMethod.Post,
HttpMethod.Delete);
});
Disabling retries is not the only way to make an operation safe. For APIs that support idempotency keys, a client can send the same key for repeated attempts so the server can recognize duplicate operations.
For example:
var request = new HttpRequestMessage(
HttpMethod.Post,
"payments");
request.Headers.Add(
"Idempotency-Key",
Guid.NewGuid().ToString());
request.Content = JsonContent.Create(paymentRequest);
using var response = await client.SendAsync(request);
In a real implementation, generate and persist the idempotency key for the logical payment operation. Do not generate a new key for every retry, because the server would treat each key as a separate operation.
Only retry a side-effecting operation when the API's idempotency contract makes that behavior safe.
Configure a Circuit Breaker for an External API
A circuit breaker is useful when a dependency repeatedly fails.
The standard handler already includes a circuit breaker, but its behavior can be customized.
builder.Services
.AddHttpClient("CustomerApi")
.AddStandardResilienceHandler(options =>
{
options.CircuitBreaker.FailureRatio = 0.25;
options.CircuitBreaker.MinimumThroughput = 20;
options.CircuitBreaker.SamplingDuration =
TimeSpan.FromSeconds(30);
options.CircuitBreaker.BreakDuration =
TimeSpan.FromSeconds(15);
});
This configuration uses a 25% failure ratio and requires at least 20 requests during the sampling period before the circuit breaker can evaluate the failure ratio.
The circuit breaker is not intended to detect a single failed request. It evaluates failures over a period of time.
For example, if an API receives 100 requests during the sampling window and 30 fail, the failure ratio is 30%. If the configured threshold is 25% and the minimum throughput condition is satisfied, the circuit breaker can open.
When the circuit is open, requests are rejected without calling the unhealthy dependency. After the break duration, the circuit enters the half-open state and allows requests to test recovery.
Avoid setting an extremely low minimum throughput for high-volume systems without understanding the impact. Similarly, a low-volume service may never reach the minimum throughput required to evaluate the circuit breaker.
Create a Custom Resilience Pipeline
The standard handler is convenient, but some applications need more control.
For example, a service may need a custom retry count, a specific circuit-breaker threshold, or a different timeout configuration.
Use AddResilienceHandler to define the strategies manually.
using Microsoft.Extensions.Http.Resilience;
using Polly;
builder.Services
.AddHttpClient("CustomApi")
.AddResilienceHandler(
"CustomApiPipeline",
pipeline =>
{
pipeline.AddRetry(
new HttpRetryStrategyOptions
{
MaxRetryAttempts = 3,
Delay = TimeSpan.FromSeconds(1),
BackoffType =
DelayBackoffType.Exponential,
UseJitter = true
});
pipeline.AddCircuitBreaker(
new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.2,
MinimumThroughput = 10,
SamplingDuration =
TimeSpan.FromSeconds(30),
BreakDuration =
TimeSpan.FromSeconds(10)
});
pipeline.AddTimeout(
new HttpTimeoutStrategyOptions
{
Timeout = TimeSpan.FromSeconds(5)
});
});
This example creates a custom pipeline with retry, circuit-breaker, and timeout strategies.
Unlike the standard handler, this custom configuration does not automatically include the standard rate limiter and total-request timeout arrangement. Add the strategies required by the application and carefully consider their order.
Also review the default predicates used by the HTTP-specific retry and circuit-breaker options. If your dependency uses additional transient status codes or custom failure conditions, configure the predicates accordingly.
Avoid adding a standard handler and a custom handler to the same client without a clear reason. Stacking multiple resilience handlers can produce unexpected retries, repeated timeouts, and excessive request amplification.
Handle Timeout and Circuit-Breaker Exceptions
Resilience strategies can produce exceptions when an operation cannot continue.
For example, the timeout strategy can throw TimeoutRejectedException. A circuit breaker can reject an operation with BrokenCircuitException.
A service should handle these conditions according to its business requirements.
using Polly.CircuitBreaker;
using Polly.Timeout;
public class CustomerService
{
private readonly HttpClient _client;
private readonly ILogger<CustomerService> _logger;
public CustomerService(
HttpClient client,
ILogger<CustomerService> logger)
{
_client = client;
_logger = logger;
}
public async Task<string?> GetCustomerAsync(
int customerId,
CancellationToken cancellationToken)
{
try
{
return await _client.GetStringAsync(
$"customers/{customerId}",
cancellationToken);
}
catch (TimeoutRejectedException ex)
{
_logger.LogWarning(
ex,
"Customer API request timed out.");
return null;
}
catch (BrokenCircuitException ex)
{
_logger.LogWarning(
ex,
"Customer API circuit is open.");
return null;
}
catch (HttpRequestException ex)
{
_logger.LogError(
ex,
"Customer API request failed.");
return null;
}
}
}
This example demonstrates exception handling, but returning null is only appropriate if the calling application understands what it means.
For a production API, you may need to return a service-unavailable response, use a cached result, or propagate a domain-specific failure.
Do not catch every exception and silently return a default value. That can hide programming errors and make production problems difficult to diagnose.
Also distinguish between a resilience timeout and cancellation requested by the caller. A user cancelling an operation should not automatically be treated as an external service failure.
Configure Resilience Options Through appsettings.json
Keeping resilience settings in code is simple, but production applications often need different values for development, staging, and production.
The standard handler supports configuration through an IConfiguration section.
First, add a configuration section to appsettings.json:
{
"CustomerApi": {
"Resilience": {
"RateLimiter": {
"PermitLimit": 100,
"QueueLimit": 0
},
"TotalRequestTimeout": {
"Timeout": "00:00:20"
},
"Retry": {
"MaxRetryAttempts": 2,
"Delay": "00:00:01",
"BackoffType": "Exponential",
"UseJitter": true
},
"CircuitBreaker": {
"FailureRatio": 0.2,
"MinimumThroughput": 20,
"SamplingDuration": "00:00:30",
"BreakDuration": "00:00:10"
},
"AttemptTimeout": {
"Timeout": "00:00:05"
}
}
}
}
Then register the client:
builder.Services
.AddHttpClient("CustomerApi", client =>
{
client.BaseAddress =
new Uri("https://customers.example.com/");
client.Timeout = Timeout.InfiniteTimeSpan;
})
.AddStandardResilienceHandler()
.Configure(
builder.Configuration.GetSection(
"CustomerApi:Resilience"));
This approach separates application behavior from environment-specific configuration.
The values shown are examples. Validate the configuration against the options supported by the installed package version, and avoid exposing configuration values that could make a dependency vulnerable to excessive traffic.
Use Named and Typed HTTP Clients
A common mistake is configuring one global resilience policy for every external dependency.
Different services have different response times, traffic limits, and failure characteristics. A payment provider may need strict timeout and retry rules, while an internal catalog service may support a higher concurrency limit.
Use named or typed HTTP clients to apply different policies.
Named HTTP client
builder.Services
.AddHttpClient("PaymentApi")
.AddStandardResilienceHandler(options =>
{
options.Retry.DisableForUnsafeHttpMethods();
options.TotalRequestTimeout.Timeout =
TimeSpan.FromSeconds(20);
});
builder.Services
.AddHttpClient("CatalogApi")
.AddStandardResilienceHandler(options =>
{
options.Retry.MaxRetryAttempts = 3;
options.TotalRequestTimeout.Timeout =
TimeSpan.FromSeconds(10);
});
A named client is useful when a service needs to access several external APIs or when clients are created by name through IHttpClientFactory.
Typed HTTP client
A typed client provides a dedicated class for a specific dependency.
public class CatalogClient
{
private readonly HttpClient _httpClient;
public CatalogClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public Task<Product?> GetProductAsync(
int productId,
CancellationToken cancellationToken)
{
return _httpClient.GetFromJsonAsync<Product>(
$"products/{productId}",
cancellationToken);
}
}
Register the typed client with its own resilience configuration:
builder.Services
.AddHttpClient<CatalogClient>(client =>
{
client.BaseAddress =
new Uri("https://catalog.example.com/");
client.Timeout = Timeout.InfiniteTimeSpan;
})
.AddStandardResilienceHandler(options =>
{
options.Retry.MaxRetryAttempts = 2;
options.TotalRequestTimeout.Timeout =
TimeSpan.FromSeconds(12);
});
This keeps dependency-specific behavior close to the HTTP client that uses it.
Monitor and Diagnose Resilience Pipelines
Configuring a resilience pipeline is only the first step. Production applications should also monitor how frequently each strategy is activated.
Useful metrics and diagnostic information include:
Number of retry attempts.
Number of requests rejected by the circuit breaker.
Timeout frequency.
Rate-limiter rejections.
HTTP response status codes.
Total request duration.
Dependency availability.
Number of successful and failed operations.
The resilience libraries provide diagnostic events and metrics that can be integrated with .NET observability tools.
For example, OpenTelemetry can collect HTTP client metrics and traces. Application monitoring can then show whether a dependency is becoming slower or whether retry activity is increasing.
When investigating a problem, distinguish between an original request failure and a retry attempt. A request that succeeds after two retries is different from a request that fails immediately.
Also avoid logging every retry at Error level. Repeated warnings or informational events are usually more appropriate for transient failures, while final operation failures can be recorded at Error level.
Common Mistakes When Configuring Resilience
Mistake | Why it causes problems | Better approach |
|---|
Retrying every HTTP method | Can duplicate side effects | Disable unsafe retries or use idempotency keys |
Setting very long timeouts | Requests can consume resources for too long | Choose timeouts based on dependency requirements |
Using too many retries | Can increase load during an outage | Use limited retries with exponential backoff and jitter |
Ignoring circuit breakers | Repeated failures can waste resources | Configure a circuit breaker for unstable dependencies |
Stacking multiple resilience handlers | Can multiply retries and timeouts | Use one well-designed pipeline per client |
Using the same policy for every API | Dependencies have different behavior | Configure named or typed clients |
Ignoring cancellation | User cancellation may be treated as a failure | Propagate cancellation tokens correctly |
Not monitoring retries | Dependency degradation can remain hidden | Collect resilience metrics and logs |
Best Practices for Production Applications
Use AddStandardResilienceHandler() as a starting point for ordinary HTTP dependencies.
Configure a separate resilience policy for dependencies with different service-level requirements.
Use exponential backoff and jitter to reduce synchronized retries.
Avoid automatic retries for unsafe HTTP methods unless the API provides idempotency guarantees.
Set both total request and individual attempt timeouts according to the expected response time.
Configure circuit-breaker thresholds based on realistic traffic volume.
Use concurrency limits to protect downstream services.
Propagate cancellation tokens through HTTP operations.
Avoid stacking multiple resilience handlers on the same client.
Monitor retry counts, timeouts, circuit-breaker events, and dependency latency.
Test transient failures, slow responses, and service recovery before deploying.
Keep resilience configuration externalized where different environments need different values.
A resilience pipeline should protect both the application and the external dependency. Aggressive retries may make an outage worse, while excessively strict timeouts may cause healthy operations to fail. Configuration should reflect actual traffic patterns and dependency behavior.
Advantages and Disadvantages of .NET Resilience Pipelines
Advantages | Disadvantages |
|---|
Provides ready-to-use retry and timeout strategies | Incorrect settings can increase latency |
Supports circuit breakers and concurrency limits | Requires understanding dependency behavior |
Integrates with IHttpClientFactory | Additional package dependency |
Supports custom pipelines | Complex configurations need testing |
Reduces repeated resilience code | Does not make unsafe operations automatically idempotent |
Provides telemetry and diagnostic events | Monitoring still needs to be configured |
Supports hedging for suitable endpoints | Hedging can increase network traffic |
Conclusion
Resilience pipelines help .NET applications handle temporary HTTP failures without allowing every dependency problem to become an application-wide failure.
The Microsoft.Extensions.Http.Resilience package provides a practical way to configure retry, timeout, circuit breaker, rate-limiting, and hedging strategies through IHttpClientFactory. Developers can start with the standard handler and customize its behavior according to the needs of each external service.
For production systems, the most important considerations are safe retries, appropriate timeout values, circuit-breaker thresholds, concurrency limits, and monitoring. A well-configured pipeline does not guarantee that an external API will always be available, but it helps an application respond to failures in a controlled and predictable way.
Start with a standard resilience handler, test it against realistic failure scenarios, and introduce custom strategies only when the application's requirements justify them.
Join the conversation! Your thoughts help the community grow.