Circuit Breaker

As defined by Polly “A circuit breaker detects the level of faults in calls placed through it, and prevents calls when a configurable fault threshold is exceeded”.

The circuit breaker only makes sense when calling a less reliable API.

Wait & Retry will only try on the following HTTP Status codes:

  • HttpStatusCode.InternalServerError,
  • HttpStatusCode.BadGateway,
  • HttpStatusCode.GatewayTimeout,
  • HttpStatusCode.RequestTimeout,
  • HttpStatusCode.Forbidden,
  • HttpStatusCode.PaymentRequired,
  • HttpStatusCode.TooManyRequests,
  • HttpStatusCode.Unauthorized

When a method fails several times in a row, the application should use the fast failure method. For example, if the API cannot be used multiple times in a row and is likely to fail, repeated calls to the API are useless.

If you find the method call you are calling is delayed, and this is very reasonable, you will have to use fallback scenario. The circuit breaker tracks the number of failed API calls. Once it continuously exceeds the failure threshold number, it will not even try to call the API for subsequent requests. Instead, it will fail immediately, just like the API failed. After the timeout, the circuit breaker will make a method call to “test” the API and see if it succeeded. If it fails, it returns immediate failure. If successful, the circuit is closed again, and it will return to call the API for each request.

Circuit-breaker is a state machine

A circuit-breaker is best thought of as a state machine, with three main states.

Close – Normal operations

Open – Failing no traffic returns a 500

Half Open – Trial period

In this trial period:

If a handled exception is received, that exception is rethrown, and the circuit transitions immediately back to open, and remains open again for the configured timespan.

If a successful result is received, the circuit transitions back to closed.
If an unhandled exception is received, the circuit remains in half-open.

For full details on the Circuit Break please go to Polly directly, here is the link: