Introduction
Modern .NET applications depend on several resources to complete business operations. An ASP.NET Core application may communicate with external HTTP services, retrieve information from SQL Server, publish messages to a queue, and access distributed caches.
These dependencies do not always work as expected. A database may temporarily reject connections, an external API may return HTTP 503, or a network interruption may prevent an application from receiving a response.
If the application does not handle these failures properly, a temporary problem can become a larger application outage.
For example, consider an order management application that performs the following operations:
Retrieves product information from SQL Server.
Checks inventory through an external HTTP API.
Creates an order in the database.
Sends a confirmation request to a notification service.
If SQL Server temporarily becomes unavailable, the application may fail to create the order. If the inventory service responds slowly, the API request may take longer than expected. If the notification service is unavailable, the application may fail to complete an operation that is not necessarily required before returning a response to the customer.
Developers can handle these situations using resilience techniques such as retries, timeouts, circuit breakers, concurrency limits, and fallbacks.
.NET provides resilience libraries that allow developers to combine these techniques into reusable execution pipelines. Instead of writing separate retry and timeout logic for every database and HTTP operation, developers can define a pipeline and execute operations through it.
In this article, we will understand resilience pipelines, explore the available strategies, configure pipelines in a .NET application, and apply them to database and HTTP operations. We will also discuss transaction safety, duplicate operations, cancellation, logging, monitoring, and common mistakes.
What Is a Resilience Pipeline?
A resilience pipeline is a collection of strategies that control how an application executes an operation when something goes wrong.
For example, suppose an application needs to retrieve customer information from a database. The database connection may fail temporarily because of a network interruption.
Without resilience handling, the operation may fail immediately.
With a resilience pipeline, the application can retry the operation a limited number of times. If the operation continues failing, the pipeline can stop waiting after a configured timeout and return the failure to the calling code.
A pipeline can contain multiple strategies, and each strategy handles a different aspect of failure management.
Consider this simplified execution flow:
Application Request
|
v
Resilience Pipeline
|
+-------+-------+
| |
v v
Retry Timeout
| |
+-------+-------+
|
v
Circuit Breaker
|
v
Database / API
|
v
Operation ResultThe actual execution order depends on how the strategies are added to the pipeline. Each strategy wraps the strategies configured inside it, so configuration order matters.
A pipeline can be designed for a specific dependency or operation. For example, an application may use one pipeline for SQL Server read operations, another for database writes, and a separate pipeline for external HTTP services.
This makes resilience behavior easier to understand, configure, and maintain.
Understanding Resilience Strategies
Before implementing pipelines, let's understand the main strategies available in .NET.
Retry
Retry means executing an operation again when it fails because of a condition that may be temporary.
For example, an application sends a request to a Customer API, but the service returns HTTP 503 Service Unavailable. If the failure is temporary, the application may wait briefly and try again.
A retry strategy should define the maximum number of attempts, the delay between attempts, and the failures that are eligible for another attempt.
Retries are useful for temporary connection failures, selected HTTP server errors, and certain transient database errors.
However, retrying every failure is not a good practice. If a database query fails because a table does not exist, repeating the query will not fix the problem.
Retrying a payment or order creation operation without duplicate protection can also create additional business operations.
Timeout
A timeout defines how long an operation is allowed to run.
For example, an application may allow a database query to run for three seconds. If the query takes longer, the timeout strategy can cancel the operation and report a timeout failure.
Timeouts help prevent operations from waiting indefinitely.
However, a timeout does not guarantee that the underlying database or remote service immediately stops processing. Cancellation is cooperative, and the remote system may already have received or started executing the operation.
A timeout should therefore be combined with appropriate cancellation handling and safe operation design.
Circuit Breaker
A circuit breaker prevents an application from repeatedly calling a dependency that is continuously failing.
It generally has three states:
Closed: Requests are allowed to reach the dependency normally.
Open: Requests are temporarily blocked 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, suppose an external payment service has been unavailable for several minutes. Without a circuit breaker, every incoming request may continue calling it and waiting for a timeout.
The circuit breaker detects repeated failures and temporarily stops sending requests.
This protects the calling application from repeatedly spending resources on operations that are unlikely to succeed.
Rate Limiting and Concurrency Limiting
Rate limiting controls how frequently operations can be executed.
Concurrency limiting controls how many operations can run at the same time.
These strategies are related, but they solve different problems.
For example, an application may allow a maximum of 100 requests per second to a downstream API. This is a rate limit.
The same application may allow only 20 requests to execute concurrently against SQL Server. This is a concurrency limit.
Concurrency limiting is particularly useful when a dependency has limited capacity. It prevents an application from sending more simultaneous requests than the dependency can reasonably handle.
Fallback
Fallback provides an alternative response when the primary operation fails.
For example, if a Product API becomes unavailable, an application may return previously cached product information.
Fallback behavior must follow business requirements. Returning cached product descriptions may be acceptable, but returning outdated payment or inventory information may cause incorrect decisions.
A fallback should not hide a failure by returning information that appears to be current when it is not.
Hedging
Hedging sends additional requests when an operation takes longer than expected, usually to another endpoint or replica.
For example, an application may send a request to one read replica and, after a configured delay, send another request to a different replica if the first one has not completed.
The application can use the first successful result and cancel the remaining work where possible.
Hedging can reduce latency in certain distributed systems, but it increases traffic and should only be used when duplicate execution is safe.
It is generally more suitable for read operations than for operations that create or update business data.
Why Use Resilience Pipelines in .NET?
Earlier applications often implemented retry logic directly inside service methods.
For example, a developer might write a loop that sends an HTTP request three times, waits between attempts, and handles exceptions.
Another developer might write similar logic for database operations.
Over time, this creates several problems:
Retry behavior becomes inconsistent across services.
Timeout settings are repeated in multiple places.
Exception handling becomes difficult to maintain.
Developers may retry operations that are not safe to repeat.
Monitoring retry behavior becomes more complicated.
Changing resilience settings requires modifying several service implementations.
Resilience pipelines help centralize this behavior.
.NET provides two important packages:
Microsoft.Extensions.Resilience provides general resilience pipeline integration.
Microsoft.Extensions.Http.Resilience provides resilience strategies specifically for HttpClient.
These packages are built on Polly, which provides the underlying resilience strategies.
For new .NET applications, these packages are preferred over the older Microsoft.Extensions.Http.Polly integration.
Step 1. Create a .NET Web API Project
Let's create a sample ASP.NET Core application.
Open a terminal and execute:
dotnet new webapi -n ResiliencePipelineDemoNavigate to the project directory:
cd ResiliencePipelineDemoWe will create two examples:
A database operation that uses a resilience pipeline to handle transient SQL failures.
An HTTP client that uses a resilience pipeline to handle temporary downstream API failures.
The examples will use SQL Server and an external Customer API as dependencies.
Step 2. Install the Required NuGet Packages
Install the general resilience package:
dotnet add package Microsoft.Extensions.ResilienceInstall the HTTP resilience package:
dotnet add package Microsoft.Extensions.Http.ResilienceInstall the SQL Server client package:
dotnet add package Microsoft.Data.SqlClientThe first package provides general resilience pipeline support through dependency injection.
The second package integrates resilience strategies with HttpClientFactory.
The third package provides the SQL Server client used by the database example.
The general resilience package is useful when the operation is not an HTTP request. For example, it can wrap a database query, a cache operation, or another asynchronous operation.
The HTTP resilience package provides HTTP-specific options, including handling HTTP response status codes and configuring standard HTTP resilience strategies.
Step 3. Create a General Resilience Pipeline
Let's begin with a pipeline that can be reused by database operations.
Open Program.cs and register a pipeline using AddResiliencePipeline.
using Polly;
using Polly.Retry;
using Polly.Timeout;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResiliencePipeline(
"database-read",
pipeline =>
{
pipeline.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
Delay = TimeSpan.FromMilliseconds(500),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
ShouldHandle = new PredicateBuilder()
.Handle<TimeoutRejectedException>()
});
pipeline.AddTimeout(
TimeSpan.FromSeconds(3));
});
var app = builder.Build();
app.Run();The AddResiliencePipeline method registers a pipeline with the name database-read.
The pipeline contains two strategies: retry and timeout.
The retry strategy allows up to three additional attempts when the configured failure condition occurs. In this example, it handles TimeoutRejectedException.
The Delay property defines the initial delay between retry attempts. BackoffType uses exponential backoff, which increases the delay between attempts.
UseJitter adds variation to the delay so that multiple application instances do not necessarily retry at exactly the same time.
The timeout strategy limits the duration of an individual execution attempt in this configuration.
The order is important. The retry strategy is added first, so it wraps the timeout strategy. Each retry attempt is therefore subject to the timeout.
This example demonstrates the pipeline structure. A production database pipeline should also identify the actual transient database exceptions that are safe to retry. We will add that handling in the database example.
Step 4. Retrieve and Execute a Resilience Pipeline
Registering a pipeline does not execute it automatically.
The application must retrieve the pipeline and execute the required operation through it.
.NET provides ResiliencePipelineProvider to retrieve a registered pipeline by its name.
For example:
using Polly.Registry;
public class CustomerService
{
private readonly ResiliencePipeline pipeline;
public CustomerService(
ResiliencePipelineProvider<string> provider)
{
pipeline = provider.GetPipeline("database-read");
}
public async Task<string> GetCustomerAsync(
CancellationToken cancellationToken)
{
return await pipeline.ExecuteAsync(
async token =>
{
await Task.Delay(
200,
token);
return "Customer information retrieved.";
},
cancellationToken);
}
}The constructor receives ResiliencePipelineProvider through dependency injection.
It then retrieves the database-read pipeline.
The GetCustomerAsync method executes its operation through ExecuteAsync.
The delegate contains the work that may fail. In this example, Task.Delay represents an asynchronous operation.
The cancellation token passed to the delegate comes from the pipeline execution. It should be passed to underlying operations so they can respond to timeout or cancellation requests.
When an eligible failure occurs, the pipeline applies the configured strategies.
This separation is useful because the service focuses on its business operation while the pipeline manages the configured resilience behavior.
Step 5. Apply a Resilience Pipeline to SQL Server Operations
Database operations can fail for several reasons.
A SQL Server connection may be interrupted, the server may temporarily become unavailable, or a failover operation may interrupt an active connection.
Some of these failures are temporary and can be retried.
However, not every SqlException represents a transient failure. For example, an invalid SQL statement, a missing table, or a permission problem is unlikely to be fixed by retrying.
Microsoft.Data.SqlClient provides the IsTransient property on SqlException, which can help identify errors considered transient by the provider.
Let's create a database service that uses a resilience pipeline.
First, register a database pipeline:
using Microsoft.Data.SqlClient;
using Polly;
using Polly.Retry;
using Polly.Timeout;
builder.Services.AddResiliencePipeline(
"sql-read",
pipeline =>
{
pipeline.AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
Delay = TimeSpan.FromMilliseconds(500),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
ShouldHandle = new PredicateBuilder()
.Handle<SqlException>(
exception => exception.IsTransient)
.Handle<TimeoutRejectedException>()
});
pipeline.AddTimeout(
TimeSpan.FromSeconds(5));
});The pipeline retries SQL exceptions that the SQL client identifies as transient.
It also handles timeout failures generated by the resilience pipeline.
The timeout strategy limits each execution attempt to five seconds. Because the retry strategy wraps the timeout strategy, an operation can receive multiple attempts, each with its own timeout.
The total time spent on retries can therefore be longer than five seconds. If the complete database operation needs a strict overall deadline, configure an additional outer timeout or enforce a deadline at the calling layer.
Now create a service that executes a database query through this pipeline.
using Microsoft.Data.SqlClient;
using Polly;
using Polly.Registry;
public class CustomerRepository
{
private readonly string connectionString;
private readonly ResiliencePipeline pipeline;
public CustomerRepository(
IConfiguration configuration,
ResiliencePipelineProvider<string> provider)
{
connectionString =
configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException(
"Database connection string is missing.");
pipeline = provider.GetPipeline("sql-read");
}
public async Task<string?> GetCustomerNameAsync(
int customerId,
CancellationToken cancellationToken)
{
return await pipeline.ExecuteAsync(
async token =>
{
await using var connection =
new SqlConnection(connectionString);
await connection.OpenAsync(token);
await using var command =
new SqlCommand(
"""
SELECT Name
FROM Customers
WHERE CustomerId = @CustomerId
""",
connection);
command.Parameters.AddWithValue(
"@CustomerId",
customerId);
var result = await command.ExecuteScalarAsync(
token);
return result?.ToString();
},
cancellationToken);
}
}Let's understand how this implementation works.
The constructor receives the database connection string from application configuration and retrieves the sql-read pipeline.
When GetCustomerNameAsync is called, the database operation is executed through the pipeline.
A new SqlConnection is created inside the execution delegate for each attempt. This is important because a connection involved in a failed operation should not automatically be reused for the next attempt.
The connection is opened asynchronously, and the SQL command is executed with the cancellation token provided by the pipeline.
If a transient SQL exception occurs, the retry strategy can execute the delegate again.
The connection is disposed at the end of each attempt because it is declared using await using. This helps ensure that database resources are released even when an operation fails.
The query uses a parameter for customerId rather than inserting the value directly into the SQL statement. This protects the query from SQL injection and allows the database provider to handle the parameter correctly.
For a real application, register CustomerRepository with dependency injection and add the connection string to configuration.
builder.Services.AddScoped<CustomerRepository>();Example configuration:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=CustomerDb;Trusted_Connection=True;TrustServerCertificate=True;"
}
}Use an appropriate authentication method and secure connection settings for production. Do not store production database credentials in source-controlled configuration files.
Step 6. Understand Why Database Writes Need Extra Care
Retrying database reads and writes requires different considerations.
Join the conversation! Your thoughts help the community grow.