Modern System Design & API Architecture · Chapter 11 · ~25 min · Advanced
Reliability & Resiliency: Rate Limiting & Circuit Breakers
In large-scale microservices, partial failure is not an anomaly — it is a permanent condition. Learn how to engineer bulletproof distributed systems using Token Bucket rate limiters, Circuit Breaker state machines, and exponential backoff with full jitter.
- Implement the Token Bucket and Leaky Bucket rate limiting algorithms
- Protect upstream microservices with the Circuit Breaker state machine (Closed, Open, Half-Open)
- Prevent cascading failure loops using Exponential Backoff with randomized full jitter
- Design graceful degradation and fallback responses when dependencies fail
Reliability & Resiliency: Rate Limiting & Circuit Breakers: learn it visually
Defend distributed microservices from cascading failures: Token Bucket & Leaky Bucket rate limiting, exponential backoff with full jitter, and three-state circuit breakers.
1The Anatomy of Cascading Failures
In a complex microservices topology, services depend on each other through internal RPCs and HTTP APIs. When a low-level service (such as payment authorization or recommendation scoring) suffers latency, callers hold open TCP sockets waiting for timeouts:
Slow Dependency
A database slow-query log causes the Recommendations service to take 15 seconds per request instead of 20ms.
Thread Starvation
The API Gateway holds 500 worker threads waiting for recommendations. All gateway threads saturate.
Total Blackout
Because gateway threads are blocked, unrelated APIs (Login, Cart, Account) fail with 504 Gateway Timeouts.
To stop cascading failures, systems rely on two complementary shields: Rate Limiting to protect servers from abusive traffic spikes, and Circuit Breakers to isolate failing dependencies.
2Rate Limiting Algorithms: Token Bucket vs Leaky Bucket
Rate limiters throttle excessive client requests before they reach application servers. Two predominant algorithms govern production gateways:
Tokens are added to a bucket at a fixed refill rate (e.g. 10 tokens/sec). Each request consumes 1 token. If the bucket is full, requests can burst up to capacity instantly. Ideal for general web APIs.
Requests enter a FIFO queue and leak out at a strictly constant rate (e.g. 5 requests/sec). Bursts are smoothed out, but excess requests overflow and drop. Ideal for traffic shaping and database writes.
// Redis-backed Token Bucket Lua Script (Atomic Execution)
const TOKEN_BUCKET_LUA = `
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local bucket = redis.call('HMGET', key, 'tokens', 'last_updated')
local tokens = tonumber(bucket[1]) or capacity
local last_updated = tonumber(bucket[2]) or now
-- Calculate newly replenished tokens
local elapsed = math.max(0, now - last_updated)
tokens = math.min(capacity, tokens + (elapsed * refill_rate))
if tokens >= 1 then
tokens = tokens - 1
redis.call('HMSET', key, 'tokens', tokens, 'last_updated', now)
return 1 -- Allowed
else
return 0 -- Rejected (HTTP 429)
end
`;3The Circuit Breaker State Machine
Modeled after an electrical circuit breaker in a home that trips when current spikes dangerously high, a software circuit breaker wraps protected network calls:
CLOSED (Normal)
Requests pass through to the dependency. Successes and failures are counted. If failures exceed the threshold, the circuit trips to OPEN.
OPEN (Failing Fast)
Calls fail immediately without touching the network, returning a fallback response in <1ms. A cooldown sleep timer runs.
HALF-OPEN (Probe)
A limited trial probe request is sent. If it succeeds, the breaker resets to CLOSED. If it fails, the breaker trips back to OPEN.
What is the primary architectural advantage of an OPEN circuit breaker failing fast immediately instead of waiting for a 30-second network timeout?
4Mental Models: Retries, Breakers & Rate Limits
Examine the critical design principles behind resilient systems:
Wrong idea: Retry failed API calls immediately every 50ms in a tight loop
When a downstream microservice experiences high CPU and returns 503, 10,000 client pods bombard it with synchronized immediate retries.
Real system: Exponential backoff with randomized full jitter spreads the retry stampede
Multiply wait times by powers of 2 (1s, 2s, 4s, 8s) and inject random jitter (0 to wait). Retries desynchronize smoothly over time.
Why does standard Exponential Backoff without Jitter still fail during major cloud outages?
5Hands-On: Token Bucket & Circuit Breaker Simulator
Interact with the live simulator below. Send burst requests to test token depletion, toggle upstream failure to watch the breaker trip from CLOSED → OPEN → HALF-OPEN, and observe fallback behavior:
Token Bucket & Circuit Breaker State Machine Simulator
Token Bucket Rate Limiter
Each API request consumes 1 token. When empty, incoming requests are rejected immediately with HTTP 429.
Circuit Breaker Protection
If downstream dependency crashes, breaker opens to prevent thread exhaustion and return instant fallbacks.
6Bug Hunt: Fix the Circuit Breaker State Machine
Below is a Python Circuit Breaker state machine. It contains three fatal architectural bugs: it fails to block requests when in the OPEN state, never trips to OPEN when failure threshold is exceeded, and forgets to reset to CLOSED when trial probes succeed in HALF_OPEN.
Fix the implementation below, then click Run & verify:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Check OPEN state: uncomment the cooldown timer check in
can_execute(). - Reset on success: uncomment
self.state = "CLOSED"andself.failure_count = 0inrecord_success(). - Trip on failure: uncomment the threshold check in
record_failure().
7Chapter Knowledge Challenge
Test your mastery of rate limiting and circuit breaker architectures:
When an API Gateway returns HTTP 429 Too Many Requests to a client, which response header should it provide to guide well-behaved clients?
What is 'Graceful Degradation' in system design?
8Recap & Architectural Review
- Cascading Failures: Unbounded network timeouts consume thread pools, taking down healthy services.
- Token Bucket: Governs rate limits by replenishing tokens at a constant rate while allowing short bursts.
- Circuit Breaker: Trips to OPEN during outages, failing fast in <1ms to protect thread pools.
- Exponential Backoff + Full Jitter: Desynchronizes retry storms to give struggling upstream services room to heal.
Ready for the Capstone: Scalable URL Shortener & Global Chat?