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

Core Principle: Failure Is Inevitable

Modern cloud-native applications are distributed across many components, including:

  • Multiple servers and hardware systems

  • Networks and network providers

  • Operating systems and runtime environments

  • Cloud services and third-party APIs

  • Different technology stacks and software dependencies

Any one of these components can eventually fail. This does not necessarily indicate poor design. Instead, resilient application design assumes that failures will occur and plans how the application should respond.

Resilience is the ability of an application to recover from component failures and continue serving users.

A resilient application should:

  • Detect failures quickly

  • Avoid waiting indefinitely for unavailable services

  • Prevent one failing dependency from bringing down the entire application

  • Return useful alternative responses when possible

  • Control the number and timing of repeated requests

  • Recover when the failed service becomes available again

  • Be tested under realistic failure conditions

The five primary patterns discussed are:

  1. Timeouts

  2. Graceful degradation

  3. Retries

  4. Exponential backoff, including jitter

  5. Circuit breakers

A complementary engineering practice is chaos engineering, which deliberately introduces failures to discover weaknesses and improve resilience.


Example Application Architecture

The example application is a small distributed joke service.

Application Components

The application contains three main layers:

1. React Web Application

The React client provides the user interface. Its main data-fetching component:

  • Calls the application API

  • Receives joke data in JSON format

  • Displays the joke setup, punchline, and source

  • Refreshes the content when the user requests another joke

The client does not call the third-party joke service directly. Instead, it communicates with the application’s own .NET API.

2. .NET Microservice

The .NET service contains a controller and a joke client.

Its responsibilities are to:

  • Receive requests from the React application

  • Call the third-party joke API

  • Receive the third-party response as JSON

  • Serialize the response back to the React application

  • Act as a proxy between the frontend and the external service

The service uses an HttpClient to make REST requests to the external API.

3. Third-Party Joke API

The external joke API supplies the actual joke data. A joke contains:

  • Setup

  • Punchline

  • Source

Under normal conditions, the source identifies the third-party API. During fallback behavior, the source changes so that the application can show which resilience mechanism generated the response.

Request Flow

The normal request path is:

  1. The user requests a joke in the React application.

  2. The React application sends a request to the .NET microservice.

  3. The .NET microservice forwards the request to the third-party joke API.

  4. The third-party API returns a joke.

  5. The .NET microservice serializes and forwards the joke.

  6. The React application renders the joke.

This architecture creates a dependency chain. If the third-party service becomes slow or unavailable, the problem can propagate backward through the microservice to the user interface.


Failure Propagation Without Resilience

Suppose the third-party joke API becomes slow or begins failing.

A typical failure sequence is:

  1. A client sends a request to the .NET microservice.

  2. The microservice forwards the request to the third-party API.

  3. The third-party API does not respond promptly.

  4. The microservice continues waiting.

  5. The React application also waits for the microservice.

  6. Additional users send more requests.

  7. The microservice creates more outgoing requests to an already overloaded dependency.

  8. Requests accumulate and consume resources.

  9. The microservice itself becomes overloaded.

  10. New requests experience even longer delays or fail completely.

This demonstrates a central resilience problem: a dependency failure can become an application-wide failure if requests are allowed to wait indefinitely or are repeated without control.


1. Timeouts

Definition

A timeout limits how long an application waits for a response from another service.

If the response does not arrive within the configured period, the request is canceled and the application handles the resulting timeout exception.

A timeout converts an indefinite wait into a controlled failure.

Why Timeouts Matter

Without a timeout:

  • Threads or asynchronous tasks may remain occupied indefinitely

  • Requests can accumulate

  • Memory and connection resources may be exhausted

  • The dependent service may become even more overloaded

  • The application may eventually stop serving other users

A timeout allows the application to stop waiting and move on to another response strategy, such as a fallback or retry.

Configuring an HTTP Client Timeout

In .NET, a timeout can be assigned directly to an HttpClient. For example, the service can set a five-second limit.

Conceptually:

  • The request begins

  • The client waits for the external response

  • If the response arrives within five seconds, it is returned normally

  • If it does not, the client raises a timeout exception

The timeout applies to each individual request attempt.

Benefits and Limitations

