Web & DataComplete guide

Resilience & Rate Limiting

Resilience policies decide how a call behaves when something downstream is slow or failing; rate limiting decides how much load a service accepts in the first place.

Overview

Resilience is controlled failure handling, not a promise that every operation eventually succeeds. Outbound calls need explicit deadlines, bounded retries with jitter, circuit breaking, concurrency limits, and an end-to-end time budget. Inbound rate limiting protects finite capacity and should partition fairly by authenticated client or another trustworthy key. Retry only transient, repeatable operations; use idempotency keys where a repeated write is possible. Choose token bucket for controlled bursts, fixed or sliding windows for quotas, and concurrency limiting for scarce work slots. Emit stable rejection responses and Retry-After guidance, measure attempts and breaker state, and test with deterministic time and injected failures. Layer budgets so retries cannot outlive the caller, and avoid multiplying attempts across clients, gateways, and services.

What you will learn

  • Classify failures before applying policies.
  • Compose timeout, retry, breaker, and concurrency budgets.
  • Choose an inbound limiter from workload behavior.
  • Partition admission fairly and securely.
  • Make repeated writes idempotent.
  • Test failure and refill behavior deterministically.

Prerequisites

  • ASP.NET Core middleware, HttpClient, async cancellation, and dependency injection.
  • Basic latency, throughput, HTTP status, and idempotency concepts.
  • A stated capacity and failure budget for the protected operation.

When to use Resilience & Rate Limiting

Good fit

  • A remote dependency has known transient failures.
  • A service must preserve capacity during bursts.
  • Clients need predictable overload behavior.

Choose another approach when

  • Retries wrap non-repeatable writes without idempotency.
  • Every layer independently retries.
  • Limits use spoofable or unbounded partition keys.

Key concepts

Failure taxonomy

Classify transient, permanent, overload, cancellation, and timeout outcomes before choosing a response.

Timeout budgets

Bound the whole operation and give each attempt less time than the remaining caller budget.

Retry and jitter

Retry only safe transient failures with bounded exponential delay and randomness that prevents synchronized storms.

Circuit breakers

Stop calls after sustained failure, probe recovery carefully, and expose breaker state to operators.

Concurrency isolation

Limit simultaneous dependency calls so one slow system cannot exhaust every worker or connection.

Rate-limit algorithms

Fixed window, sliding window, token bucket, and concurrency policies offer different burst and fairness behavior.

Partitioning and identity

Partition limits by a trusted tenant, API client, or route instead of attacker-controlled raw input.

Backpressure and signals

Return predictable 429 or 503 responses, Retry-After where useful, and telemetry that explains rejection.

Architecture

Outbound calls pass through composed resilience policies before reaching a dependency, while inbound requests pass through a rate limiter before reaching application code.

Inbound request
Rate limiter
Application
Resilience-wrapped outbound call

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The sample isolates the policy mechanics with a deterministic token bucket and bounded retry policy, making time and failure assertions fast and repeatable.

  1. 01
    Define outcomes

    Map exceptions and status codes to transient, permanent, timeout, cancellation, or overload.

  2. 02
    Set a budget

    Choose an end-to-end deadline, per-attempt timeout, and maximum attempts.

  3. 03
    Protect repetition

    Require idempotency before retrying mutations and add jitter to backoff.

  4. 04
    Select admission

    Choose token bucket, window, or concurrency limiting from burst and resource behavior.

  5. 05
    Partition fairly

    Use authenticated client or tenant identity and bound partition count.

  6. 06
    Return contracts

    Produce stable problem details, 429 or 503 semantics, and Retry-After guidance.

  7. 07
    Observe and tune

    Measure attempts, latency, rejections, saturation, and breaker transitions under injected failure.

Code example

A named HttpClient gets a standard resilience pipeline once, so every call through it is protected consistently.

ResilientClient.cs
builder.Services.AddHttpClient<IPaymentsClient, PaymentsClient>()
    .AddResilienceHandler("payments", pipeline =>
    {
        pipeline.AddRetry(new HttpRetryStrategyOptions { MaxRetryAttempts = 3 });
        pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions());
        pipeline.AddTimeout(TimeSpan.FromSeconds(5));
    });

builder.Services.AddRateLimiter(options =>
    options.AddFixedWindowLimiter("api", limiter =>
    {
        limiter.PermitLimit = 100;
        limiter.Window = TimeSpan.FromMinutes(1);
    }));

Testing strategy

Test policies as state machines with fake time and scripted outcomes.

  • Prove transient success within the attempt bound.
  • Prove permanent failure is not retried.
  • Advance fake time to verify token refill.
  • Test cancellation and total timeout.
  • Test partition fairness and eviction.
  • Load-test rejection before dependency collapse.

Security considerations

Admission controls are also abuse controls, but only when identity and resource accounting are trustworthy.

  • Prefer authenticated client or tenant keys.
  • Do not reveal internal dependency details.
  • Bound partition cardinality.
  • Protect bypass and policy configuration.
  • Audit repeated abusive rejection patterns.

Performance and scalability

Policies consume latency and capacity, so tune the whole call graph rather than isolated defaults.

  • Keep retries inside the caller budget.
  • Measure retry amplification.
  • Limit concurrent dependency calls.
  • Use jitter to smooth recovery.
  • Benchmark limiter partitions at expected cardinality.

Deployment and operations

Roll policy changes gradually because small threshold changes can reshape traffic.

  • Publish rejection and retry contracts.
  • Canary threshold changes.
  • Align gateway and service policies.
  • Alert on saturation and breaker state.
  • Rehearse dependency brownouts.

Common problems and fixes

Latency grows during outage.

Likely cause: Retries multiply slow attempts.

Fix: Reduce attempts and enforce an end-to-end timeout.

Dependency never recovers.

Likely cause: Retry storms keep it saturated.

Fix: Add jitter, circuit breaking, and concurrency isolation.

Legitimate bursts are rejected.

Likely cause: The chosen algorithm has no burst allowance.

Fix: Use a token bucket or tune queue and replenishment.

One tenant affects everyone.

Likely cause: Limits use a global partition.

Fix: Partition by trusted tenant and reserve shared capacity deliberately.

Memory grows with clients.

Likely cause: Partition keys are unbounded.

Fix: Normalize keys and evict idle limiter state.

Clients retry immediately.

Likely cause: Rejections omit useful guidance.

Fix: Return stable 429 responses and a realistic Retry-After value.

Best practices

  • Retry only transient repeatable work.
  • Budget the entire operation.
  • Add jitter to delayed retries.
  • Use breakers with measured thresholds.
  • Limit dependency concurrency.
  • Partition admission with trusted identity.
  • Bound limiter state cardinality.
  • Tune from telemetry and failure drills.

Production checklist

  • Failure classes are explicit.
  • Total and per-attempt timeouts are bounded.
  • Writes are idempotent before retry.
  • Attempts use backoff and jitter.
  • Concurrency protects dependencies.
  • Limiter algorithm and partition key are justified.
  • Rejections are observable and documented.
  • Brownout and recovery tests pass.

Common interview questions

Why can retries worsen an outage?

They amplify demand while a dependency has reduced capacity, especially when clients retry together.

Retry versus circuit breaker?

Retry repeats one operation; a breaker suppresses new calls after aggregate failure crosses a threshold.

Why use jitter?

It spreads retries over time so callers do not create a synchronized recovery spike.

Which limiter allows controlled bursts?

A token bucket accumulates permits up to a capacity while replenishing at a configured rate.

When is concurrency limiting useful?

When the scarce resource is simultaneous work, such as database connections or expensive requests.

How should limits be partitioned?

By a bounded, trusted identity that matches the fairness boundary, usually tenant or API client.

What makes retrying a POST safe?

An idempotency contract that returns the same outcome and prevents duplicate side effects.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Resilience Admission Lab

A deterministic .NET 10 sample demonstrating bounded transient retries, permanent failure handling, token-bucket admission, rejection, and fake-time refill tests.

.NET 10ResilienceRate LimitingxUnit
dedicated-sampleretrytoken-bucketfake-time
Run
dotnet run --project src/ResilienceAdmissionLab
Test
dotnet test ResilienceAdmissionLab.slnx