1. Home
  2. Explore
  3. Computer Science
  4. Resilient Application Design Patterns

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Resilient Application Design Patterns

Building Resilient Distributed Applications

Modern applications often depend on many separate components: web interfaces, microservices, third-party APIs, networks, servers, and databases. Each component introduces another possible point of failure. Resilience is the ability of an application to continue operating acceptably when one or more of those components fail.

A resilient application does not assume that every request will succeed. Instead, it anticipates failure, limits the damage caused by failure, and provides a controlled way to recover.

Failures are inevitable over time. The important design question is not whether failure will occur, but how the application will respond when it does.

This lesson develops five patterns for building resilient applications:

  1. Timeouts
  2. Graceful degradation
  3. Retries
  4. Exponential backoff
  5. Circuit breakers

It also introduces chaos engineering, a practice used to test whether resilience mechanisms actually work.

A Distributed Application Example

The example application is a small joke service with three main parts:

  1. A React web application provides the user interface.
  2. A .NET microservice receives requests from the React application.
  3. A third-party joke API supplies the jokes.

The request path is:

React application→.NET microservice→third-party joke API\text{React application} \rightarrow \text{.NET microservice} \rightarrow \text{third-party joke API}React application→.NET microservice→third-party joke API

The third-party API returns information such as:

  • The setup of the joke
  • The punchline
  • The source of the joke

The .NET service acts as a proxy. It receives a request from the React application, calls the external joke API, receives a JSON response, and serializes the result back to the React application.

The application works normally when the third-party API responds quickly. The problem appears when that external service becomes slow or unavailable.

What happens without resilience?

Suppose the React application sends a request. The .NET microservice forwards it to the third-party API, but the API does not respond.

Without protective mechanisms, several harmful events can occur:

  • The .NET microservice waits indefinitely.
  • The React interface waits for the .NET response.
  • Another client sends another request.
  • The microservice forwards that request too.
  • More requests accumulate while the third-party API is already struggling.
  • The microservice consumes more resources waiting for responses.
  • Eventually, the microservice itself may become overloaded.

This creates a chain reaction. A failure in one external service can spread into the rest of the application.

Think About It

If an external API becomes slow, why might waiting indefinitely be more dangerous than immediately returning an error or alternate response?

Pattern One: Timeouts

A timeout places an upper limit on how long an application will wait for an operation to complete.

The purpose of a timeout is not to make the external service faster. Instead, it prevents the calling application from waiting forever and consuming resources while it waits.

HTTP client timeouts

In .NET, a timeout can be configured directly on an HttpClient. For example, a five-second timeout means:

  • The request begins.
  • The application waits for the response.
  • If the response does not arrive within five seconds, the request is cancelled.
  • A timeout exception is produced.

Conceptually:

Maximum waiting time=5 seconds\text{Maximum waiting time} = 5\text{ seconds}Maximum waiting time=5 seconds

If the external API responds in four seconds, the request succeeds. If it responds in more than five seconds, the request times out.

This protects the microservice from indefinitely waiting on a dependency.

Why a basic timeout is not enough

A simple timeout limits waiting, but it may produce an unhandled exception. From the user’s perspective, the interface may freeze while waiting and then receive no useful explanation when the timeout occurs.

Therefore, a timeout is an important foundation, but it usually needs to be combined with another response strategy.

Policy-based timeouts with Polly

Polly is a .NET resilience library. Other programming languages have comparable resilience libraries, but Polly provides the mechanisms used in this example.

Instead of configuring only the HTTP client, the application can use Polly’s timeout policy. A policy controls how an operation is executed and gives the application more control over the result.

The operation is placed inside an asynchronous policy execution:

  1. Polly starts the operation.
  2. The operation receives a cancellation token.
  3. The cancellation token allows the task to be cancelled if the timeout is reached.
  4. If the operation does not finish in time, Polly signals the timeout.

A cancellation token gives the application control over an asynchronous task. Rather than merely waiting for a general client-level timeout, the application can explicitly cancel the individual operation being managed by the policy.