Benefits

  • Prevents requests from waiting forever

  • Protects application resources

  • Provides a clear point at which failure handling begins

  • Reduces the chance that a slow dependency will bring down the application

Limitations

A basic timeout only produces an exception. If the application does not handle that exception, the user may see an error or an unhelpful interface state.

Timeouts therefore provide an important foundation, but they are usually combined with other resilience patterns.

More Granular Timeout Control with Polly

The .NET application can also use Polly, a resilience library for .NET. Similar resilience libraries exist for other programming languages.

A Polly timeout policy can:

  • Define a timeout duration

  • Wrap the external request

  • Execute the request asynchronously

  • Pass a cancellation token to the operation

  • Cancel the individual task when the timeout is reached

A cancellation token provides more precise control over asynchronous work. It allows the application to cancel the operation inside the policy rather than merely allowing the overall request to continue in an uncontrolled state.

Two Timeout Approaches

Direct HTTP Client Timeout

  • Configured as a property of the HTTP client

  • Simple to implement

  • Applies broadly to requests made by that client

  • Produces a timeout exception when the limit is exceeded

Policy-Based Timeout

  • Implemented through a resilience library such as Polly

  • Wraps the request in a policy

  • Supports cancellation tokens

  • Can be combined with retries, fallbacks, and circuit breakers

  • Provides more control over how the timeout participates in a wider resilience strategy


2. Graceful Degradation

Definition

Graceful degradation occurs when an application provides a reduced but still useful experience instead of failing completely when a dependency is unavailable.

When the preferred service cannot provide a response, the application returns an acceptable alternative.

In the example application, the fallback response is a locally defined joke. Its source indicates that it came from the fallback rather than the third-party API.

Fallback Policies

A Polly fallback policy specifies what the application should do after the normal operation fails.

The fallback policy:

  1. Handles an exception from the primary operation

  2. Creates an alternative response

  3. Returns that response to the caller

  4. Allows the user interface to remain functional

The fallback response has the same general structure as a normal joke:

  • Setup

  • Punchline

  • Source

For example, the application can return a joke whose source is labeled “fallback.” This makes the behavior visible during testing and demonstrates that the external service was not used successfully.

Policy Wrapping

A fallback policy can be combined with another policy, such as a timeout policy.

The policies are wrapped together so that:

  1. The application attempts the normal request.

  2. The timeout policy limits how long the request can run.

  3. If the request fails or times out, an exception is produced.

  4. The fallback policy catches the failure.

  5. The application returns the fallback joke.

This arrangement prevents a timeout from becoming an unhandled error.

Example Behavior

When the third-party API responds quickly:

  • The normal joke is returned.

  • The source identifies the external API.

When the third-party API takes longer than the timeout:

  • The timeout occurs.

  • The fallback policy is activated.

  • A predefined joke is returned.

  • The source identifies the fallback.

When the external API becomes available again:

  • A later request can return a normal response.

Advantages

Graceful degradation:

  • Preserves a usable user experience

  • Prevents every dependency failure from becoming a visible application failure

  • Allows the application to provide partial functionality

  • Gives developers a controlled response for known failure conditions

Important Design Considerations

Fallback content should be:

  • Appropriate for the feature

  • Valid according to the same response structure as normal data

  • Clearly distinguishable during monitoring and testing

  • Safe to return when the dependency is unavailable

  • Sufficiently useful to the user

A fallback is not always appropriate. For some operations, such as financial transactions, returning fabricated data would be dangerous. In those situations, the application may need to return a clear failure message instead.


3. Retries

Definition

A retry repeats a failed request in the hope that the failure is temporary.

Retries can help with transient problems such as:

  • Short network interruptions

  • Temporary service overload

  • Brief connection failures

  • Intermittent infrastructure problems

  • Random service errors

Retry Policy

A Polly retry policy can:

  • Specify which exceptions should trigger a retry

  • Define the maximum number of retry attempts

  • Execute the request again after a failure

  • Be combined with timeouts and fallback behavior

In the example, the retry policy handles an exception and attempts the request up to five times.

Combining Retries with Timeouts and Fallbacks

