Skip to content

Circuit Breaker Pattern: Building Resilient Microservices

Circuit Breaker Pattern: Building Resilient Microservices

The Circuit Breaker Pattern is a stability-oriented design pattern that prevents a network or service failure from cascading through your entire system.

๐Ÿ—๏ธ The Problem

In a microservices architecture, Service A calls Service B. If Service B is slow or failing, Service A might hang or fail while waiting for a response. This can lead to a โ€œcascade failure,โ€ where the entire system goes down because one service is slow.

๐Ÿš€ The .NET Implementation (using Polly)

In .NET, Polly is the most popular library for implementing resiliency patterns like Circuit Breaker, Retry, and Timeout.

1. The States of the Circuit

  1. Closed: The system is healthy, and requests flow normally.
  2. Open: The system is failing. Requests are rejected immediately (Fast-Fail) to save resources.
  3. Half-Open: A trial state. A few requests are allowed through to see if the target service has recovered.

2. Implementation with Polly

using Polly;
using Polly.CircuitBreaker;

// 1. Define the policy
var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(
        exceptionsAllowedBeforeBreaking: 3, // Break if 3 consecutive failures
        durationOfBreak: TimeSpan.FromSeconds(30) // Wait for 30s before trying again
    );

// 2. Use the policy
await circuitBreakerPolicy.ExecuteAsync(async () =>
{
    // The actual HTTP call!
    var response = await _httpClient.GetAsync("https://service-b/api/data");
    return response;
});

๐Ÿ“Š Comparison: Retry vs. Circuit Breaker

PatternPurposeWhen to use?
RetryHandle โ€œTransientโ€ (temporary) errors.โ€Glitchโ€ in the network.
Circuit BreakerHandle โ€œLong-termโ€ or โ€œMajorโ€ failures.Service B is down or overloaded.

๐Ÿ’ก Why use Circuit Breaker?

  • Fast-Fail: Return an error quickly instead of letting the user wait for a long timeout.
  • Self-Healing: Allows the failing service time to recover without being hammered with new requests.
  • Graceful Degradation: Show a โ€œcachedโ€ version of data or a friendly error message when the circuit is open.