Fallback strategies (cached, default, partial and alternative responses), graceful degradation of non-critical features, feature switches and kill switches, what to show users, and when a system must fail closed rather than fall back.
A fallback returns a substitute result when a call fails: a cached value, a sensible default, a partial response or an alternative provider. Graceful degradation is the product-level version: when a dependency is down, the system keeps doing its core job with optional features switched off. For example, checkout still works but recommendations disappear.
In .NET I use Polly's AddFallback behind a circuit breaker, a last-known-good cache with an age limit, and kill switches (Microsoft.FeatureManagement or Azure App Configuration) to turn off optional features quickly. The user should see honest, reduced functionality, such as "prices as of 10:42".
The trade-off is correctness. For authorisation, payments and safety checks you fail closed: an error beats a wrong "yes".
"A fallback is what a single call returns when the real answer isn't available: a cached value, a default, partial data, or a second provider. Graceful degradation is the bigger idea: when part of the system is unhealthy, the product keeps doing its core job and drops the extras. On a product page, the price and the buy button are critical. Reviews, recommendations and the 'customers also bought' strip are optional. If the recommendations service is down, the page should render without that strip in normal time, not hang for 30 seconds and then show an error.
In .NET the building blocks are a Polly v8 fallback strategy that handles specific failures, such as
BrokenCircuitException,TimeoutRejectedExceptionand 5xx responses, and returns a substitute. It sits behind a circuit breaker, so when the dependency is down the fallback is instant instead of waiting for a timeout every time. For data that changes slowly, I keep a last-known-good copy with an age limit, and I tell the user how old it is. For whole features I use kill switches in Azure App Configuration with Microsoft.FeatureManagement, so on-call can turn off a heavy feature in seconds without a deploy.The mistake I see is falling back where you must not. If the authorisation service is down, the answer is 'no' or an error, never 'allow'. If the fraud check times out, you don't approve the payment. You queue it or decline it. And a silent fallback is dangerous too: if nobody records that we served stale data for six hours, we've hidden an outage. Every fallback emits a metric and has an owner."
| Fallback | Example | Good for | Risk |
|---|---|---|---|
| Last-known-good cache | Exchange rates from 20 minutes ago | Slowly changing reference data | Stale data used for money without the user knowing |
| Static default | Empty recommendations list | Optional UI | Hides the failure if not measured |
| Partial response | Order page without the delivery estimate | Composite pages and BFFs | Clients must handle missing fields |
| Alternative provider | Second SMS gateway | Commodity third parties | Different behaviour and cost; needs testing |
| Deferred processing | Accept the order, confirm by email later | Writes that can be eventually consistent | Must be idempotent and visible to users |
| Check | Decision | Why |
|---|---|---|
| Authorisation / permission lookup | Fail closed | Wrongly allowing access is a breach (and may be a Notifiable Data Breach under the Privacy Act 1988) |
| Payment fraud scoring | Fail closed, or queue for review | A wrong approval is real money lost |
| Product recommendations | Fail open (hide) | No harm if missing |
| Rate limiter backed by Redis | Usually fail open, with a local limit | Blocking all traffic is worse than briefly allowing extra |
| Age / identity verification | Fail closed | Legal and safety requirement |
| Situation | UI behaviour |
|---|---|
| Optional widget failed | Hide it or show a small "unavailable right now" note |
| Stale data served | Show the time it is from ("prices as of 10:42") |
| Write deferred | "We've received your order; confirmation will follow by email" |
| Core feature down | A clear error with a retry option; do not fake success |
On a retail site, the recommendations service was called synchronously on every product page with a 5 s timeout. When it went down, page p95 latency went from 300 ms to 5.2 s and conversion dropped. With a 400 ms attempt timeout, a breaker and a fallback to an empty list, the next recommendations outage left page p95 at 320 ms. The only user-visible change was a missing strip.
Checks whether the candidate can keep a system useful during partial failure without trading away correctness or security.
Green flags
Red flags
A fallback replaces a failure with a result, so it must see every failure the inner strategies produce:
Fallback ── handles BrokenCircuitException, TimeoutRejectedException, 5xx
└─ Retry
└─ CircuitBreaker (when open: fails instantly → fallback is instant)
└─ AttemptTimeout
└─ HTTP call
Without the breaker, every request during an outage waits for the full timeout before the fallback runs. With it, the fallback costs microseconds.
Degradation is a product decision, made in advance. A simple way to do it:
Product page
├─ Price, stock, buy button ── critical ── fail with a clear error
├─ Reviews ─────────────────── optional ── hide
├─ Recommendations ─────────── optional ── empty list
└─ Delivery estimate ───────── optional ── "estimated at checkout"
A normal cache entry expires and is gone. A last-known-good store keeps the previous value alongside the fresh cache, with its own age limit:
HybridCache in .NET 9 and later gives you an L1/L2 cache with stampede protection, but it does not serve stale entries after expiry on its own, so last-known-good is a separate store or a separate key.
Microsoft.FeatureManagement reads flags from configuration. With the Azure App Configuration provider and a refresh interval, a flag change reaches every instance within that interval (for example, 30 s) without a deploy. Kill switches are the manual form of degradation. On-call turns off a heavy feature (search suggestions, PDF generation) to protect the core flow during an incident.
Every fallback must be visible: a counter tagged with the dependency name and the fallback type, and a log at Warning level (sampled). Alert when the fallback rate stays above a threshold. Otherwise a broken dependency can go unnoticed for days, because the product "works".
AddFallback returning an empty list, then kill the API and measure page latency with and without a breaker.IDistributedCache that keeps a timestamp, and render "as of" in the response.Counter<long> for fallback use and watch it with dotnet-counters monitor --counters YourApp.Resilience.A fallback pipeline for optional recommendations, a last-known-good store for exchange rates, and a kill switch.
// Program.cs (.NET 10): Polly v8 via Microsoft.Extensions.Resilience, Microsoft.FeatureManagement
using System.Diagnostics.Metrics;
using Microsoft.FeatureManagement;
using Polly;
using Polly.CircuitBreaker;
using Polly.Fallback;
using Polly.Timeout;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFeatureManagement();
builder.Services.AddHttpClient<RecommendationsClient>(c => c.BaseAddress = new Uri("https://recs.internal"));
builder.Services.AddResiliencePipeline<string, IReadOnlyList<string>>("recs", (pipeline, ctx) =>
{
var fallbackUsed = ctx.ServiceProvider.GetRequiredService<IMeterFactory>()
.Create("Shop.Resilience").CreateCounter<long>("fallback.used");
// Outermost: an optional feature degrades to "no recommendations".
pipeline.AddFallback(new FallbackStrategyOptions<IReadOnlyList<string>>
{
ShouldHandle = new PredicateBuilder<IReadOnlyList<string>>()
.Handle<BrokenCircuitException>()
.Handle<TimeoutRejectedException>()
.Handle<HttpRequestException>(),
FallbackAction = _ => Outcome.FromResultAsValueTask<IReadOnlyList<string>>([]),
OnFallback = _ =>
{
// A silent fallback hides an outage: always count it.
fallbackUsed.Add(1, new KeyValuePair<string, object?>("dependency", "recommendations"));
return default;
}
});
// Breaker makes the fallback instant while recs is down.
pipeline.AddCircuitBreaker(new CircuitBreakerStrategyOptions<IReadOnlyList<string>>
{
FailureRatio = 0.5, MinimumThroughput = 20, BreakDuration = TimeSpan.FromSeconds(15)
});
pipeline.AddTimeout(TimeSpan.FromMilliseconds(400)); // optional data gets a tight budget
});
var app = builder.Build();
app.MapGet("/products/{id:int}/recommendations", async (
int id, RecommendationsClient client, IFeatureManager features,
Polly.Registry.ResiliencePipelineProvider<string> pipelines, CancellationToken ct) =>
{
// Kill switch: on-call can turn the feature off without a deploy.
if (!await features.IsEnabledAsync("Recommendations"))
return Results.Ok(Array.Empty<string>());
var pipeline = pipelines.GetPipeline<IReadOnlyList<string>>("recs");
var items = await pipeline.ExecuteAsync(async token => await client.GetAsync(id, token), ct);
return Results.Ok(items);
});
app.Run();
public sealed class RecommendationsClient(HttpClient http)
{
public async Task<IReadOnlyList<string>> GetAsync(int productId, CancellationToken ct) =>
await http.GetFromJsonAsync<List<string>>($"/recs/{productId}", ct) ?? [];
}
// Last-known-good: serve old data only within a business age limit, and say how old it is.
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;
namespace Shop.Rates;
public sealed record RateSnapshot(decimal AudToUsd, DateTimeOffset AsOf);
public sealed class RatesService(IRatesApi api, IDistributedCache cache, TimeProvider clock)
{
private const string LkgKey = "rates:last-known-good";
private static readonly TimeSpan MaxAge = TimeSpan.FromHours(24); // display only, never for settlement
public async Task<RateSnapshot> GetAsync(CancellationToken ct)
{
try
{
var fresh = new RateSnapshot(await api.GetAudToUsdAsync(ct), clock.GetUtcNow());
await cache.SetStringAsync(LkgKey, JsonSerializer.Serialize(fresh), ct);
return fresh;
}
catch (Exception ex) when (ex is HttpRequestException or TimeoutException)
{
var json = await cache.GetStringAsync(LkgKey, ct);
if (json is not null && JsonSerializer.Deserialize<RateSnapshot>(json) is { } old
&& clock.GetUtcNow() - old.AsOf < MaxAge)
return old; // caller shows "rates as of {AsOf}"
throw; // too old: an error beats a wrong number
}
}
}
public interface IRatesApi { Task<decimal> GetAudToUsdAsync(CancellationToken ct); }
NullReferenceException, serialisation errors) are hidden as "degraded" forever. Instead: Handle specific transient and resilience exceptions only.Graceful degradation is a product conversation before it is a code change. I sit with the product owner and rank each feature on the critical flows. The output is a short table in the runbook: dependency, fallback, user message, owner. The code then follows the table. On how the strategies fit together: the fallback is the outermost strategy, so it receives whatever the inner chain finally produces. With the breaker closed, that means the fallback runs only after the timeout (and any retries) has failed, which costs up to the full budget. With the breaker open, the inner chain fails at once and the fallback is effectively instant. That is why optional dependencies get a tight timeout and few or no retries.
The other senior point is that fallbacks are untested code paths until you test them. I use fault injection in a test environment (Polly's chaos strategies AddChaosFault, AddChaosLatency and AddChaosOutcome, or Azure Chaos Studio) to prove the page really renders without its optional parts. On caching: HybridCache is the right default for fresh-path caching (L1 plus L2, with stampede protection). For last-known-good I keep a separate long-lived key with a timestamp, because an expired HybridCache entry is gone and is not served as stale.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Polly fallback with a breaker | Per-call substitute values | Little code; must be measured | Security and money decisions |
| Last-known-good cache | Slowly changing reference data | Storage and an age policy | Data used for settlement or compliance |
| Kill switch (feature flag) | Heavy optional features | Flag hygiene and clean-up | Core flows: switching them off is an outage |
| Deferred processing (queue) | Writes that can be eventually consistent | Idempotency, user communication | Actions the user needs confirmed now |
A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.
BrokenCircuitException for the break duration.In Polly v8 it opens when the failure ratio (default 10%) is exceeded over a 30 s sampling window with at least 100 calls, and it breaks for 5 s. AddStandardResilienceHandler puts it inside the retry (each attempt counts, and an open circuit stops retries) and outside the 10 s attempt timeout (a hung call counts as a failure).
Pair it with a fallback and alert when it opens. The trade-off is protection and fast failure against rejecting some calls that would have succeeded.
Unrelated requests failing means the slow API exhausted a shared resource: usually database connections held while waiting, sockets, or thread-pool threads (from sync-over-async).
Diagnose: Application Insights dependency durations, then dotnet-counters for the thread pool, SqlClient pool and HTTP connections, then dotnet-dump to see what requests are waiting on. Look for the 100 s HttpClient default timeout multiplied by retries.
Mitigate: a feature flag that switches to a fallback (flat-rate shipping).
Fix:
The trade-off is a slightly degraded feature against a whole service going down.
Fallbacks are code paths that only run during incidents, so they rot unless exercised. I inject faults in a test environment with Polly v8 chaos strategies (AddChaosFault, AddChaosLatency, AddChaosOutcome) or Azure Chaos Studio. Then I assert that the page renders, the right metric increments and the user message appears. I add integration tests that make the dependency return 503 or hang, and run a game day each quarter where on-call flips the kill switches. Success means core flows stay within their SLO while the dependency is down.
How to tell it (STAR)
**S:** At [company], a recommendations outage made every product page take over five seconds, and conversion dropped [about 8%]. **T:** I had to stop an optional feature from taking down the core flow. **A:** I turned recommendations off with a configuration flag to stop the bleeding. Then I added a 400 ms timeout, a circuit breaker and a fallback to an empty list, with a counter so we would know whenever the fallback was in use. I also worked with product to mark each page feature as critical or optional. **R:** During the next recommendations outage, page p95 stayed at [about 320 ms]. Nobody outside the team noticed, apart from a missing strip and an alert to the owning team.
Last updated 23 Nov 2026.