Introduction
In the previous lessons, we covered service-to-service HTTP communication, API contracts, error handling, and reliable messaging. However, an available service does not guarantee that every request will succeed. Network latency, short connection failures, overloaded containers, restarting processes, and temporary HTTP 5xx responses are normal possibilities in a distributed system.
In this lesson, we make HTTP calls from the Order service to the Catalog and Inventory services more resilient. We will use the Microsoft.Extensions.Http.Resilience package together with the Aspire Service Defaults approach. The goal is not to retry every failure automatically. Instead, we will distinguish transient failures from permanent failures and design behavior that is controlled, observable, and consistent with business rules.
Resilience does not mean that failures disappear. It means that the system behaves predictably when expected failures occur.
Resilience strategies
Timeout
A timeout limits how long a call may wait. In a distributed system, an HTTP request that waits indefinitely can consume connections and resources and eventually create a cascading failure. It is useful to define both a per-attempt timeout and a total request timeout that includes retries.
The standard HTTP resilience handler provides both types of protection. A slow dependency cannot hold an Order request forever.
Retry
Retry sends a request again after a transient failure. It can help with a short network interruption, an HTTP 503 response, or temporary throttling. Exponential backoff and jitter prevent many clients that failed at the same time from retrying in a synchronized burst.
Automatic retry must be limited to safe or idempotent operations. If a POST creates an order, the first request may have succeeded even though its response was lost. Retrying without an idempotency key can create a duplicate order.
Circuit breaker
A circuit breaker temporarily stops calls when a dependency fails repeatedly. While the circuit is open, new calls fail quickly instead of adding more load to the unhealthy service. After a break duration, a limited test request is allowed. If it succeeds, the circuit closes; if it fails, the circuit remains open.
Fallback
Fallback produces a controlled alternative result when the primary call fails. For example, Catalog data may be served from a cache when the Catalog service is unavailable. For Inventory, returning “stock could not be verified” is safer than incorrectly claiming that an item is available.
Fallback must not silently hide an incident. The response should communicate that the data is stale, approximate, or limited, and telemetry should record that fallback was used.
Adding the standard HTTP resilience pipeline
Add the package to the Order API project:
dotnet add Order.Api package Microsoft.Extensions.Http.ResilienceIf the Aspire solution already uses a Service Defaults project, standard resilience can be enabled centrally for HTTP clients. For example, in ServiceDefaults/Extensions.cs:
using Microsoft.Extensions.Http.Resilience;
public static IHostApplicationBuilder AddServiceDefaults(
this IHostApplicationBuilder builder)
{
builder.Services.AddServiceDiscovery();
builder.Services.ConfigureHttpClientDefaults(http =>
{
http.AddStandardResilienceHandler();
http.AddServiceDiscovery();
});
return builder;
}In the actual project, this method will also contain OpenTelemetry and health check configuration. The important idea is that all services using Service Defaults can share the same default HTTP resilience behavior.
The standard handler combines layers such as rate limiting, total timeout, retry, circuit breaker, and per-attempt timeout. Do not accept defaults blindly. Review them according to the behavior and criticality of each dependency.
Defining a client in the Order service
In this example, the Order service uses a typed client that reaches Catalog through service discovery using the resource name catalog-api:
using System.Net;
using System.Net.Http.Json;
public sealed record ProductSnapshot(
Guid Id,
string Name,
decimal Price,
bool IsActive);
public sealed class CatalogClient(HttpClient httpClient)
{
public async Task<ProductSnapshot?> GetProductAsync(
Guid productId,
CancellationToken cancellationToken)
{
using var response = await httpClient.GetAsync(
$"api/products/{productId}",
cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<ProductSnapshot>(
cancellationToken);
}
}Register the client as follows:
builder.Services.AddHttpClient<CatalogClient>(client =>
{
client.BaseAddress = new Uri("https://catalog-api");
});When Aspire service discovery is enabled, the catalog-api address can resolve to the resource registered in the AppHost. If the standard handler is configured globally, this client automatically passes through the resilience pipeline.
Configuring safe retries and timeouts
A product read is a GET operation, so limited retry is normally reasonable. For a side-effecting POST such as order creation, disabling retry is safer unless the operation has a reliable idempotency design:
builder.Services.AddHttpClient<CatalogClient>(client =>
{
client.BaseAddress = new Uri("https://catalog-api");
})
.AddStandardResilienceHandler(options =>
{
options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(8);
options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);
options.Retry.MaxRetryAttempts = 2;
options.Retry.DisableForUnsafeHttpMethods();
});Here, the total request cannot exceed eight seconds, including two retry attempts. Each individual attempt is limited to two seconds. Lowering these values alone is not enough. Use normal p95 latency, SQL query time, container resources, and network conditions to choose appropriate limits.
Custom pipelines and fallback
The standard handler is a good starting point for most HTTP dependencies. However, Catalog and Inventory may require different behavior. Catalog can serve a cached product snapshot, while Inventory should clearly report that availability could not be verified.
When creating a custom handler, avoid stacking multiple resilience handlers on the same client. Replace the standard handler with one custom pipeline:
using System.Net;
using Microsoft.Extensions.Http.Resilience;
using Polly;
using Polly.CircuitBreaker;
using Polly.Retry;
using Polly.Timeout;
builder.Services.AddHttpClient<CatalogClient>(client =>
{
client.BaseAddress = new Uri("https://catalog-api");
})
.AddResilienceHandler("catalog-read-pipeline", pipeline =>
{
pipeline.AddTimeout(TimeSpan.FromSeconds(2));
pipeline.AddRetry(new HttpRetryStrategyOptions
{
MaxRetryAttempts = 2,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.Handle<HttpRequestException>()
.Handle<TimeoutRejectedException>()
.HandleResult(response =>
response.StatusCode == HttpStatusCode.RequestTimeout ||
response.StatusCode == HttpStatusCode.TooManyRequests ||
(int)response.StatusCode >= 500)
});
pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.5,
MinimumThroughput = 4,
SamplingDuration = TimeSpan.FromSeconds(20),
BreakDuration = TimeSpan.FromSeconds(10)
});
});Pipeline order matters. The order determines which failures timeout, retry, and circuit breaker strategies observe. In low-traffic environments, a very small MinimumThroughput can cause false circuit openings. In high-traffic systems, an excessively large value can delay protection.
The safest fallback example is a read operation whose stale result can be explicitly labeled. The Catalog client can retrieve the last known product snapshot from its cache. Adding an IsStale field makes the situation visible to both the UI and operations team. Do not silently fall back for stock quantities, payment results, or order status unless the business meaning is fully defined.
Classifying failures
| Condition | Recommended behavior | Reason |
|---|---|---|
| HTTP 404 | No retry | The resource is missing; another attempt normally changes nothing. |
| HTTP 429 | Retry with Retry-After | Respect backoff and rate-limit headers. |
| HTTP 503 | Limited retry, then circuit breaker | The dependency may be temporarily unavailable. |
| Timeout | Limited retry | A total time limit is still required. |
| HTTP 400 | No retry | The request or validation is invalid. |
| HTTP 409 | Decide from business rules | It is related to idempotency and concurrency design. |
Observability and testing
Do not test resilience only with successful responses. Every retry, timeout, circuit transition, and fallback should be visible in logs or metrics. Use the Aspire Dashboard to inspect the Order request, the Catalog HTTP client span, and the retry attempts in the same distributed trace.
Your tests should include:
- The first two calls return 503 and the third returns 200.
- Every attempt times out until the total timeout is reached.
- The circuit breaker stops calls after enough failures.
- 404 and 400 responses are not retried unnecessarily.
- A GET request uses a cached fallback.
- A POST order operation does not create a duplicate record.
Common mistakes
- Retrying every request: Side effects can create duplicate data.
- Confusing HttpClient.Timeout with pipeline timeout: Different timeout layers can produce different exception types.
- Choosing very large timeout values: Resources remain occupied too long and failure chains grow.
- Hiding errors with fallback: Approximate data must be marked in the response and telemetry.
- Never testing the circuit breaker: Checking status codes alone does not prove that the circuit opened.
- Adding multiple handlers to one client: Retry counts and total latency can multiply unexpectedly.
Practice exercise
Apply the following exercise to the CatalogClient in the Order service:
- Enable the standard resilience handler through Service Defaults.
- Set the total timeout for Catalog GET requests to six seconds and the per-attempt timeout to two seconds.
- Limit retries to two attempts and use exponential backoff.
- Temporarily stop the Catalog service and inspect the Order logs and Aspire Dashboard traces.
- Verify that a 404 response is not retried.
- Add a cache fallback that returns the last known product snapshot and marks the response as stale.
Conclusion
In this lesson, we added timeout, retry, circuit breaker, and fallback strategies to service-to-service calls. The most important design decision is not to treat every failure in the same way. Temporary network and service failures can use limited retries; permanent contract and validation failures should be returned directly. Circuit breakers protect dependencies, while fallbacks should be limited to business-safe data that can be clearly labeled.
In the next stage, connect these resilience behaviors to OpenTelemetry metrics, distributed traces, and operational alerts so that you can measure whether a policy is actually improving the system.
Sources
- https://learn.microsoft.com/en-us/dotnet/core/resilience/
- https://learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/service-defaults
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.http.resilience.httpstandardresilienceoptions?view=net-10.0-pp