The two timeout approaches are therefore:

  • A timeout configured directly on HttpClient
  • A timeout managed through a resilience policy such as Polly

Both limit waiting, but a policy-based timeout provides more control and can be composed with other policies.

A timeout prevents an operation from consuming resources indefinitely, but it does not by itself determine what the user should receive afterward.

Think About It

A timeout of five seconds does not mean that every request should take five seconds. It means that five seconds is the maximum acceptable waiting period before the application stops waiting.

Pattern Two: Graceful Degradation

Graceful degradation means that an application provides a reduced but still useful response when a dependency fails.

The application does not pretend that the third-party API worked. Instead, it supplies an alternate result, allowing the rest of the application to remain usable.

For the joke application, a fallback joke is returned when the external API fails or exceeds its timeout.

Fallback policies

A Polly fallback policy defines what should happen when the normal operation cannot complete successfully.

The fallback process works like this:

  1. The application attempts to call the third-party API.
  2. The request fails or raises an exception.
  3. The fallback policy detects the failure.
  4. Instead of passing the failure directly to the user, it returns a predefined joke.
  5. The response identifies the source as "fallback".

For example, a fallback joke might have:

  • Setup: The application is in a band called 1023 megabytes.
  • Punchline: It has not had a gig yet.
  • Source: Fallback.

The specific joke is less important than the design idea: the application continues to return a valid response.

Why graceful degradation matters

A third-party API failure does not necessarily mean that the entire application must become unusable. If the application can offer an alternate response, users may still see a functioning page rather than an error or an indefinitely loading screen.

Graceful degradation is particularly useful when:

  • The external response is helpful but not essential.
  • A cached or predefined result is acceptable.
  • A reduced feature is better than no feature.
  • The application needs to preserve a usable experience during temporary failures.

Combining a timeout and fallback

The timeout and fallback policies can be wrapped together. The general flow becomes:

Request→timeout policy→fallback policy if failure occurs\text{Request} \rightarrow \text{timeout policy} \rightarrow \text{fallback policy if failure occurs}Request→timeout policy→fallback policy if failure occurs

If the request completes within the allowed time, the normal joke is returned. If it exceeds the limit and raises an exception, the fallback joke is returned instead.

This combination limits the waiting time and provides a controlled result.

Think About It

Why is a clearly labeled fallback response often better than allowing an unhandled exception to reach the user interface?

Pattern Three: Retries

A retry means attempting an operation again after it fails.

Retries are useful because some failures are temporary. A network request might fail because of a brief connection problem, momentary overload, or a transient issue in the external service. A second attempt may succeed even though the first did not.

How a retry policy works

A retry policy can be configured to handle an exception and attempt the operation again a specified number of times.

For example, the policy may allow five retries:

  1. The initial request fails.
  2. The application tries again.
  3. If the second attempt fails, another attempt is made.
  4. This continues until the retry limit is reached.
  5. If every attempt fails, the fallback policy is used.

When combined with a timeout, each individual attempt has its own maximum duration.

If each attempt has a two-second timeout and the operation is attempted five times, the total waiting period can approach:

5×2 seconds=10 seconds5 \times 2\text{ seconds} = 10\text{ seconds}5×2 seconds=10 seconds

The exact total behavior depends on whether the count describes retries in addition to the initial request, but the central idea is that repeated attempts can substantially increase total response time.

Why retries need limits

Retries can help with temporary failures, but unlimited or overly aggressive retries create new problems:

  • They increase the load on an already struggling service.
  • They consume resources in the client and microservice.
  • They delay the user’s response.
  • Many clients retrying simultaneously can overwhelm the external API.

A retry policy therefore needs a controlled retry count and should usually be combined with timeouts and a fallback.

Combining retries with fallback

A policy wrapper can combine the mechanisms in a sequence such as:

Attempt→timeout→retry→fallback\text{Attempt} \rightarrow \text{timeout} \rightarrow \text{retry} \rightarrow \text{fallback}Attempt→timeout→retry→fallback

The intended logic is:

  • Try the request.
  • If an attempt times out or fails, retry it.
  • Continue until the retry limit is reached.
  • If all attempts fail, return the fallback response.

