How do you make a .NET API resilient to a slow or failing third-party service using timeouts, retries, and circuit breakers?
Zomato · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, Microservices, Software Engineering
Community answers
Posted by wasAsked editorial collection
Give every remote call a timeout and cancellation token. Retry only transient failures and only when the operation is safe or protected by an idempotency key; use exponential backoff with jitter. A circuit breaker limits pressure during sustained failure.
Example:
builder.Services.AddHttpClient<PaymentClient>()
.AddStandardResilienceHandler();
Validate the actual handler policy for your .NET version: separate attempt and total timeouts, bounded retries, and sensible breaker thresholds. Limit concurrency, verify TLS, keep credentials in a secret store, and log correlation IDs without sensitive payloads. Model ambiguous outcomes explicitly—if a payment call times out, query by idempotency key before charging again. Provide degraded behavior only when it is truthful and safe.
Backbencher Developer · · 0 likes
Third-party calls fail in two ways: slowly or noisily. Resilience means limiting the damage of both.
Timeouts
- Never wait indefinitely. Set a per-attempt timeout (for example 2 seconds) and an overall timeout for the whole operation including retries.
- Pass the request's CancellationToken so abandoned requests stop.
Retries
- Retry only transient failures: network errors, 408, 429, 5xx. Never retry 400 or 401.
- Use exponential backoff with jitter (200 ms, 400 ms, 800 ms plus randomness) to avoid synchronised retry storms.
- Only retry idempotent operations, or send an idempotency key so the provider ignores duplicates.
- Respect Retry-After headers.
Circuit breaker
- After a threshold of failures (for example 50% failures over 30 seconds with a minimum number of calls), the circuit opens and calls fail immediately for a cooldown period.
- After the break, a few trial calls test recovery (half-open state) before closing the circuit again.
- This protects your threads and the struggling provider.
Implementation in .NET 8+ with Microsoft.Extensions.Http.Resilience (built on Polly v8):
builder.Services.AddHttpClient<PaymentGatewayClient>(c => c.BaseAddress = new Uri(baseUrl))
.AddStandardResilienceHandler(o =>
{
o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);
o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(10);
o.Retry.MaxRetryAttempts = 3;
o.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30);
});
Other patterns:
- Bulkhead / concurrency limiter: cap concurrent calls to the provider so it cannot consume all resources.
- Fallbacks: serve cached data, a default value or a degraded feature ("shipping estimate unavailable").
- Asynchronous processing: move non-urgent calls to a queue so the user request does not depend on the provider at all.
- Hedging for latency-sensitive reads with multiple endpoints.
Observability: log and measure every attempt, timeout and circuit state change, and alert on open circuits. Test the behaviour with fault injection (Polly's chaos strategies or a stub that returns errors and delays).