Circuit Breaker Pattern
What you'll learn: How to protect your serverless functions from cascading failures when downstream services become unavailable.
The Problem
When your function calls a downstream service (database, API, third-party service), that service might fail or become slow. Without protection, your function keeps trying to call the failing service, wasting execution time, exhausting concurrency limits, and potentially causing timeouts across your entire system. These failures cascade, bringing down healthy components.
What Is a Circuit Breaker?
A circuit breaker is a design pattern that monitors calls to downstream services and "trips" (opens) when failures exceed a threshold. Once open, it immediately rejects requests without attempting the call, giving the failing service time to recover.
Think of it like an electrical circuit breaker in your home: when too much current flows (too many failures), it trips to prevent damage. After a cool-down period, it allows a test request through. If successful, it "closes" and normal operation resumes.
Three States
- Closed: Normal operation, requests pass through
- Open: Failure threshold exceeded, requests fail immediately
- Half-Open: Testing phase, allows limited requests to check recovery
Implementation Approach
Since functions are stateless (remember lesson 464), circuit breaker state is typically stored externally—in a cache like Redis or DynamoDB. Your function checks the circuit state before calling downstream services. You set thresholds (e.g., "open after 5 failures in 60 seconds") and timeout periods (e.g., "try again after 30 seconds").
This pattern pairs well with Dead Letter Queues (lesson 500) for handling rejected requests and async patterns (lesson 498) for non-critical operations.
Key Takeaway: Circuit breakers prevent cascading failures by stopping calls to unhealthy downstream services, allowing them time to recover while protecting your function's resources and execution limits.