HttpClient and resilience
Calling external APIs safely needs two things: reusing connections (IHttpClientFactory and typed clients, so ports don't run out) and resilience (retry, timeouts, circuit breaker) so temporary upstream failures don't reach users. In .NET this is AddHttpClient plus AddStandardResilienceHandler.
50.1 Why is it used?
- new HttpClient per request leaves sockets in TIME_WAIT; under load ports run out (socket exhaustion, SocketException).
- One static HttpClient forever reuses connections but misses DNS changes.
- IHttpClientFactory pools and rotates handlers: connections are reused and DNS changes are picked up.
- Upstream APIs fail temporarily (503, slow responses); retries and timeouts hide that from the user, a circuit breaker protects a down service.
50.2 The bug: new HttpClient per request
var app = WebApplication.Create(args); app.MapGet("/delivery/{pin}", async (string pin) =>{ using var http = new HttpClient(); return await http.GetStringAsync( $"http://localhost:5150/eta/{pin}");}); app.Run();$ curl -s -o /dev/null \ "localhost:5050/delivery/110001?i=[1-500]"$ netstat -an | grep ":5150" | grep -c TIME_WAIT501 TCP [::1]:61565 [::1]:5150 TIME_WAIT TCP [::1]:61569 [::1]:5150 TIME_WAIT- using + dispose looks clean, but every new HttpClient opens its own connection.
- After dispose the OS keeps the socket in TIME_WAIT for a few minutes: 500 requests = 501 sockets.
- Step 1
1.Request -> new HttpClient -> new connection
- Step 2
2.Dispose: socket stays in TIME_WAIT
- Step 3
3.Load grows: thousands of TIME_WAIT sockets
- Step 4
4.Ports run out -> SocketException
Static client misses DNS changes. Fix: IHttpClientFactory
50.3 Test setup
- A fake courier API runs on port 5150; the shop app runs on 5050. Nothing calls the internet.
- Modes: ok (normal ETA), flaky (2 of 3 requests = 503), slow (5 seconds), down (always 503).
50.4 Typed client: CourierClient
public record Eta(string Pincode, int Days); public class CourierClient(HttpClient http){ public Task<Eta?> GetEtaAsync(string pin) => http.GetFromJsonAsync<Eta>($"eta/{pin}");}- A typed client is a normal class that takes HttpClient in its constructor.
- GetFromJsonAsync<Eta> turns the JSON straight into an Eta record.
- The rest of the code never sees URLs or HTTP details, only CourierClient.
50.5 Fix: AddHttpClient + DI
var builder = WebApplication.CreateBuilder(args);var courierUrl = "http://localhost:5150/"; builder.Services.AddHttpClient<CourierClient>(c => c.BaseAddress = new(courierUrl)); var app = builder.Build(); app.MapGet("/delivery/{pin}", (string pin, CourierClient courier) => courier.GetEtaAsync(pin)); app.Run();$ curl -i localhost:5050/delivery/110001HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{"pincode":"110001","days":2} $ curl -s -o /dev/null \ "localhost:5050/delivery/110001?i=[1-500]"$ netstat -an | grep ":5150" | grep -c TIME_WAIT0 TCP [::1]:64016 [::1]:5150 ESTABLISHED- AddHttpClient<CourierClient> registers the typed client with a BaseAddress.
- The factory keeps handlers in a pool and rotates them after a few minutes.
- After the same 500 requests: 0 TIME_WAIT, one ESTABLISHED connection.
50.6 Problem 2: flaky courier API
$ curl -X POST localhost:5150/mode/flaky$ curl -s -o /dev/null -w "%{http_code}" ... # x3500500200 fail: Microsoft.AspNetCore.Server.Kestrel[13] An unhandled exception was thrown by the application. System.Net.Http.HttpRequestException: Response status code does not indicate success: 503 (Service Unavailable).- In flaky mode the courier returns 503; GetFromJsonAsync throws HttpRequestException and the user gets a 500.
- The failure is temporary: the same call would work a second later.
50.7 Fix: AddStandardResilienceHandler
builder.Services .AddHttpClient<CourierClient>(c => c.BaseAddress = new(courierUrl)) .AddStandardResilienceHandler();$ dotnet add package Microsoft.Extensions.Http.Resilience$ curl -s -w " %{http_code}" ... # x3, mode flaky{"pincode":"110001","days":2} 200{"pincode":"110001","days":2} 200{"pincode":"110001","days":2} 200 warn: Polly[3] Execution attempt. Source: 'CourierClient-standard// Standard-Retry', Result: '503', Handled: 'True', Attempt: '0'warn: Polly[3] ... Result: '503', Handled: 'True', Attempt: '1'info: Polly[3] ... Result: '200', Handled: 'False', Attempt: '2'- Package Microsoft.Extensions.Http.Resilience (built on Polly v8).
- One line: attempts 0 and 1 got 503 and were handled, attempt 2 got 200, so all three user requests return 200.
- Step 1
1.Rate limiter: 1000 concurrent requests
- Step 2
2.Total request timeout: whole call 30s
- Step 3
3.Retry: 3 more tries, exponential backoff + jitter
- Step 4
4.Circuit breaker: 10% failures in a 30s window
- Step 5
5.Attempt timeout: each try 10s
One line builds all five strategies
50.8 Options: tuned for your API
builder.Services .AddHttpClient<CourierClient>(c => c.BaseAddress = new(courierUrl)) .AddStandardResilienceHandler(o => { o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2); o.Retry.MaxRetryAttempts = 2; o.CircuitBreaker.MinimumThroughput = 5; o.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(15); });$ curl -X POST localhost:5150/mode/slow$ curl -i -w "time %{time_total}s" localhost:5050/delivery/110001HTTP/1.1 500 Internal Server Errortime 10.995423sfail: Polly[0] EventName: 'OnTimeout', Source: '...//Standard-AttemptTimeout'Polly.Timeout.TimeoutRejectedException: The operation didn't complete within the allowed timeout of '00:00:02'.- AttemptTimeout 2s, MaxRetryAttempts 2, MinimumThroughput 5 (the default 100 never trips in a demo), BreakDuration 15s.
- Slow mode (5s responses): each attempt is cancelled at 2s with TimeoutRejectedException; 3 attempts plus backoff = about 11s, then 500.
| Strategy | Default | Tuned here |
|---|---|---|
| Total request timeout | 30s | (default) |
| Retry | 3 retries, exponential backoff + jitter | MaxRetryAttempts = 2 |
| Circuit breaker | 10% failure ratio, 30s window, MinimumThroughput 100 | MinimumThroughput = 5, BreakDuration = 15s |
| Attempt timeout | 10s | 2s |
| Rate limiter | 1000 concurrent | (default) |
50.9 Checkpoint: courier down
$ curl -X POST localhost:5150/mode/down1: 500 5.842865s courier hits: 32: 500 5.177276s courier hits: 53: 500 0.035248s courier hits: 54: 500 0.018036s courier hits: 5EventName: 'OnCircuitOpened', Result: '503'Polly.CircuitBreaker.BrokenCircuitException: The circuit is now open and is not allowing calls.- Requests 1 and 2 make 5 failed courier hits in total, so the circuit opens (OnCircuitOpened).
- Requests 3 and 4 fail in about 35 ms with BrokenCircuitException; courier hits stay at 5.
- Failing fast saves your threads and gives the down service no extra load.
- Step 1
1.Closed: calls go through, failures are counted
- Step 2
2.Failure ratio crosses the limit (min throughput reached)
- Step 3
3.Open: calls fail immediately (BrokenCircuitException) for BreakDuration
- Step 4
4.Half-open: one trial call
- Step 5
5.Success -> Closed, failure -> Open again
50.10 Common mistakes
- Retrying POST blindly: if the gateway took the payment but the response timed out, the retry charges the customer twice. Use Retry.DisableForUnsafeHttpMethods() unless the API supports an idempotency key.
- Myth: HttpClient is IDisposable, so using it every time is correct. That is exactly what causes socket exhaustion.
- Injecting a typed client into a singleton: its handler never rotates (DNS changes missed).
- Old code uses Microsoft.Extensions.Http.Polly with AddPolicyHandler (Polly v7); new code uses the standard resilience handler.
// Wrong: POST retried -> risk of a double chargebuilder.Services .AddHttpClient<PaymentClient>(c => c.BaseAddress = new(paymentUrl)) .AddStandardResilienceHandler();// POST /pay -> 503 (after a timeout)// retry: the same payment is POSTed again // Right: only safe methods retriedbuilder.Services .AddHttpClient<PaymentClient>(c => c.BaseAddress = new(paymentUrl)) .AddStandardResilienceHandler(o => o.Retry.DisableForUnsafeHttpMethods());// GET: retried// POST, PUT, DELETE: not retried50.11 HttpClient rules
- Never new HttpClient yourself: AddHttpClient + typed client.
- Add the standard resilience handler to every outgoing client.
- Tune timeouts to your upstream API.
- Retry off for POST and other unsafe methods (unless idempotency key).
- No typed client inside a singleton.
50.12 Interview tips
- A new HttpClient per request causes socket exhaustion (TIME_WAIT); a static one misses DNS changes.
- I register a typed client with IHttpClientFactory, which pools and rotates handlers.
- AddStandardResilienceHandler adds rate limiter, total timeout, retry with backoff + jitter, circuit breaker and attempt timeout.
- I disable retries for non-idempotent POST calls and tune the timeouts to the upstream service.