The policies can be chained so that they operate in a specific order:

  1. The application sends a request.

  2. The timeout policy limits the duration of the attempt.

  3. If the attempt fails, the retry policy sends another request.

  4. This process continues until the retry limit is reached.

  5. If every attempt fails, the fallback policy returns an alternative response.

If each attempt has a two-second timeout and the application makes five attempts, the external service may be given approximately ten seconds of total request time, excluding additional policy overhead.

Benefits

Retries are useful when:

  • The failure is likely to be temporary

  • The operation is safe to repeat

  • The dependency may recover quickly

  • A successful response is significantly more valuable than an immediate fallback

Risks

Retries can also make an outage worse.

If many clients retry immediately and repeatedly:

  • The failing service receives even more traffic

  • Existing overload increases

  • Recovery becomes less likely

  • The retrying clients consume additional resources

  • The system can create a feedback loop

A basic retry strategy used by many clients can resemble a distributed denial-of-service attack against the dependency.

When Retries Are Unsafe

Retries should be used cautiously for operations that are not idempotent.

An idempotent operation produces the same effective result when repeated. Reading a joke is generally safe to retry. Creating an order or charging a payment may not be safe unless the operation has safeguards such as an idempotency key.


4. Exponential Backoff

Definition

Exponential backoff increases the waiting period between retry attempts.

Instead of retrying immediately or waiting the same duration each time, the application waits progressively longer.

A typical sequence might be:

  • First wait: two seconds

  • Second wait: four seconds

  • Third wait: eight seconds

  • Fourth wait: sixteen seconds

The delay grows exponentially according to a mathematical rule such as:

delay=2retry attempt\text{delay} = 2^{\text{retry attempt}}delay=2retry attempt

The exact sequence depends on how retry attempts are numbered and how the policy is configured.

Why Exponential Backoff Is Better Than Immediate Retries

Exponential backoff reduces pressure on an unhealthy dependency.

It gives the external service time to:

  • Recover from temporary overload

  • Release exhausted resources

  • Reestablish network connections

  • Complete internal recovery processes

  • Process existing requests before receiving more traffic

It also spreads requests over a longer period rather than sending them all at once.

Implementing Exponential Backoff

A retry policy can use a wait-and-retry operation. The wait duration is calculated for each retry attempt using an exponential function.

The policy defines:

  • How many retries are permitted

  • The base delay

  • The mathematical growth factor

  • The request behavior after each failure

Exponential backoff is typically combined with a timeout and fallback:

  1. The request is attempted.

  2. The attempt times out or fails.

  3. The application waits for the calculated delay.

  4. The request is attempted again.

  5. The delay increases after subsequent failures.

  6. A fallback is returned if all retries fail.

Limitations of Exponential Backoff

Although exponential backoff reduces request concentration, it does not automatically eliminate it.

If every client uses the same deterministic schedule, many clients may retry at approximately the same times:

  • All clients fail at the same moment

  • All wait two seconds

  • All retry together

  • All then wait four seconds

  • All retry together again

This synchronized behavior is called retry clustering or a thundering herd effect.


Exponential Backoff with Jitter

Definition

Jitter introduces randomness into retry delays.

Instead of every client waiting for exactly the same duration, each client receives a slightly different delay. This prevents large groups of clients from retrying simultaneously.

A retry delay can be conceptualized as:

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

In the example, a random millisecond value between zero and one thousand is added to the calculated delay. This creates approximately up to one second of variation between clients.

Why Jitter Helps

Jitter:

  • Reduces retry synchronization

  • Spreads traffic more evenly

  • Prevents retry clusters

  • Further protects the failing service

  • Improves the chance that the dependency can recover

Retry Evolution

The resilience strategies can be viewed as progressively more controlled approaches:

  1. Basic retry: repeat the request a fixed number of times.

  2. Retry with exponential backoff: increase the wait between attempts.

  3. Retry with exponential backoff and jitter: increase the wait and add randomness to avoid synchronization.

Jitter is particularly important in distributed systems where many clients may experience the same failure at the same time.


5. Circuit Breakers

Definition

A circuit breaker stops requests from reaching a failing dependency after repeated failures.

It is modeled after an electrical circuit breaker: when too many failures occur, the circuit opens and interrupts the flow of requests.

A circuit breaker prevents the application from repeatedly calling a dependency that is known to be unhealthy.

