Chapter 11 of 12
Course Progress0 of 12 completed (0%)

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.

Reliability & Resiliency: Rate Limiting & Circuit BreakersDefend distributed microservices from cascading failures: Token Bucket & Leaky Bucket rate limiting, exponential backoff with full jitter, and three-state circuit breakers.UNDERSTANDLimit incoming callsFOLLOW THE FLOWOpen circuitAPPLY ITRecover safelyReliability & Resiliency: Rate Limiting & Circuit BreakersDefend distributed microservices from cascading failures: Token Bucket & Leaky Bucket rate limiting, exponential backoff with full jitter, and three-state circuit breakers.UNDERSTANDLimit incoming callsFOLLOW THE FLOWOpen circuitAPPLY ITRecover safely

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:

Step 1

Slow Dependency

A database slow-query log causes the Recommendations service to take 15 seconds per request instead of 20ms.

Step 2

Thread Starvation

The API Gateway holds 500 worker threads waiting for recommendations. All gateway threads saturate.

Step 3

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:

Token Bucket
Burst Friendly

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.

Leaky Bucket
Constant Flow Rate

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:

State 1

CLOSED (Normal)

Requests pass through to the dependency. Successes and failures are counted. If failures exceed the threshold, the circuit trips to OPEN.

State 2

OPEN (Failing Fast)

Calls fail immediately without touching the network, returning a fallback response in <1ms. A cooldown sleep timer runs.

State 3

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.

Concept Check

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

503 Service Unavailable → 10,000 Instant Retries → Thundering Herd crushes recovering pod!Flaw: Retry storms prevent downed servers from ever finishing boot or clearing connection queues

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

sleep = min(cap, base × 2^attempt) × uniform(0, 1) → Smooth Gaussian retry distributionResilience: Eliminates resonance peaks and gives downstream dependencies breathing room to heal

Multiply wait times by powers of 2 (1s, 2s, 4s, 8s) and inject random jitter (0 to wait). Retries desynchronize smoothly over time.

Concept Check

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
8/10available
Breaker State
CLOSED
Breaker Failures
0/3to trip
Rate Limits (429)
0blocked

Token Bucket Rate Limiter

+1 Token / sec

Each API request consumes 1 token. When empty, incoming requests are rejected immediately with HTTP 429.

Bucket Fill Level:80%

Circuit Breaker Protection

Upstream: Healthy (200)

If downstream dependency crashes, breaker opens to prevent thread exhaustion and return instant fallbacks.

CLOSEDNormal Traffic
OPENTripped
HALF-OPENTrial Probe
Gateway Resiliency Event Stream:
›Gateway online: Token Bucket initialized (Capacity: 10, Refill: +2/sec).
›Circuit Breaker initialized: State = CLOSED (Threshold: 3 failures).

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:

Python Circuit Breaker Bug Hunt · Resiliency & Fallbacks
Python

🎯 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" and self.failure_count = 0 in record_success().
  • Trip on failure: uncomment the threshold check in record_failure().

7Chapter Knowledge Challenge

Test your mastery of rate limiting and circuit breaker architectures:

Concept Check 1 of 2
1

When an API Gateway returns HTTP 429 Too Many Requests to a client, which response header should it provide to guide well-behaved clients?

Concept Check 2 of 2
2

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?

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us