Monday, 22 September 2025

Circuit Breaker Pattern

💡 What Is the Circuit Breaker Pattern?

The Circuit Breaker is a reliability pattern used when one service calls another (e.g., your API calling a payment gateway).
It stops repeatedly calling a failing service to avoid wasting resources and causing more failures.

Think of it like an electrical circuit breaker in your house:
If there’s a problem, it “trips” and cuts the flow until things are safe.


🏷️ Why We Need It

  • Prevents cascading failures across microservices.

  • Gives the failing service time to recover.

  • Improves user experience (you can show a quick fallback message instead of waiting for timeouts).


⚙️ How It Works

A circuit breaker has three states:

  1. Closed (normal)

    • All requests pass through.

    • If calls keep failing beyond a threshold (e.g., 5 failures in 30 seconds), it opens.

  2. Open (tripped)

    • Requests are blocked immediately (or a fallback is returned).

    • The system waits a fixed time (e.g., 1 minute).

  3. Half-Open

    • After the wait, it lets a few test requests through.

    • If they succeed → back to Closed.

    • If they fail → back to Open.


Simple Diagram

[Closed] -- too many failures --> [Open] [Open] -- wait & try --> [Half-Open] [Half-Open] -- success --> [Closed] [Half-Open] -- fail --> [Open]

🛠️ Using in .NET (with Polly)

Polly is a popular .NET library for resilience.

Example:

using Polly; using Polly.CircuitBreaker; var circuitBreaker = Policy .Handle<HttpRequestException>() .CircuitBreakerAsync( exceptionsAllowedBeforeBreaking: 3, durationOfBreak: TimeSpan.FromSeconds(30) ); await circuitBreaker.ExecuteAsync(async () => { // Your external call, e.g., HTTP to payment service await httpClient.GetAsync("https://payment.example.com/process"); });

Explanation:

  • After 3 failures, the circuit goes Open.

  • It stays open for 30 seconds before trying again.


✅ Best Practices

  • Set realistic thresholds (failure count, duration).

  • Provide fallback logic (cached data, default response).

  • Monitor and log state changes.

  • Combine with retry (exponential backoff) for transient errors.


🔑 Summary Table

StateWhat Happens
ClosedNormal, calls go through.
OpenCalls fail fast, no external calls.
Half-OpenTest a few requests to check recovery.

🏁 Quick Recap

The Circuit Breaker pattern:

  • Detects repeated failures when calling external services.

  • Opens the circuit to stop calls temporarily.

  • Half-opens to test if the service has recovered.

  • In .NET, use Polly to implement it easily.

This protects your microservices or APIs from cascading outages and keeps your system responsive even when dependencies fail.

No comments:

Post a Comment