Why a Circuit Breaker Is Needed

Retries, even with exponential backoff and jitter, may continue to send requests to a service that is completely unavailable.

Those requests are unlikely to succeed and still consume:

  • Network capacity

  • Application threads or tasks

  • Connection-pool resources

  • CPU and memory

  • Resources on the failing dependency

A circuit breaker stops this repeated traffic.

Circuit Breaker Behavior

In the example, the circuit breaker is configured to:

  • Observe exceptions from the external API

  • Open after five failures within a defined period

  • Prevent further calls for one minute

  • Return a special fallback response while open

  • Allow requests again after the break period ends

The exact threshold and duration should be chosen according to the application and dependency.

Circuit Breaker States

Although the demonstration focuses on the circuit opening and later closing, circuit breakers are commonly described using three states.

Closed

  • Requests flow normally to the dependency.

  • Failures are counted.

  • The circuit remains closed while the dependency behaves acceptably.

Open

  • Requests are stopped before reaching the dependency.

  • A fallback or immediate failure is returned.

  • The failing service is given time to recover.

Half-Open

  • After the open period expires, a limited request or set of requests is allowed through.

  • If the dependency has recovered, the circuit closes.

  • If the dependency still fails, the circuit opens again.

Circuit Breaker Fallback

A circuit breaker can have its own fallback policy.

This fallback handles a specific broken-circuit exception rather than a general request exception. It returns a response that indicates the circuit breaker is active.

For example:

  • A normal fallback may indicate that an individual request timed out.

  • A circuit breaker fallback indicates that the dependency has been failing repeatedly and calls are currently being blocked.

These different responses can help with:

  • User communication

  • Logging

  • Metrics

  • Troubleshooting

  • Operational monitoring

Maintaining Circuit State

A circuit breaker must maintain state across requests. If a new policy instance is created for every request, the application may lose the accumulated failure count and the circuit may never open correctly.

The policy wrapper should therefore be created and stored at a longer-lived scope, such as:

  • A class-level field

  • A long-lived service instance

  • A dependency-injection-managed singleton or appropriately scoped object

The policy configuration can be initialized when the joke client is constructed rather than every time the joke method is called.

Policy Order

A complete policy wrapper can combine:

  • Timeout

  • Retry

  • Exponential backoff

  • Jitter

  • Normal fallback

  • Circuit breaker

  • Circuit breaker fallback

The ordering matters. A typical conceptual sequence is:

  1. Attempt the request.

  2. Enforce a timeout.

  3. Retry transient failures.

  4. Increase delays using exponential backoff.

  5. Add jitter to spread retries.

  6. Open the circuit after repeated failures.

  7. Return a fallback while the circuit is open.

The precise ordering should be selected carefully because it changes how failures are counted and how long the application waits.

Advantages

Circuit breakers:

  • Stop unnecessary calls to an unhealthy service

  • Reduce cascading failures

  • Protect both the caller and the dependency

  • Return rapid responses instead of waiting through repeated timeouts

  • Allow the dependency time to recover

  • Make persistent failures visible through metrics and logs


Chaos Engineering

Definition

Chaos engineering is the disciplined practice of deliberately introducing controlled failures or stress into a system, observing its behavior, and using the results to improve resilience.

Chaos engineering is not merely breaking a system; it is learning how the system responds under realistic stress and correcting weaknesses discovered during the experiment.

Purpose

Chaos engineering helps uncover:

  • Hidden failure modes

  • Incorrect assumptions

  • Missing fallbacks

  • Poor timeout settings

  • Retry storms

  • Inadequate monitoring

  • Unexpected dependency relationships

  • Components that become single points of failure

  • Differences between expected and actual recovery behavior

It improves both:

  • Resilience, by identifying how the system can continue operating

  • Performance, by exposing resource bottlenecks under stress

Chaos Engineering Versus Simple Failure Injection

Simply causing a service to fail is not enough.

A complete chaos engineering exercise includes:

  1. Defining a controlled failure experiment

  2. Targeting the correct resources

  3. Applying the failure

  4. Observing system behavior

  5. Measuring user and system impact

  6. Comparing actual behavior with expected behavior

  7. Improving the application

  8. Repeating the test to verify the improvement