Retries are therefore more useful than a single timeout when failures may be temporary, while fallback prevents the application from failing completely when retries do not help.

Think About It

A retry helps when a failure is temporary. What happens if the dependency is permanently unavailable and every client keeps retrying at the same time?

Pattern Four: Exponential Backoff

A basic retry policy may retry immediately or at a fixed interval. Exponential backoff improves this approach by increasing the waiting period after each failed attempt.

A typical sequence is:

2 seconds, 4 seconds, 8 seconds, 16 seconds2\text{ seconds},\ 4\text{ seconds},\ 8\text{ seconds},\ 16\text{ seconds}2 seconds, 4 seconds, 8 seconds, 16 seconds

The wait grows exponentially rather than remaining constant.

Why increasing the wait helps

Suppose the external API is overloaded. If every client retries immediately, the failed requests are replaced by more requests at exactly the moment the service is under pressure.

Exponential backoff gives the external service time to recover and spreads requests over a longer period.

The retry process can be represented as:

  1. Initial request fails.
  2. Wait two seconds.
  3. Retry and fail again.
  4. Wait four seconds.
  5. Retry and fail again.
  6. Wait eight seconds.
  7. Continue according to the configured retry limit.

This reduces the intensity of repeated requests compared with immediate retries.

Implementing the timing

The delay can be calculated with a power relationship. For example, a delay based on powers of two can be represented conceptually as:

delay=2n seconds\text{delay} = 2^{n}\text{ seconds}delay=2n seconds

where nnn represents the retry attempt.

The retry policy therefore controls both:

  • How many attempts are permitted
  • How long the application waits before each attempt

Exponential backoff is better, but not perfect

Exponential backoff reduces concentrated load, but clients may still become synchronized.

For example, if many clients experience the same failure at the same time and all use the same delay sequence, they may all retry after two seconds, then all retry after four seconds, and so on. The requests become clustered at predictable moments.

This phenomenon can undermine the load-distributing benefit of exponential backoff.

Jitter

Jitter adds a random variation to each retry delay.

For example, the application can add a random delay between zero and one thousand milliseconds:

0 ms≤random adjustment≤1000 ms0\text{ ms} \leq \text{random adjustment} \leq 1000\text{ ms}0 ms≤random adjustment≤1000 ms

Instead of all clients retrying at exactly four seconds, their retries may occur at slightly different times around that interval.

The purpose is to prevent retry clustering:

  • Client A retries after approximately four seconds.
  • Client B retries after approximately four and a half seconds.
  • Client C retries after approximately four and nine-tenths seconds.

The exact values vary, but the requests are spread out.

Exponential backoff with jitter

The combined approach can be understood as:

retry delay=exponential delay+random adjustment\text{retry delay} = \text{exponential delay} + \text{random adjustment}retry delay=exponential delay+random adjustment

This provides two protections:

  • Exponential growth reduces repeated pressure on the dependency.
  • Jitter prevents many clients from retrying simultaneously.

Exponential backoff spaces retries farther apart; jitter prevents those spaced retries from becoming synchronized.

Think About It

If one hundred clients all use the same retry schedule, why might randomizing the delay be safer than giving every client identical waiting periods?

Pattern Five: Circuit Breakers

Retries and backoff are useful when recovery is likely. However, repeated attempts become wasteful when the dependency is clearly broken.

A circuit breaker stops requests from reaching a failing service after a defined failure threshold has been reached.

The name comes from an electrical circuit breaker. When dangerous conditions are detected, the breaker interrupts the circuit to prevent further damage.

The circuit breaker sequence

The circuit breaker in the example is configured so that:

  • If five API calls produce exceptions, the circuit opens.
  • Once open, requests are not sent to the third-party API.
  • The circuit remains open for one minute.
  • During that minute, the application returns a circuit-breaker fallback response.
  • After the minute has passed, requests can again reach the third-party API.

Conceptually:

five failures→open circuit for one minute\text{five failures} \rightarrow \text{open circuit for one minute}five failures→open circuit for one minute

When the circuit is open, the request path changes:

