.NET  

What is Circuit Breaker Pattern and How to Implement It in Microservices?

Introduction

In modern microservices architecture, applications often depend on multiple external services such as APIs, databases, and third-party systems. While this makes systems flexible and scalable, it also introduces a big challenge — failure handling.

If one service fails and we keep calling it repeatedly, it can slow down the entire system or even cause a complete outage. This is where the Circuit Breaker Pattern becomes very important.

The circuit breaker pattern helps protect your system from cascading failures by stopping calls to a failing service and allowing it time to recover.

In this article, we will understand the circuit breaker pattern in simple words and learn how to implement it in microservices step by step with practical 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

The circuit breaker pattern is a powerful design pattern used in microservices to handle failures and improve system resilience. By stopping repeated calls to failing services and allowing controlled recovery, it prevents cascading failures and ensures system stability. Using tools like Polly in .NET, you can easily implement circuit breakers and build robust, production-ready microservices.