Observation is essential. Without measurement and analysis, failure injection provides little useful information.


Fault Injection in a Cloud Environment

A fault injection simulator can be used to run controlled experiments against real infrastructure.

Example Experiment

Suppose the third-party joke API runs across several Amazon EC2 instances. An experiment can be configured to:

  • Stop selected instances

  • Target only instances labeled for the API

  • Keep them stopped for one minute

  • Observe how the application responds

  • Allow the instances to recover afterward

The experiment acts on real services rather than a mock environment, so it must be designed and executed carefully.

Targeting Resources with Tags

Tags allow the experiment to select only the intended infrastructure.

For example:

  • API instances are given an API-related tag.

  • The experiment targets resources with that tag.

  • Unrelated servers remain unaffected.

Targeting is important because it makes the experiment:

  • More precise

  • Easier to control

  • Safer

  • More representative of the intended failure scenario

Experiment Lifecycle

A controlled fault-injection experiment generally follows this process:

  1. Define the failure action, such as stopping instances.

  2. Specify the target resources.

  3. Apply filters or tags to limit the target.

  4. Set the duration of the failure.

  5. Create the experiment.

  6. Review the target resources and warnings.

  7. Start the experiment.

  8. Observe the infrastructure and application.

  9. Confirm recovery after the experiment ends.

During the demonstration, the selected instances stopped for one minute and then became available again.

Other Possible Actions

Fault injection can support more than stopping virtual machines. Depending on the environment, experiments may affect:

  • Container instances

  • Network behavior

  • Infrastructure availability

  • Service resource conditions

  • Other cloud-based components

The key principle is to introduce realistic but controlled disruptions that test the application’s assumptions.


Designing Effective Resilience Strategies

The patterns work best when combined rather than used in isolation.

A Typical Resilience Sequence

A robust request strategy may operate as follows:

  1. Timeout: Stop waiting after a reasonable period.

  2. Retry: Repeat the operation if the failure may be temporary.

  3. Exponential backoff: Increase the delay between attempts.

  4. Jitter: Randomize delays to avoid synchronized retries.

  5. Fallback: Return a useful alternative if the operation cannot succeed.

  6. Circuit breaker: Stop making calls when repeated failures show that the dependency is unhealthy.

  7. Observability: Record and measure the behavior for diagnosis and improvement.

Questions to Ask When Choosing Policies

For each dependency, designers should consider:

  • How long should a normal request take?

  • Which errors are transient?

  • Which operations are safe to repeat?

  • How many retries are appropriate?

  • How much total time can the user wait?

  • What fallback response is safe and useful?

  • How many failures should open the circuit?

  • How long should the circuit remain open?

  • How will recovery be detected?

  • What logs, metrics, and alerts are needed?

  • How will the strategy be tested under realistic failure conditions?

Avoiding Overengineering

Resilience policies should reflect the dependency and operation.

For example:

  • A read-only joke request can usually be retried safely.

  • A payment request requires much stricter retry controls.

  • A fallback containing stale information may be acceptable for a catalog.

  • A fallback containing fabricated financial data would be unacceptable.

  • A five-second timeout may be suitable for one service but too short or too long for another.

Resilience is therefore not a fixed collection of settings. It is a design process based on failure probability, user expectations, business consequences, and dependency behavior.


Key Takeaways

Failures are inevitable in distributed systems, so applications should be designed to recover rather than assuming every dependency will always work.

  • Timeouts prevent requests from waiting indefinitely.

  • Graceful degradation supplies a reduced but useful response when the preferred dependency fails.

  • Retries handle temporary failures, but uncontrolled retries can amplify an outage.

  • Exponential backoff increases the delay between retries and reduces pressure on an unhealthy service.

  • Jitter adds randomness to retry delays and prevents clients from retrying in synchronized clusters.

  • Circuit breakers stop requests to a repeatedly failing dependency and allow it time to recover.

  • Chaos engineering deliberately tests failure behavior and uses observations to improve the system.

  • Resilience policies must be composed carefully, configured according to the operation, and validated through realistic testing.

  • A resilient application does not merely avoid failure; it continues providing an appropriate service while failure is occurring.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent