Circuit Breaker is an architectural pattern that prevents cascading errors and degradation of distributed systems. Its essence is that a component responsible for calls to an external system checks the success of operations. If there are too many failed attempts, the Circuit Breaker automatically "opens" and further calls do not go through until the system starts to recover.
Example: if the Auth microservice stops responding, the Order service, using the Circuit Breaker, temporarily does not send requests but immediately returns an error, preventing high load on the dependent system.
Example code in Python (using the pybreaker library):
import pybreaker import requests breaker = pybreaker.CircuitBreaker(fail_max=3, reset_timeout=30) @breaker def call_service(): return requests.get("https://api.service.com/data") try: response = call_service() except pybreaker.CircuitBreakerError: print("Service temporarily unavailable. Please try later.")
Key features:
Is Circuit Breaker the same as Retry?
No. Retry repeats failed operations, while Circuit Breaker breaks the chain of calls when there are many failures, allowing the system to rest. These patterns are often combined: retry inside, circuit breaker outside.
Is it necessary to implement Circuit Breaker between your own microservices that are deployed simultaneously?
Yes, if the services may experience fault-tolerant or network failures. No one is immune to configuration errors or load, not even your microservices.
Is Circuit Breaker only needed for external API integrations?
No, this pattern can be applied to any unreliable interaction, including within your own infrastructure: databases, caches, message queues.