Enhancing Resilience in Applications

Enhancing Resilience in Applications

Today, we're delving into two game-changing concepts that can enhance the reliability of the applications: the Retry and Circuit Breaker patterns. Let's jump right in and explore how these patterns work their magic!

In this article, we will explore about Retry pattern

Retry Pattern: In the world of cloud computing, things can sometimes get a bit unpredictable. Connections might experience glitches, servers could briefly falter, and data might take an unexpected turn. Retry pattern comes to our rescue.

Strategies: Where should we consider using this pattern?

Network Failure: Imagine an application losing connection for a moment

Component Failure: Sometimes, a piece of our system might go offline for a little while—maybe for maintenance or it crashed or restarted.

Request Throttling: If a section of our system is inundated with an excessive number of requests, requests will be throttled for some time.

These kinds of issues often fix themselves over time. And that's where the Retry Pattern comes into play. Instead of throwing in the towel and giving up, we're going to give it another shot.

Let's look into the code now:

public class RetryPattern : IResiliencePolicy
{
? ? ?private readonly int maxRetryAttempts;
? ? ?private readonly TimeSpan retryDelay;

? ? ?public RetryPattern(int maxRetryAttempts, TimeSpan retryDelay)
? ? ?{
? ? ? ? ? ? this.maxRetryAttempts = maxRetryAttempts;
? ? ? ? ? ? this.retryDelay = retryDelay;
? ? ?}

? ? ?public async Task<T> ExecuteAsync<T>(Func<Task<T>> asyncAction)
? ? ?{
? ? ? ? ?int retryCount = 0;


? ? ? ? ?while (retryCount < maxRetryAttempts)
? ? ? ? ?{
? ? ? ? ? ? ?try
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? T result = await asyncAction();
? ? ? ? ? ? ? ? ? ? return result;? ? ? ? ?
? ? ? ? ? ? ?}
? ? ? ? ? ? ?catch (TransientException ex)
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?Console.WriteLine($"Transient Exception: {ex.Message}");
? ? ? ? ? ? ? ? ?// Increment the retry count
? ? ? ? ? ? ? ? ?retryCount++;
? ? ? ? ? ? ? ? ?// Wait for the specified delay before retrying
? ? ? ? ? ? ? ? ?await Task.Delay(retryDelay);
? ? ? ? ? ? ?}
? ? ? ? ? ? ?catch (Exception ex)
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?// Handle other non-                
? ? ? ? ? ? ? ? ?Console.WriteLine($"Non-Transient Exception: {ex.Message}");
? ? ? ? ? ? ? ? ?throw;
? ? ? ? ? ? ?}
? ? ? ? ?}
? ? ? ? ?Console.WriteLine("Maximum retry attempts reached. The operation failed.");
? ? ? ? ?throw new MaxRetryAttemptsReachedException();
? ? ?}
}
        

Exceptions :

public class TransientException : Exceptio
{
? ? //It is usually temporary and intermittent in nature, meaning it appears and disappears over time.
? ? public TransientException(string message) : base(message)
? ? {
? ? }
}

public class MaxRetryAttemptsReachedException : Exceptio
{
    public MaxRetryAttemptsReachedException() : base("Maximum retry attempts reached.") { }
}        

Interface: All resilient policies in the next articles will implement this interface

public interface IResiliencePolicy
{
? ? Task<T> ExecuteAsync<T>(Func<Task<T>> action);
}        


Things to consider here if the error/fault is not transient, then the application should cancel the operation and report an exception.

For example: Imagine we have an authentication request and due to invalid credentials we get the error then we should cancel the request instead to go with retry.

Another example, we have a system that sends notifications to users via email. the email service provider might experience temporary issues due to high demand. In that situation, trying to resend the same notification over and over again using the Retry Pattern might not be ideal. Instead, we should be using the Circuit Breaker Pattern. If the email service consistently fails to respond, the circuit could "trip," and set the states(Close, Open, HalfOpen). Once the provider is back in action, the circuit could close, allowing notifications to be sent again.

We will explore the circuit breaker in the next article.

So, next time you encounter a hiccup in your services, remember the Retry Pattern

要查看或添加评论,请登录

Saurabh Singh的更多文章

社区洞察

其他会员也浏览了