ASP.NET Hosting

ASP.NET Core Tutorial: How can the Circuit Breaker Pattern be Implemented in Microservices?

Applications with contemporary microservices architecture frequently rely on a variety of external services, including databases, third-party systems, and APIs. Systems become more adaptable and scalable as a result, but addressing failures becomes a significant difficulty.

The system as a whole may slow down or possibly go completely down if one service fails and we keep calling it. The Circuit Breaker Pattern becomes crucial at this point. By halting calls to a malfunctioning service and giving it time to recover, the circuit breaker pattern helps shield your system from cascade failures. This post will explain the circuit breaker pattern in layman’s terms and walk us through the process of implementing it in microservices using real-world examples.

What is Circuit Breaker Pattern?

The circuit breaker pattern is a design pattern used in microservices to detect failures and prevent continuous calls to a failing service.

It works similar to an electrical circuit breaker:

  • When everything is fine → current flows normally
  • When there is a fault → circuit breaks
  • After some time → circuit tries again

In software:

  • Service works → requests are allowed
  • Service fails → requests are blocked
  • After recovery → requests are allowed again

Why Circuit Breaker is Important in Microservices?

In microservices, services are connected with each other. If one service fails, it can affect others.

Without a circuit breaker:

  • Continuous retries overload the failing service
  • System performance drops
  • Cascading failures happen

With circuit breaker:

  • System becomes resilient
  • Failures are isolated
  • Recovery becomes faster

States of Circuit Breaker

A circuit breaker has three main states:

Closed State

  • Requests are allowed
  • System works normally
  • Failures are monitored

Open State

  • Requests are blocked
  • Immediate failure response is returned
  • Prevents further damage

Half-Open State

  • Limited requests are allowed
  • Checks if service has recovered
  • If successful → moves to Closed
  • If failed → moves back to Open

How Circuit Breaker Works Internally

The circuit breaker monitors failures and switches states based on conditions:

  1. Service is working → Closed state
  2. Failures exceed threshold → Open state
  3. After timeout → Half-Open state
  4. If success → Closed
  5. If failure → Open again

This ensures controlled recovery.

Step 1: Install Polly Library (for .NET)

Polly is a popular .NET library for resilience patterns.

dotnet add package Polly

Step 2: Create a Circuit Breaker Policy

using Polly;

var circuitBreaker = Policy
    .Handle<Exception>()
    .CircuitBreaker(
        exceptionsAllowedBeforeBreaking: 3,
        durationOfBreak: TimeSpan.FromSeconds(10)
    );

Explanation:

  • After 3 failures → circuit opens
  • Break duration → 10 seconds

Step 3: Execute Code with Circuit Breaker

circuitBreaker.Execute(() =>
{
    Console.WriteLine("Calling external service...");
    throw new Exception("Service failure");
});

After failures, further calls will fail immediately.

Step 4: Handle Circuit Breaker States

You can track state changes:

var circuitBreaker = Policy
    .Handle<Exception>()
    .CircuitBreaker(
        3,
        TimeSpan.FromSeconds(10),
        onBreak: (ex, breakDelay) =>
        {
            Console.WriteLine("Circuit opened");
        },
        onReset: () =>
        {
            Console.WriteLine("Circuit closed");
        },
        onHalfOpen: () =>
        {
            Console.WriteLine("Circuit half-open");
        });

Step 5: Use Circuit Breaker with HttpClient

In ASP.NET Core microservices:

builder.Services.AddHttpClient("MyService")
    .AddPolicyHandler(Policy
        .Handle<HttpRequestException>()
        .CircuitBreakerAsync(3, TimeSpan.FromSeconds(10)));

Now all HTTP calls are protected.

Step 6: Combine Retry and Circuit Breaker

Best practice is to combine retry with circuit breaker.

var retryPolicy = Policy
    .Handle<Exception>()
    .Retry(2);

var circuitBreaker = Policy
    .Handle<Exception>()
    .CircuitBreaker(3, TimeSpan.FromSeconds(10));

var policyWrap = Policy.Wrap(retryPolicy, circuitBreaker);

This improves resilience.

Step 7: Provide Fallback Response

When circuit is open, return fallback response.

var fallback = Policy
    .Handle<Exception>()
    .Fallback(() => "Service unavailable, try later");

Real-World Example

Imagine an e-commerce system:

  • Order service calls payment service
  • Payment service fails

Without circuit breaker:

  • Continuous retries → system slowdown

With circuit breaker:

  • Requests blocked
  • System remains stable

Best Practices for Circuit Breaker

  • Use proper failure thresholds
  • Combine with retry and timeout
  • Monitor system health
  • Log state changes

Common Mistakes to Avoid

  • Setting very low thresholds
  • Ignoring fallback strategies
  • Not monitoring circuit state

Summary

One effective design pattern for handling failures and enhancing system resilience in microservices is the circuit breaker pattern. It prevents cascade failures and guarantees system stability by preventing repeated calls to failing services and permitting controlled recovery. You can quickly implement circuit breakers and create reliable, production-ready microservices using tools like Polly in.NET.

ASP.NET Core 10.0 Hosting Recommendation

HostForLIFE.eu
HostForLIFE.eu is a popular recommendation that offers various hosting choices. Starting from shared hosting to dedicated servers, you will find options fit for beginners and popular websites. It offers various hosting choices if you want to scale up. Also, you get flexible billing plans where you can choose to purchase a subscription even for one or six months.