# The Fallback Pattern With Polly

> Retries and circuit breakers decide how to fail. The fallback decides what the user sees when everything else has failed. A good fallback returns a visibly degraded answer instead of a fake success. Here is how to build fallbacks with Polly v8, where they belong in the pipeline, and what to log when they fire.

Published: 2026-11-26. Author: Milan Jovanović. Topic: Resilience. Tags: design-patterns, dotnet, polly, resilience.

Canonical: https://milanjovanovic.tech/blog/fallback-pattern-polly-dotnet

Retries, timeouts, and circuit breakers all answer the same question: how should this call fail?

The fallback answers a different one: given that it failed, **what does the user get instead?**

That makes it the most product-shaped of the resilience patterns, and the easiest to get wrong.
A good fallback returns a degraded answer the caller can recognize as degraded.
A bad fallback returns a fake success, and nobody notices until someone makes a decision based on data that was never real.

## What a Fallback Is (and Is Not)

A fallback is the last strategy standing.
When retries are exhausted and the [**circuit breaker**](https://milanjovanovic.tech/blog/circuit-breaker-pattern-dotnet) is open, the fallback intercepts the failure and produces a substitute result.

Good substitutes are *honestly degraded*.

- **Stale data from cache.** The recommendation service is down; show the recommendations cached 20 minutes ago.
- **A static default.** Personalization failed; show bestsellers.
- **An explicit empty state.** The reviews service is down; return an empty list plus a flag the UI turns into "reviews are temporarily unavailable".
- **A cheaper computation.** The ML pricing model timed out; use the rule-based price.

Bad substitutes look identical to a real response.
Returning `0` for an account balance is not a fallback, it's misinformation.
Returning "payment succeeded" because the payment API timed out is a bug you'll read about in an incident report.

A useful design test: *could the caller distinguish a fallback response from a real one if they needed to?*
If nothing in the response says "degraded", the caller will treat the substitute as real data.

## Fallback in Polly v8

In [**Polly v8**](https://milanjovanovic.tech/blog/polly-v8-resilience-pipelines), fallback is a strategy for typed pipelines, `ResiliencePipeline<T>`, since it must produce a `T`:

```bash
dotnet add package Polly.Core
```

The pipeline below wraps a recommendations call with a fallback, retry, circuit breaker, and timeout.
Build it once and reuse it (a singleton or a field), because the circuit breaker keeps its state in the pipeline instance.
`logger`, `recommendationClient`, `userId`, and `cancellationToken` come from the surrounding service:

```csharp
using Polly;
using Polly.CircuitBreaker;
using Polly.Fallback;
using Polly.Retry;
using Polly.Timeout;

ResiliencePipeline<Recommendations> pipeline =
    new ResiliencePipelineBuilder<Recommendations>()
        // Fallback first = outermost. It catches what the rest give up on.
        .AddFallback(new FallbackStrategyOptions<Recommendations>
        {
            ShouldHandle = new PredicateBuilder<Recommendations>()
                .Handle<HttpRequestException>()
                .Handle<TimeoutRejectedException>()
                .Handle<BrokenCircuitException>(),
            FallbackAction = args =>
            {
                var fallback = Recommendations.Bestsellers with
                {
                    IsDegraded = true
                };

                return Outcome.FromResultAsValueTask(fallback);
            },
            OnFallback = args =>
            {
                logger.LogWarning(
                    args.Outcome.Exception,
                    "Recommendations fallback served. Cause: {Cause}",
                    args.Outcome.Exception?.GetType().Name);

                return ValueTask.CompletedTask;
            }
        })
        .AddRetry(new RetryStrategyOptions<Recommendations>
        {
            MaxRetryAttempts = 2,
            BackoffType = DelayBackoffType.Exponential,
            UseJitter = true
        })
        .AddCircuitBreaker(new CircuitBreakerStrategyOptions<Recommendations>
        {
            FailureRatio = 0.5,
            MinimumThroughput = 10,
            SamplingDuration = TimeSpan.FromSeconds(30),
            BreakDuration = TimeSpan.FromSeconds(15)
        })
        .AddTimeout(TimeSpan.FromSeconds(2))
        .Build();

var recommendations = await pipeline.ExecuteAsync(
    async ct => await recommendationClient.GetForUserAsync(userId, ct),
    cancellationToken);

public sealed record Recommendations(IReadOnlyList<string> ProductIds)
{
    public bool IsDegraded { get; init; }

    public static Recommendations Bestsellers { get; } =
        new(["sku-101", "sku-202", "sku-303"]);
}
```

Notice the `IsDegraded = true`.
That flag lets the UI render the data *and* the "showing popular items" note.

Notice also what `ShouldHandle` covers: the raw failure (`HttpRequestException`), the pipeline's own give-up signals (`TimeoutRejectedException`), and the breaker's fast-fail (`BrokenCircuitException`).
A fallback that only handles the first one stops working the day the breaker opens.

## Placement: Fallback Goes Outermost

In Polly v8, strategies run in the order added; the first added wraps everything after it.
Add the fallback **first** so it is outermost.

Trace the alternative to see why.
Suppose the order were retry, then fallback, then timeout.
The first timeout fires, the fallback (now inside the retry) catches it and returns bestsellers, and the retry sees a success.
Result: no retry ever happens, and every transient blip permanently serves the degraded answer.

With fallback outermost, the sequence is right: the timeout bounds each attempt, the retry burns through its attempts, the breaker fast-fails when things are systemically bad, and only when that whole stack gives up does the fallback produce the substitute.

![A resilience pipeline with fallback outermost, wrapping retry, circuit breaker, and timeout around the dependency; only when every inner strategy gives up does the fallback produce a degraded result marked IsDegraded](https://milanjovanovic.tech/blogs/articles/fallback-pattern-polly-dotnet/fallback-pipeline-placement.png)

In a stale-cache fallback, the cache read goes in the fallback action instead of the happy path.
This version replaces the `AddFallback` call above, with `cache` as an injected `IDistributedCache` (add `using Microsoft.Extensions.Caching.Distributed;` and `using System.Text.Json;`):

```csharp
.AddFallback(new FallbackStrategyOptions<Recommendations>
{
    ShouldHandle = new PredicateBuilder<Recommendations>()
        .Handle<HttpRequestException>()
        .Handle<TimeoutRejectedException>()
        .Handle<BrokenCircuitException>(),
    FallbackAction = async args =>
    {
        // Serve stale-but-real data if we have it, bestsellers if not.
        var json = await cache.GetStringAsync(
            $"recs:{userId}", args.Context.CancellationToken);

        var cached = json is not null
            ? JsonSerializer.Deserialize<Recommendations>(json)
            : null;

        var result = cached is not null
            ? cached with { IsDegraded = true }
            : Recommendations.Bestsellers with { IsDegraded = true };

        return Outcome.FromResult(result);
    }
})
```

This pairs with a cache-aside flow: successful responses write a copy to the cache with a long expiration, and the fallback reads that copy when the live call fails.
I go deeper on cache-aside in **caching strategies in .NET**.

## Reads Degrade, Writes Don't (Silently)

Everything above assumed reads.

For a read, a stale or generic answer is a strictly better user experience than an error page.
For a write, a fabricated success is strictly *worse* than an honest failure, because the caller now believes something false about the state of the world.
"Your order is placed" when no order exists costs more trust than "please try again in a minute" ever will.

When a write dependency is down, the legitimate options are:

- **Fail honestly.** Return a clear error. This is the right default.
- **Queue durably.** Accept the operation, persist it (an [**outbox-style**](https://milanjovanovic.tech/blog/outbox-pattern-dual-write-problem) table or a message queue), and process it when the dependency recovers, telling the user "accepted, processing" rather than "done". That's an architectural decision with idempotency and ordering consequences.

The one write-ish fallback I'll defend is a *secondary provider* (a second email or SMS gateway), because the operation still happens.
That's redundancy expressed as a fallback, and the response is still true.

## A Fallback That Fires Silently Is an Invisible Outage

When the dependency dies, fallbacks fire and users see bestsellers, while the error rate stays at zero and dashboards stay green.
Nobody notices for two days, and the business wonders why conversion dipped.

The fallback moved the failure out of the error rate; you have to put it somewhere else observable.
Minimum viable observability for any fallback:

- **Log at warning** in `OnFallback` with the original outcome, as in the code above. Warning fits a failure that is handled but still needs attention.
- **A metric.** Count fallback activations per pipeline, and alert on the *rate*. Occasional activations are normal; a sustained elevated rate is an outage.
- **Response marking.** The `IsDegraded` flag again, so support tickets saying "recommendations look generic" can be correlated with the metric.

You don't need hand-rolled counters for the metric.
Install `Polly.Extensions` and call `.ConfigureTelemetry(loggerFactory)` on the builder before `.Build()`.
Pipelines registered with `AddResiliencePipeline` get telemetry automatically.

Every fallback then increments the `resilience.polly.strategy.events` counter on the `Polly` meter with `event.name` set to `OnFallback`.
`Polly.Core` on its own emits nothing to that meter.

Then prove the whole thing works by [**injecting faults with Simmy**](https://milanjovanovic.tech/blog/chaos-engineering-simmy-dotnet): kill the dependency in staging and check that users get bestsellers, the log line appears, and the metric moves.

The same idea works at a larger scale when you choose entire degraded implementations at startup based on available infrastructure, which I covered in [**designing for graceful degradation**](https://milanjovanovic.tech/blog/graceful-degradation-fallback-pattern-dotnet).

## Summary

The fallback decides what users see while a dependency is failing.

- Return honestly degraded answers (stale cache, defaults, explicit empty states) and mark them so callers can tell.
- Put the fallback outermost in the pipeline, and make `ShouldHandle` cover `TimeoutRejectedException` and `BrokenCircuitException`, not just the raw exception.
- Let reads degrade; for writes, fail honestly or queue durably instead of returning a fake success.
- Log, count, and alert on fallback activations, because the error rate stays at zero while the fallback fires.

Decide what "degraded" means for each feature before the outage.

## Frequently asked questions

### What is the fallback pattern?

The fallback pattern provides an alternative result when an operation fails after all other resilience strategies are exhausted. Instead of surfacing an exception, the caller receives a degraded but useful answer: cached data, a default value, or an explicit empty state.

### Where should the fallback go in a Polly pipeline?

Outermost, added first in Polly v8. That way it catches everything the inner strategies give up on: exhausted retries, an open circuit breaker, and timeouts. A fallback placed inside a retry would trigger on the first failure and the retry would never run.

### Should fallbacks be used for write operations?

Almost never as a silent substitute. Returning a fake success for a failed write corrupts the caller's view of the world. For writes, prefer failing honestly or queueing the operation durably for later processing, and make the deferred state explicit in the response.

### What should I log when a fallback fires?

Log the original outcome (exception or status code) at warning level, tag the response as degraded, and increment a fallback-rate metric. A fallback that fires silently hides outages: dashboards stay green while every user sees stale or empty data.
