No matter how solid a service's own code is, the moment it makes an HTTP call to another service it inherits every problem of that service and of the network in between. The other side slows down, refuses connections for a few seconds during a redeploy, returns 503 under load, or never answers at all. These are not exceptions; they are the normal state of a distributed system.
An HttpClient left on its defaults is not prepared for this: a single slow dependency leaves requests hanging for a long time and eventually clogs the calling service as well. In this post I cover how I put limits around outbound calls with IHttpClientFactory and the Microsoft.Extensions.Http.Resilience package: a timeout budget, safe retries, a circuit breaker, and how failures surface to the caller.
Creating HttpClient correctly: IHttpClientFactory and typed clients
The first step comes before resilience: how HttpClient instances are created. Creating and disposing a new HttpClient() on every call exhausts sockets under load. Using a single static instance forever means connections are never refreshed and DNS changes go unnoticed.
IHttpClientFactory balances these two extremes: it pools the underlying message handlers and recycles them at regular intervals. A typed client built on top of it gathers everything about one external service into a single class:
public sealed class CatalogClient(HttpClient http)
{
public async Task<ProductDto?> GetProductAsync(Guid id, CancellationToken ct)
{
using var response = await http.GetAsync($"products/{id}", ct);
if (response.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<ProductDto>(ct);
}
}
The address, headers and resilience settings are supplied once at registration; calling code only sees CatalogClient. There is one thing to watch: a typed client is designed to be short-lived. If you inject it into a singleton service and hold on to it, the same HttpClient and handler live for the lifetime of the process, and the factory's recycling mechanism is bypassed.
Timeouts: separate limits per attempt and in total
HttpClient.Timeout defaults to 100 seconds. For an API that is expected to answer a user in under a second, that is effectively unlimited. A dependency that slows down does not fail, it just makes you wait; every waiting request consumes a connection, memory and, most of the time, a user's patience.
You need to think about two separate limits. The per-attempt timeout defines how long a single HTTP request may take. The total timeout defines the longest the caller will wait, including retries and the delays between them. That second value is a budget, and it should be derived from the caller's own deadline: if your endpoint has to respond in two seconds, there is no point in giving the inner call a total of thirty.
Then there is the cancellation token. Passing the incoming request's CancellationToken all the way to the outbound call avoids wasted work when the client disconnects. A timeout and a cancellation are different things and should show up differently in logs; one tells you the dependency is slow, the other that the user gave up.
Retries: what, how many times, at what interval
Retrying is an effective way to hide transient failures, and a harmful one when misused. There are three decisions to make.
What to retry: connection failures, attempts that timed out, and 408, 429 and 5xx responses can be transient. 400, 401, 404 or 422 will give the same result when the same request is repeated; retrying them only adds latency.
How many times: few. Two or three attempts are enough to cover short interruptions. More than that puts load on a service that is already struggling. In layered systems the effect multiplies: if each of three layers retries three times, the service at the bottom receives a large number of calls for a single user request. That is why it matters to keep retries in a single layer wherever possible.
At what interval: exponential backoff with random jitter on top. A fixed interval makes every client that failed at the same moment retry at the same moment; the other side takes a new wave just as it is recovering. If the server sends a Retry-After header, following it is better than guessing.
Requests with side effects: do not blindly retry a POST
Repeating a GET request is safe. The same cannot be said for a POST. When a payment request times out, there are two possibilities: the request never reached the server, or it did, was processed, and the response was lost on the way back. The client cannot tell these apart. Retrying blindly means performing the operation twice in the second case.
There are two ways out. The first is not to retry requests with side effects at all and leave the failure to the caller. The second is to make the request idempotent: the client generates a key for each logical operation and sends it in a header, and when the server sees the same key a second time it returns the first result instead of repeating the operation. This second approach requires support from the other service; where that support is missing, the default should be not to retry.
Circuit breaker: stop leaning on a service that is down
If a dependency is in trouble not for a few seconds but for minutes, having every request wait for its timeout and then retry hurts both sides. The calling service slows down, and the troubled service keeps receiving load while it is trying to recover.
A circuit breaker tracks the failure ratio over a recent time window. When the ratio crosses a threshold, the circuit opens and, for a set duration, calls fail immediately without being sent to the other side at all. When that duration ends the circuit moves to a half-open state and lets a few trial requests through; if they succeed it closes, otherwise it opens again.
There is also a minimum throughput threshold. At low traffic, one failure out of two requests is a fifty percent failure ratio but not enough evidence to open the circuit. What to do while the circuit is open is a product decision: show the last cached value, temporarily hide the feature, or return an explicit error.
Configuring the standard resilience pipeline
The Microsoft.Extensions.Http.Resilience package offers these strategies as a ready-made pipeline. AddStandardResilienceHandler sets up the following order from the outside in: a concurrency limiter, a total timeout, retry, a circuit breaker and a per-attempt timeout. The defaults are general purpose: 10 seconds per attempt, 30 seconds in total, and three retries with exponential backoff. For a user-facing API they need to be tightened:
builder.Services
.AddHttpClient<CatalogClient>(client =>
{
client.BaseAddress = new Uri(builder.Configuration["Catalog:BaseUrl"]!);
})
.AddStandardResilienceHandler(options =>
{
options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);
options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(8);
options.Retry.MaxRetryAttempts = 2;
options.Retry.Delay = TimeSpan.FromMilliseconds(300);
options.Retry.DisableForUnsafeHttpMethods();
options.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30);
options.CircuitBreaker.FailureRatio = 0.5;
options.CircuitBreaker.MinimumThroughput = 20;
options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(15);
});
DisableForUnsafeHttpMethods turns off retries for methods with side effects such as POST, PUT, PATCH and DELETE; it applies the default from the previous section in a single line. The options are validated at startup: for example, the circuit breaker's sampling duration must be at least twice the attempt timeout. An inconsistent configuration fails instead of running silently.
When choosing the values, it helps to do the arithmetic end to end: do three attempts of two seconds each, plus the delays between them, fit into a total budget of eight seconds? If they do not, the last attempt is cut off midway and that attempt is wasted.
How failures surface to the caller: exceptions, observability and tests
A resilience pipeline does not remove failures, it changes their shape. There are three situations calling code can run into. When retries are exhausted the pipeline does not throw, it returns the last failed response; checking the status code is therefore still your job. When the total time runs out, a TimeoutRejectedException is thrown, and while the circuit is open, a BrokenCircuitException. Catching these two inside the typed client and translating them into the language of the domain, for example a single result type meaning "the catalog is currently unavailable", shields the upper layers from Polly details.
On the observability side I want to see at least three things: the number of attempts, calls that timed out, and the circuit's state changes. Because retries hide problems, a rising attempt count while the success rate still looks high is the first sign that a dependency is starting to degrade.
For tests, producing fake responses at the HttpMessageHandler level is enough: with a handler that returns two 503 responses followed by a 200 you can verify that retrying works, and with a handler that never responds you can verify that the timeout kicks in within the expected time. Keeping delays short in tests makes it possible to run these scenarios on every build.
Closing
With outbound service calls the real question is not "will it fail" but "how long do we wait when it fails, and what do we do then". A timeout puts an upper bound on that wait, a retry covers short interruptions without the user noticing, and a circuit breaker protects both sides during long outages. AddStandardResilienceHandler sets these up in a few lines, but the values are determined by your time budget and the behaviour of the other service. Making these three decisions deliberately for each dependency, instead of leaving the defaults as they are, keeps one service's slowdown from spreading through the whole system.