iTranslated by AI
[KugelPOS] Dapr Implementation Part 5/5 — Designing for Failure with Circuit Breakers

Introduction
In our previous articles, we introduced three mechanisms for solving common microservice challenges: Service Invocation (Pain Point 1), Pub/Sub (Pain Point 2), and State Store (Pain Point 3). But what happens if these mechanisms themselves encounter failures?
What if the Redis cache you rely on goes down? What if your Pub/Sub message broker becomes unresponsive? In the world of microservices, you must design with the mindset that failures in dependent components are not a "possibility," but an "inevitability."
In this article, I will discuss the "Circuit Breaker" pattern, a technique to prevent the cascading of failures, and how we implemented it in KugelPOS.
The Mechanism of Cascading Failures

One Failure, Total Impact
Let’s consider a concrete scenario.
The KugelPOS Cart service caches cart data in Redis (State Store). Under normal conditions, reading from and writing to Redis is fast, ensuring a smooth checkout experience at the register.
One day, a failure occurs in Redis. Redis stops responding, but the connection remains open, waiting for a timeout. If the timeout is set to 3 seconds and there are 3 retries, a single cart operation could potentially keep the user waiting for up to 9 seconds.
Waiting 9 seconds every time a product is scanned at the register? Checking out 30 items would take 4 and a half minutes. This effectively renders the register unusable.
Even worse, requests stuck in the timeout queue accumulate within the Cart service, eventually causing the entire system to degrade in a cascading manner.
The Concept of Circuit Breakers
Just Like an Electrical Breaker
The circuit breakers in your home’s electrical panel cut off the circuit when they detect an overcurrent, thereby protecting your electrical devices. Software circuit breakers operate on the same principle.
Three States

CLOSED — Normal State
Electricity flows normally. Requests are sent to the target component as usual. However, the number of failures is being counted.
OPEN — Tripped State
The breaker has tripped. When the number of consecutive failures reaches a certain threshold, the system transitions to this state. Requests to the target component are blocked immediately, and a fallback process is executed.
HALF-OPEN — Recovery Trial State
After a certain period of time has passed since the breaker tripped, the system sends a test request. If it succeeds, the state reverts to CLOSED; if it fails, it returns to OPEN.
Implementation in KugelPOS
Redis Fallback in the Cart Service

# cart/app/models/repositories/cart_repository.py
class CartRepository(AbstractRepository[CartDocument]):
def __init__(self, db, terminal_info=None):
super().__init__(settings.DB_COLLECTION_NAME_CACHE_CART, CartDocument, db)
self._circuit_open = False
self._failure_count = 0
self._last_failure_time = 0
self._failure_threshold = 3 # OPEN after 3 consecutive failures
self._reset_timeout = 60 # Transition to HALF_OPEN after 60 seconds
async def cache_cart_async(self, cart: CartDocument, isNew: bool = False):
# If circuit breaker is OPEN, bypass Redis
if not self._check_circuit_breaker():
logger.warning("Circuit is open. Using database directly.")
await self.__save_cart_to_db_async(cart)
return
try:
await self.__cache_cart_async(cart, isNew)
self._record_success() # Record success
except Exception as e:
self._record_failure() # Record failure
await self.__save_cart_to_db_async(cart) # Fallback to MongoDB
Under normal conditions, data is saved to Redis (in-memory cache). When a Redis failure occurs, the circuit breaker switches to OPEN, and the system immediately starts saving directly to MongoDB (persistent DB). While response speed may slightly decrease, the register remains operational.
Configuration Values — Why these numbers?
Failure Threshold: 3 times
A single failure might just be a temporary network fluctuation. Two consecutive failures could still be a coincidence. But three consecutive failures make it reasonable to conclude there is a "component failure." On the other hand, if the threshold is too high, failure detection is delayed, and the register continues to experience latency due to waiting for timeouts.
Reset Timeout: 60 seconds
Lightweight in-memory stores like Redis usually recover relatively quickly once restarted. 60 seconds is enough time to wait for recovery while preventing the system from staying in MongoDB fallback mode for too long.
Two Types of Circuit Breakers

KugelPOS actually utilizes two types of circuit breakers:
CartRepository Circuit Breaker — Protects read/write operations to the State Store within the Cart service. Falls back to MongoDB on failure.
DaprClientHelper Circuit Breaker — A common library that protects all communication with the Dapr sidecar.
The former has a fallback strategy specific to the Cart service ("replace State Store with database"), while the latter provides generic protection by detecting communication failures with the Dapr sidecar.
Designing for Failure

Balancing Optimism and Pessimism
Prepare pessimistically: Assume Redis will go down, networks will break, and Dapr sidecars will stop responding. Since these failures are "inevitable," prepare fallbacks and circuit breakers for everything.
Operate optimistically: Take full advantage of the high-speed Redis cache and Pub/Sub under normal conditions. Switch to alternatives only when a failure occurs, and automatically return to normal operations once recovered.
Integration with Health Checks
Each service in KugelPOS periodically executes the following health checks:
| Target | Verification Method |
|---|---|
| Dapr sidecar | Confirm response to health endpoint |
| State Store | Write, read, and delete test data |
| Pub/Sub | Confirm publication of test messages |
| MongoDB | Verify database connection |
The role of health checks is to visualize the status of each component. While the circuit breaker detects failures and continues operations via fallbacks, operators can identify the root cause based on health check information and perform recovery actions. This synergy maintains the availability of the entire system.
Conclusion
Circuit breakers are not mechanisms to "prevent" failures. They are mechanisms to prevent the influence of a failure from spreading when it occurs.
Because microservices consist of many components, the probability of failure somewhere is high. Accepting this reality and designing to "continue business operations even when a failure occurs" is crucial. Circuit breaker fallbacks sustain operations, while health checks visualize the situation. Together, they support the availability of KugelPOS.
Throughout this series, I have discussed the challenges of microservices and their solutions using Dapr: simplifying inter-service communication with Service Invocation, asynchronous processing with Pub/Sub, infrastructure-independent state management with State Store, and fault tolerance with Circuit Breakers. Each of these mechanisms separates infrastructure complexity from application code, allowing developers to focus on business logic.

KugelPOS Backend Services
GitHub: https://github.com/kugel-masa/kugelpos-backend
License: Apache 2.0
Discussion