Circuit Breaker Design Pattern

Buyung Hardiansyah
2 min readApr 22, 2021

Circuit breaker in electrical terms is an automatically switch designed to protect an electrical circuit from damage caused by excess current from an overload or short circuit.

in the role of software development, circuit breaker is a design pattern use to detects failures and prevents the application from trying to perform the action that is doomed to fail until it’s safe to retry and protecting resource and help services or a server to perform recovery.

the main idea of a circuit breaker works is by creating a wrapper or function to call the circuit breaker object to monitor failures. When the failure reaches the specified threshold, circuit breakers will immediately return the error without having to call the service to be addressed.

Generally Circuit Breaker can be used to check the availability of an external service. An external service can be a database server or a web service used by the application.

Cascading failure
Circuit breaker reduce cascading failure

circuit breaker separate into 3 state:

  • Close state in circuit breaker is a normal state where request to external services can be sent.
  • Open state is a state where a system detect failures from the requested services, when a failures detect and reached the threshold, circuit breaker will not request to the service that failed.
  • Half-Open is a state where services periodically check the service requested with limited request. if the requested service success then the state will change it state to close, if it still failed the state will return to open.

this is a sample of go code implementing circuit breaker using hystrix-go library.

we can test this code with JMeter or postman runner (using test scenario with 50 iterations and delay 50ms).

when the requested endpoint failed and reached the threshold then the response will return

{"error":"hystrix: circuit open"}

this indicate that the circuit breaker is in open state, and the request to the next services will not be sent.

--

--

Buyung Hardiansyah

Software Developer -- Golang | Python | PHP | Reactjs | Flutter