Stop Ignoring API Failures: Handle Them Properly with Polly
From the publisher’s feed, collected in the ZeroLabs newsroom.
Credit: My project images used in this complete articleWhen you build a microservices or distributed application, you quickly learn one thing: not every API call is going to succeed.Sometimes a downstream API is temporarily unavailable. Sometimes a database takes longer than expected. Sometimes the network connection drops for a few seconds.These failures are normal in distributed systems. The problem isn’t that an API failed. The real problem is what your application does after the failure.If every failed request immediately becomes a 500 internal server error, your users are going to feel every small problem in the system.This is where resilience patterns become useful.In this article, I’ll walk through how I use Polly in .NET to handle common API failures using retries, timeouts, circuit breakers, and fallback strategies. I’ll also show how the frontend can apply a similar approach with React and Axios.The goal isn’t to make failures disappear. The goal is to make the application handle failures gracefully.What Do We Mean by Resilience?Before looking at Polly, it’s worth understanding what we’re actually trying to solve. In a distributed application, your service usually depends on other services.For example: React Application | v ASP.NET Core API | +----> User Service | +----> Payment Service | +----> Notification Service | +----> DatabaseIf one of these dependencies becomes unavailable, your entire application doesn’t necessarily need to fail. A resilient application can decide what to do depending on the type of failure.For example:Retry a temporary failure.Stop calling a service that is consistently failing.Give slow operations a reasonable timeout.Return cached or default data when appropriate.Tell the user that a particular feature is temporarily unavailable instead of crashing the entire page.That’s the difference between simply handling exceptions and designing for failure.Polly v7 vs. Polly v8If you’ve worked with Polly before, you may have seen the older policy-based API.Polly v7 commonly used individual policies such as:PolicyPolicyWrapRetryPolicyTimeoutPolicyCircuitBreakerPolicyPolly v8 introduced a different approach based around Resilience Pipelines.Instead of thinking about each policy as a completely separate object, you can build a pipeline containing several resilience strategies.Conceptually: HTTP Request | v Resilience Pipeline | +--> Retry | +--> Circuit Breaker | +--> Timeout | +--> Fallback | v External APIThis makes it easier to see the complete resilience strategy for a particular operation.For new .NET applications, the modern Polly APIs and the Microsoft.Extensions.Http.Resilience integration are generally the better starting point.The Four Strategies I Use MostPolly provides several resilience strategies. Four of the most useful when working with HTTP APIs are:RetryCircuit BreakerTimeoutFallbackLet’s look at each one.1. RetryA retry is useful when you believe a failure is temporary. Imagine your API calls another service and receives:503 Service UnavailableThe service might recover a moment later. Instead of immediately returning the failure to the user, your application can wait briefly and try again.For example:Request => X 503 => Wait => Retry => X 503 => Wait => Retry => ✓ SuccessThe important part is not to retry everything.A 400 Bad request usually isn’t going to become successful simply because you tried it again.The same applies to many 401, 403 and validation errors.Retries are mainly useful for failures that are likely to be temporary.Optimization:2. Circuit BreakerRetries are useful, but there is a problem. What happens if the downstream service is completely down?If you keep retrying every request, you’re simply creating more traffic against a service that is already struggling. That’s where the circuit breaker comes in.A circuit breaker has three main states:i. Closed:Everything is working normally and Requests are allowed through.ii. Open:The failure rate has reached the configured threshold. The circuit opens and subsequent requests fail fast instead of repeatedly calling the unhealthy service.iii. Half-Open:After the configured break duration, Polly allows requests through again to check whether the dependency has recovered.If the dependency is healthy, the circuit closes. If it fails again, the circuit opens again.This can protect both your application and the downstream service from unnecessary traffic.3. TimeoutNot every failure is an exception. Sometimes the external API simply doesn’t respond. Without a sensible timeout, a request can sit around waiting much longer than your application can reasonably tolerate.A timeout gives the operation a defined limit.For example:Start API request | | |---- 1 second | |---- 2 seconds | |---- 3 seconds | X TimeoutIf your application can only reasonably wait three seconds, there is little value in keeping the request alive for another 30 seconds.One important point here:A timeout doesn’t magically stop every piece of work in the system.Your underlying operations should also respect cancellation tokens so that cancellation can propagate correctly.4. FallbackSometimes retrying isn’t the right answer. Suppose your application displays product recommendations. The recommendation service is temporarily unavailable.Does the entire page need to fail? Probably not.You might have:cached recommendationsdefault recommendationspreviously stored dataor a simplified responseThat’s where a fallback can be useful.Instead of:Recommendation API | X Failure | v500 Internal Server ErrorYou could have:Recommendation API | X Failure | vCached/Default DataThe important thing is that fallback data should make sense for the particular business operation.You shouldn’t return fake success responses just to hide an outage.Setting Up Polly in an ASP.NET Core APIFor HTTP resilience in a modern ASP.NET Core application, you can use the Microsoft resilience integration package:dotnet add package Microsoft.Extensions.Http.ResilienceOnce the package is installed, we can configure resilience for an HttpClient.Creating a Resilience PipelineHere’s a simplified example of configuring an HTTP client with retry, circuit breaker, and timeout strategies:using System.Net;using Polly;using Polly.CircuitBreaker;using Polly.Retry;var builder = WebApplication.CreateBuilder(args);builder.Services .AddHttpClient("ExternalApiClient") .AddResilienceHandler("ExternalApiPipeline", pipelineBuilder => { pipelineBuilder.AddRetry( new RetryStrategyOptions { MaxRetryAttempts = 3, Delay = TimeSpan.FromSeconds(1), BackoffType = DelayBackoffType.Exponential, UseJitter = true,ShouldHandle = new PredicateBuilder() .Handle() .HandleResult(response => response.StatusCode == HttpStatusCode.ServiceUnavailable) }); pipelineBuilder.AddCircuitBreaker( new CircuitBreakerStrategyOptions { FailureRatio = 0.5, SamplingDuration = TimeSpan.FromSeconds(10), MinimumThroughput = 8, BreakDuration = TimeSpan.FromSeconds(30), ShouldHandle = new PredicateBuilder() .Handle() .HandleResult(response => response.StatusCode == HttpStatusCode.ServiceUnavailable) }); pipelineBuilder.AddTimeout(TimeSpan.FromSeconds(3)); });var app = builder.Build();app.Run();The exact failure conditions should depend on the API you’re calling.For example, you might decide that 503 Service Unavailable should be retried, 400 Bad Request while should immediately be returned to the caller.Why Use Exponential Backoff?Suppose an external service is temporarily unavailable. If 1,000 clients all retry after exactly two seconds, you can end up with another large burst of traffic at the same time.That’s not particularly helpful. Instead, exponential backoff increases the delay between attempts.A simplified example might look like:Attempt 1 → immediateAttempt 2 → wait ~1 secondAttempt 3 → wait ~2 secondsAttempt 4 → wait ~4 secondsAdding jitter introduces some randomness to those delays. So instead of thousands of clients retrying at exactly the same moment, their retries are spread out.That’s one reason this setting is useful:UseJitter = trueBut remember: more retries don’t automatically mean more resilience. Too many retries can actually make an outage worse.Don’t Retry Every ErrorThis is one of the easiest mistakes to make when implementing retry logic.Consider:400 Bad Request401 Unauthorized403 Forbidden404 Not FoundRetrying these requests usually doesn’t solve the underlying problem.For example, if your request contains an invalid parameter, sending the same invalid parameter three more times doesn’t help.The same principle applies to authentication problems. A better approach is to classify failures before deciding whether to retry them.A simple rule of thumb is:Transient problem? | Yes | RetryPermanent/client problem? | Yes | Return the errorThe actual rules should be based on the behavior and contract of the dependency you’re calling.What About the Frontend?Resilience shouldn’t necessarily stop at the backend. Your React application also depends on network connectivity and backend availability.For example, a user might be connected through an unreliable mobile network. You can configure Axios with a timeout and use axios-retry for selected retry scenarios.First, install the package:npm install axios axios-retryThen create a reusable Axios client:import axios from "axios";import axiosRetry from "axios-retry";const apiClient = axios.create({ baseURL: "https://api.example.com/v1", timeout: 5000});axiosRetry(apiClient, { retries: 3, retryDelay: (retryCount) => { return retryCount * 1500; }, retryCondition: (error) => { return ( axiosRetry.isNetworkOrIdempotentRequestError(error) || error.response?.status === 503 ); }, onRetry: (retryCount, error) => { console.warn( `Retrying request. Attempt ${retryCount}: ${error.message}` ); }});export default apiClient;Now the frontend has its own basic retry behavior. But there is an important detail here too:Don’t blindly retry every frontend request.Retries are safer for operations that can be repeated without causing unwanted side effects.For example, retrying a GET request is usually very different from automatically retrying a payment operation.Backend and Frontend Should Work TogetherIt’s tempting to add retries everywhere and call the application resilient.That’s not how it works.Imagine this:React | | Retry 3 times vBackend | | Retry 3 times vExternal APIA single user request could potentially result in many downstream attempts. That’s why resilience needs to be designed across the whole request path.A better architecture might look like:React | | Limited client retry vASP.NET Core API | | Polly resilience pipeline vExternal ServiceEach layer should have a clear responsibility. The frontend should focus on the user experience.The backend should protect its dependencies and control server-side behavior.A Practical Resilience Cheat SheetWhen deciding which strategy to use, I normally think about the problem first rather than starting with the Polly feature.This is much more useful than simply adding every available strategy to every API call.Common Mistakes to Avoid1. Retrying Too MuchThree retries can be reasonable.Thirty retries probably aren’t.Every retry consumes resources and increases latency.2. Retrying Permanent ErrorsDon’t retry because you can.Retry because there is a reasonable chance the operation will succeed shortly.3. Forgetting JitterIf many clients follow exactly the same retry schedule, they can all retry together.Jitter helps spread those retries out.4. Ignoring CancellationIf an operation has been cancelled or timed out, downstream work should ideally be able to observe that cancellation.Pass Cancellation Token through your asynchronous operations where appropriate.For example:await service.GetDataAsync(cancellationToken);This becomes especially important when your application has multiple layers of asynchronous work.Using Fallback as a Way to Hide Every ErrorFallback isn’t a replacement for proper error handling.If your payment service fails, returning:{ "status": "success"}would be dangerous. Fallback makes sense only when the alternative response is actually valid for the business scenario.Resilience Is About Making Better DecisionsPolly isn’t going to prevent your APIs from failing. That’s not really its job.The value comes from deciding what your application should do when something goes wrong.A useful resilience strategy might look like this:API Request | v Timeout | v Retry | v Circuit Breaker | v External API | +-----------+-----------+ | | Success Failure | | v v Response FallbackThe exact order and combination should be chosen based on your application’s requirements rather than copying a generic pipeline.Some useful strategies:Final ThoughtsAPI failures are part of building distributed applications. The goal isn’t to pretend they won’t happen. The goal is to make sure one failing dependency doesn’t unnecessarily bring down everything around it.Polly gives .NET developers a practical way to implement common resilience strategies such as:RetryCircuit BreakerTimeoutFallbackWhen these strategies are configured carefully, your application can become much more tolerant of temporary failures and slow dependencies.But resilience isn’t about adding as many policies as possible. It’s about asking a simple question for every dependency:What should my application do when this service doesn’t behave as expected?That’s where good resilience design starts.Source CodeI’ve also created a repository containing the example project and supporting material:GitHub:https://github.com/Shiv-Darshan-Singh/PollyEnterpriseUnderstandingThe repository also contains the presentation material referenced in this article.PollyIf you’re already using Polly in a production application, I’d be interested to hear what strategies you’ve found most useful, and which ones caused unexpected problems.Share your experience in the comments.Stop Ignoring API Failures: Handle Them Properly with Polly was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.