Invitation Digital Tech Blog

Building Scalable & Responsive Architecture


Just another .Net circuit breaker

There are many examples of the circuit breaker pattern in .Net floating about on the web, but they all use a timer to reset the circuit. What about maintaining the state outside of the circuit so we can use a different circuit across many requests?

I won’t bore you with another explanation of the circuit breaker pattern, you can find that here, here or even here. We needed a circuit breaker to maintain consistent connections to a remote server and fall back to a known good state if there was a problem. When a circuit is created it takes in a Func\<TResult\> that it will run when executed, a threshold of exceptions before the circuit is opened, and a timeout when the circuit is set to half open. The circuit state maintains the position of the circuit Open | Half open | Closed, the current failure count and a time that the circuit is reset.

var circuit = new Circuit<TResponse>(() => { throw new Exception();  }, 5, TimeSpan.FromSeconds(5));
var state = new CircuitState();

for(int i = 0; i < 6; i++){
    Console.WriteLine("The circuit is now open");
    Console.WriteLine("The circuit is closed");

This will output:
The circuit is closed
The circuit is closed
The circuit is closed
The circuit is closed
The circuit is closed
The circuit is now open

After 5 seconds the circuit will become ‘half open’ and allow one more request before entering the open state again. If the circuit operation is successful the circuit will close and reset the failure count.

// outputs "HalfOpen"

circuit = new Circuit<string>(() => "Test passed" , 5, TimeSpan.FromSeconds(5));
// outputs "Test passed"

// outputs "Closed"

There are a few other bells and whistles like an array of exceptions to exclude from breaking the circuit and threadsafe increments of the iteration counter, but other than that it’s a simple library that fits the bill better than maintaining a timer in a single circuit class.

Source code