0Pricing
C# Academy · Lesson

Timeout and Fallback Policies

Bound waits and provide graceful fallbacks.

Timeout and Fallback Policies is a free C# Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Timeouts Matter

A call that never returns is worse than one that fails: it ties up threads and connections. A timeout strategy caps how long an operation may run before Polly cancels it.

Adding A Timeout

Polly v8 provides AddTimeout. When the limit is exceeded it throws a TimeoutRejectedException and cancels the underlying token.

using Polly.Timeout;

var pipeline = new ResiliencePipelineBuilder()
    .AddTimeout(TimeSpan.FromSeconds(3))
    .Build();

Cooperative Cancellation

The timeout works by cancelling the CancellationToken passed to your callback. Your code must honor that token for the timeout to take effect promptly.

await pipeline.ExecuteAsync(async token =>
{
    // token is cancelled when the timeout fires
    await httpClient.GetAsync(url, token);
});

Reacting To Timeouts

Use TimeoutStrategyOptions with an OnTimeout callback to log or emit metrics when an operation is cut short.

new TimeoutStrategyOptions
{
    Timeout = TimeSpan.FromSeconds(3),
    OnTimeout = args =>
    {
        Console.WriteLine($"Timed out after {args.Timeout}");
        return default;
    }
};

What Is A Fallback?

A fallback provides a substitute result when an operation fails, so the user gets a graceful degraded experience instead of an error: cached data, a default value, or a friendly message.

Adding A Fallback Strategy

AddFallback needs a typed pipeline. You define which failures to handle and what value to return instead.

using Polly.Fallback;

var pipeline = new ResiliencePipelineBuilder<string>()
    .AddFallback(new FallbackStrategyOptions<string>
    {
        ShouldHandle = new PredicateBuilder<string>()
            .Handle<HttpRequestException>(),
        FallbackAction = args =>
            Outcome.FromResultAsValueTask("cached default")
    })
    .Build();

Returning Cached Data As Fallback

A common pattern is to serve the last known good value from cache when the live call fails, keeping the app responsive.

FallbackAction = args =>
{
    var cached = _cache.GetLastKnownGood();
    return Outcome.FromResultAsValueTask(cached);
}

Observing Fallbacks

The OnFallback callback fires when the fallback runs, ideal for logging that a degraded path was taken.

new FallbackStrategyOptions<string>
{
    FallbackAction = args => Outcome.FromResultAsValueTask("default"),
    OnFallback = args =>
    {
        Console.WriteLine("Fallback executed");
        return default;
    }
};

Timeout Plus Fallback Together

Combining them is powerful: a timeout bounds the wait, and a fallback supplies a value when the timeout (or any handled failure) occurs, so callers never hang or crash.

Choosing Sensible Timeouts

Set timeouts based on realistic latency plus headroom, not arbitrarily small values. Too tight and you fail healthy calls; too loose and you defeat the purpose.

Fallback Is The Last Resort

Place fallback as the outermost strategy so it can catch failures from retries, breakers and timeouts alike, guaranteeing the caller always gets a usable result.

Quick Check

Test timeout and fallback strategies.

Recap

Timeouts cap operation duration with AddTimeout, cancelling the token and throwing TimeoutRejectedException (honor the token!). Fallbacks supply substitute results via AddFallback with a FallbackAction, often serving cached data. Together they keep apps responsive: bound the wait, then degrade gracefully. Place fallback outermost so it catches all handled failures.

Frequently asked questions

Is the “Timeout and Fallback Policies” lesson free?

Yes — the full text of “Timeout and Fallback Policies” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Timeout and Fallback Policies”?

Bound waits and provide graceful fallbacks. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Timeout and Fallback Policies” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Retry Policies
  2. Circuit Breaker Pattern
  3. Timeout and Fallback Policies
  4. Resilience Pipelines
← Back to C# Academy