React application→.NET microservice→circuit-breaker fallback\text{React application} \rightarrow \text{.NET microservice} \rightarrow \text{circuit-breaker fallback}React application→.NET microservice→circuit-breaker fallback

The third-party API is bypassed entirely.

Why a circuit breaker is different from a retry

A retry continues trying to reach the dependency. A circuit breaker decides that continuing to try is currently pointless.

This distinction is important:

  • Retry: “The failure may be temporary, so try again.”
  • Circuit breaker: “Enough failures have occurred that further attempts should stop temporarily.”

The circuit breaker protects both sides of the relationship. It prevents the client from wasting resources and prevents the failing service from receiving even more requests.

Circuit-breaker fallback

A circuit-breaker fallback is different from an ordinary exception fallback because it specifically indicates that the circuit is open.

The policy handles a circuit-breaker exception, often described as a broken-circuit condition, and returns a predefined response whose source identifies the circuit breaker.

This allows the application to distinguish among situations such as:

  • A normal response from the third-party API
  • A fallback caused by an individual request failure
  • A fallback caused by an already-open circuit

Why the circuit breaker must preserve state

Unlike a simple timeout or retry, a circuit breaker must remember previous failures. It needs to know whether the failure threshold has been reached and whether the one-minute open period is still active.

For that reason, the policy wrapper should be created once and stored as shared state in the client rather than rebuilt for every request.

If the policy were reconstructed each time, it could lose its history and never accumulate enough failures to open the circuit.

The design therefore involves:

  1. Defining the policies during client construction.
  2. Storing the policy wrapper as a class-level or client-level field.
  3. Reusing that wrapper for subsequent requests.
  4. Allowing the circuit breaker to maintain its state across calls.

Combining all resilience policies

The patterns can be composed into a layered strategy:

  1. The request is given a timeout.
  2. A temporary failure may trigger retries.
  3. Retry delays use exponential backoff.
  4. Jitter spreads the retry attempts.
  5. Repeated failures eventually open the circuit.
  6. A fallback response is returned when the request cannot be completed.

A conceptual flow is:

request→timeout→retry with backoff and jitter→circuit breaker→fallback\text{request} \rightarrow \text{timeout} \rightarrow \text{retry with backoff and jitter} \rightarrow \text{circuit breaker} \rightarrow \text{fallback}request→timeout→retry with backoff and jitter→circuit breaker→fallback

The policies address different failure behaviors rather than replacing one another.

Think About It

Why would a circuit breaker be preferable to continuing exponential-backoff retries when the external service has already failed repeatedly?

Chaos Engineering

The five patterns describe how an application should respond to failure. Chaos engineering is the practice of deliberately creating controlled failures so that the response can be observed and improved.

Chaos engineering involves more than simply breaking a service. It has two essential parts:

  1. Injecting a failure or stressful condition.
  2. Observing how the system behaves and using the results to improve it.

The goal is to uncover hidden problems, expose blind spots, and verify that resilience mechanisms work under realistic conditions.

Failure injection in the example

The joke API used randomly injected failures. This made it possible to observe:

  • Requests timing out
  • Retry policies making additional attempts
  • Exponential backoff spacing those attempts
  • Fallback responses being returned
  • Circuit breakers opening after repeated failures

This provides a practical way to test the application’s behavior before an unexpected production failure occurs.

Fault injection experiments

A fault injection simulator can define an experiment that affects real infrastructure.

For example, an experiment may:

  • Stop selected compute instances.
  • Target only instances with a particular tag.
  • Keep those instances stopped for one minute.
  • Allow the application to be observed during that period.
  • Restore the instances after the experiment ends.

If the third-party API runs across several EC2 instances, the experiment can target only the instances tagged as API servers. This makes the test more precise than indiscriminately affecting every server.

The process is:

  1. Define the failure action, such as stopping instances.
  2. Define the target resources.
  3. Use tags or other parameters to limit the target.
  4. Specify the duration of the experiment.
  5. Create the experiment.
  6. Run it with the appropriate warnings and controls.
  7. Observe the application while the failure is active.
  8. Inspect the behavior after the infrastructure recovers.

Because the experiment acts on real services, it must be treated carefully. It is not merely a simulation shown for appearance; stopping the instances actually affects the running system.

Why chaos engineering is difficult

Traditional chaos testing can require:

  • Custom scripts to cause failures
  • Multiple tools stitched together
  • Agents or complex libraries
  • A carefully controlled test environment
  • Difficult attempts to reproduce realistic production events

Testing in production is risky, but testing only in an artificial environment may fail to reveal real interactions among services, networks, and infrastructure.

A fault injection simulator helps make experiments more targeted and repeatable. The failure can be applied to a particular service, at a particular time, for a particular duration.

What chaos engineering teaches

Chaos engineering reveals whether the system behaves as designed. It can answer questions such as:

  • Does the client stop waiting after the timeout?
  • Do retries stop at the configured limit?
  • Are retry delays spread out?
  • Does the fallback response appear?
  • Does the circuit breaker prevent further calls?
  • Does the application remain usable when servers stop?
  • Does the system recover when the dependency returns?

The observations from these experiments should guide improvements to the architecture and resilience policies.

Chaos engineering improves resilience by turning unknown failure behavior into something that can be observed, tested, and corrected.

How the Patterns Work Together

Each pattern addresses a different part of the failure problem.

Timeouts limit waiting

A timeout prevents a request from occupying resources indefinitely.

Graceful degradation preserves usability

A fallback response gives the application something useful to return when the normal dependency is unavailable.

Retries handle temporary failures

Retries provide additional opportunities for a request to succeed.

Exponential backoff controls retry pressure

Backoff prevents retries from happening too quickly and gives the failing service time to recover.

Jitter prevents synchronized retries

Random variation prevents large groups of clients from retrying at the same instant.

Circuit breakers stop futile traffic

A circuit breaker interrupts calls to a dependency that has demonstrated repeated failure.

Chaos engineering validates the design

Chaos experiments test whether all of these mechanisms actually behave correctly under failure.

The overall relationship can be summarized as follows:

MechanismMain purpose
TimeoutLimit how long a request waits
Graceful degradationReturn an alternate response
RetryAttempt a potentially temporary failure again
Exponential backoffIncrease the delay between retries
JitterRandomize retry timing
Circuit breakerTemporarily stop calls after repeated failures
Chaos engineeringTest and improve failure behavior

Comprehensive Review

A distributed application depends on multiple components, and any of those components can eventually fail. Resilient design accepts this reality instead of treating failure as an unusual event.

The example application demonstrates a request flowing from a React interface through a .NET microservice to a third-party joke API. Without resilience, a slow external API can cause requests to accumulate, overload the microservice, and eventually affect users.

A timeout establishes a maximum waiting period. A policy-based timeout, such as one implemented with Polly, also allows more precise control over asynchronous cancellation.

Graceful degradation uses a fallback response when the normal request fails. This keeps the application useful even when the external API cannot provide a joke.

Retries address temporary failures by attempting the operation again. However, retries must be limited because many clients retrying at once can overload the dependency.

Exponential backoff improves retries by increasing the waiting period after each failure. Jitter adds randomness so that clients do not synchronize their retry attempts into the same time windows.

A circuit breaker protects the system when failures continue. After a threshold such as five exceptions, it stops sending requests to the failing service for a defined period such as one minute. Because it must remember prior failures, its policy state must persist across requests.

Chaos engineering deliberately injects failures and observes the results. It is used to discover hidden weaknesses, confirm that resilience policies work, and improve the application based on evidence.

Together, these patterns create a controlled failure strategy:

limit waiting→retry carefully→spread retries→stop repeated damage→return a useful fallback\text{limit waiting} \rightarrow \text{retry carefully} \rightarrow \text{spread retries} \rightarrow \text{stop repeated damage} \rightarrow \text{return a useful fallback}limit waiting→retry carefully→spread retries→stop repeated damage→return a useful fallback

A resilient application is not one that never encounters failure. It is one that recognizes failure quickly, limits its effects, continues serving users when possible, and recovers when the underlying dependency becomes healthy again.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent