📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are fallback and graceful degradation in a distributed system? How do you serve cached or partial data when a dependency fails, how do feature switches help, what should the user see, and when must you fail closed instead of falling back?

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.

Mid-Level Theory Intermediate distributed-systems fallback feature-flags graceful-degradation polly resilience

🎯 Key points

  • Fallback = a substitute result when a call fails; degradation = the product keeps its core job with fewer features
  • Rank features as critical or optional before the outage, not during it
  • Last-known-good cache with an age limit, and show the user how old the data is
  • Polly v8 (current major version) AddFallback with ShouldHandle on specific failures; it sits outermost, around retry and breaker
  • Fallback is instant only while the breaker is open; with it closed, the fallback runs after retries and timeouts are exhausted
  • Kill switches with Microsoft.FeatureManagement or Azure App Configuration to turn off optional features quickly
  • Fail closed for authorisation, payments, safety and compliance checks; never default to allow
  • Emit metrics when the fallback is used and test fallbacks with fault injection

⏱ 30-second answer

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".

🗣 Full answer (senior)

How I would answer this in an interview

"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, TimeoutRejectedException and 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."


Kinds of fallback

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

Fail open or fail closed?

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

What the user sees

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can keep a system useful during partial failure without trading away correctness or security.

Green flags

  • Separates critical from optional features and plans it in advance
  • Pairs fallback with a circuit breaker and a tight timeout
  • Names fail-closed cases (authorisation, payments) without being asked
  • Makes fallbacks visible with metrics and honest UI

Red flags

  • Catches all exceptions and returns a default
  • Would serve stale prices or permissions with no limit
  • Never mentions what the user sees

📚 Learn in depth

1. Fallback is the outermost layer

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.

2. Design degradation before the outage

Degradation is a product decision, made in advance. A simple way to do it:

  1. List the features on each critical page or flow.
  2. Mark each one critical (the flow fails without it) or optional.
  3. For each optional dependency, decide the fallback and the user message.
  4. For each critical one, decide what the error looks like and whether writes can be deferred.
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"

3. Last-known-good caching

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:

  • Fresh path: call the dependency, update both the fresh cache (short TTL) and the last-known-good copy (long TTL, timestamped).
  • Failure path: return the last-known-good copy if it is younger than the business limit (for example, 24 hours for exchange rates used for display only), with its timestamp.
  • Past the limit: fail, because data that old is worse than no data.

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.

4. Kill switches

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.

5. Observability of fallbacks

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".

Try it yourself

  1. Build a page model that calls a fake recommendations API. Add Polly AddFallback returning an empty list, then kill the API and measure page latency with and without a breaker.
  2. Implement a last-known-good store with IDistributedCache that keeps a timestamp, and render "as of" in the response.
  3. Add a feature flag with Microsoft.FeatureManagement and wire an endpoint to return 404 when it is off. Flip it at runtime through configuration reload.
  4. Write a test that proves an authorisation lookup failure returns 403 or 503, never 200.
  5. Add a Counter<long> for fallback use and watch it with dotnet-counters monitor --counters YourApp.Resilience.

💻 Code

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); }

⚠ Common mistakes

  • Mistake: Falling back to "allow" when the authorisation or entitlement service fails. Why it is wrong: An outage becomes a security breach. Instead: Fail closed with 403 or 503 and alert.
  • Mistake: A fallback that only runs after a long timeout, because there is no circuit breaker and no tight attempt timeout inside it. Why it is wrong: During an outage every request still waits the full timeout (and any retries) before the fallback runs, so the page is slow anyway. Instead: Design the whole pipeline together: fallback outermost, then retry (if any), a breaker, and a timeout sized for optional data. When the breaker is open, the fallback is instant. While it is closed, the fallback costs at most the timeout budget.
  • Mistake: Serving stale data with no age limit and no timestamp. Why it is wrong: Users act on data that may be days old without knowing it. Instead: Keep an age limit and show "as of".
  • Mistake: Catching every exception in the fallback. Why it is wrong: Bugs (NullReferenceException, serialisation errors) are hidden as "degraded" forever. Instead: Handle specific transient and resilience exceptions only.
  • Mistake: No metric when a fallback is used. Why it is wrong: The dependency can be broken for days while dashboards look green. Instead: Count fallback use per dependency and alert on a sustained rate.
  • Mistake: Deciding what is critical during the incident. Why it is wrong: Under pressure, teams make inconsistent choices and argue. Instead: Rank features in advance and write the fallback per dependency in the runbook.
  • Mistake: Never exercising the fallback path. Why it is wrong: Code that only runs during incidents rots, and you find the bug during the outage. Instead: Inject faults in staging with Polly chaos strategies or Azure Chaos Studio, and test the degraded UI.
  • Mistake: Faking success for a deferred write. Why it is wrong: The user thinks the order is confirmed when it is only queued. Instead: Say it is received and confirm later, and make the deferred work idempotent.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions pairing the fallback with a circuit breaker Why: Checks understanding of breaker states and why an open breaker makes fallback cheap
    How to answer

    A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.

    • Closed: calls flow and outcomes are sampled.
    • Open: when failures pass a threshold, calls are rejected straight away with BrokenCircuitException for the break duration.
    • Half-open: a trial call decides whether to close the circuit or open it again.

    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.

  2. When: Candidate talks about a slow dependency taking down unrelated features Why: Checks the ability to diagnose a cascade and apply timeout, bulkhead and fallback together
    How to answer

    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:

    • Timeouts: 2 s per attempt, 5 s total.
    • One jittered retry, outside a circuit breaker tuned to the traffic.
    • A bulkhead: a concurrency limit on the shipping client.
    • No external calls inside DB transactions.
    • Liveness checks that don't include the third party.

    The trade-off is a slightly degraded feature against a whole service going down.

  3. When: Candidate mentions fallbacks or kill switches Why: Checks whether the candidate treats fallbacks as code that needs testing, using fault injection
    How to answer

    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.

🛠 Real-world problems: how you handle them

Recommendations outage slowing every product page
Situation
A retail site serving [~2 million page views a day]. Product pages called the recommendations service synchronously with a 5 s timeout and no breaker. Recommendations were [nice to have], but the call sat on the critical rendering path.
Signals
Product page p95 rose from 300 ms to 5.2 s, ThreadPool queue length went up on the web tier, the conversion rate dropped [~8%] within an hour, and recommendations returned 503s.
Investigation
The Application Insights dependency view showed the recommendations call taking 5 s on every page view. dotnet-counters showed ThreadPool queue growth. Traces confirmed no breaker and that the page awaited recommendations before rendering.
Resolution
Immediate: turned off recommendations with an existing configuration flag. Real fix: a 400 ms attempt timeout, a circuit breaker and a Polly fallback to an empty list, plus a fallback-use counter and alert.
Prevention
A critical/optional feature table per page in the runbook, chaos tests with Polly AddChaosLatency in the staging pipeline, and a review rule that optional dependencies must never block rendering.

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.

More in Reliability Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me