Day 5 B-Building blocks 2026-09-29 ← All lessons

Design a Rate Limiter: Token Bucket, Sliding Window, Redis

Control API traffic with algorithms that balance precision, memory, and burst tolerance.

300Tweets per 3 hours
300Google Docs reads per user per 60s
429HTTP status for too many requests
0.003Cloudflare error rate (wrongly allowed/limited)

Key points

Outcomes

01Compare token bucket, leaking bucket, fixed window, sliding window log, and sliding window counter algorithms.
02Design a rate limiter architecture with middleware, Redis, and rule management.
03Address distributed challenges: race conditions, synchronization, and performance optimization.
01

Rate Limiting Algorithms: Trade-offs


Each algorithm has distinct pros and cons. Token bucket is simple and allows bursts. Leaking bucket processes at fixed rate. Fixed window is memory efficient but has edge spikes. Sliding window log is accurate but memory-heavy. Sliding window counter is a hybrid approximation.

AlgorithmProsCons
Token bucketEasy to implement, memory efficient, allows burstsTuning bucket size and refill rate is challenging
Leaking bucketMemory efficient, fixed outflow rateBursts fill queue, recent requests may be limited; tuning parameters
Fixed window counterMemory efficient, easy to understandSpikes at window edges can exceed quota
Sliding window logVery accurate, no exceeding in rolling windowHigh memory usage, stores timestamps even for rejected requests
Sliding window counterSmooths spikes, memory efficientApproximation, assumes even distribution in previous window
Comparison of rate limiting algorithms
Interview tipToken bucket is used by Amazon and Stripe; leaking bucket by Shopify; sliding window counter by Cloudflare with 0.003% error rate.
02

High-Level Architecture and Redis


How to read: Follow arrows: client sends request to middleware, which checks Redis and either forwards to API or returns 429.

flowchart LR Client --> RateLimiterMiddleware RateLimiterMiddleware -->|Check counter| Redis RateLimiterMiddleware -->|Forward if allowed| APIServers RateLimiterMiddleware -->|429 if limited| Client
High-level rate limiter architecture using Redis for counters.

Redis is chosen for its speed and support for INCR and EXPIRE commands. INCR increments the counter; EXPIRE sets a timeout to automatically delete the counter.

  1. Client sends request to rate limiting middleware.

  2. Middleware fetches counter from Redis and checks if limit is reached.

  3. If limit reached, request is rejected with 429.

  4. If not, request is forwarded to API servers and counter is incremented in Redis.

03

Distributed Rate Limiting Challenges


In distributed environments, race conditions and synchronization issues arise. Race conditions occur when concurrent requests read and write counters without atomicity. Synchronization is needed when multiple rate limiter servers handle the same client.

Option A

Race Condition Solutions

  • Locks: simple but slow down system.
  • Lua scripts: atomic execution in Redis.
  • Sorted sets: efficient for sliding window log.
Option B

Synchronization Solutions

  • Sticky sessions: not scalable or flexible.
  • Centralized data store (e.g., Redis): scalable and consistent.
Interview tipUse centralized Redis to share state across rate limiter servers. Avoid sticky sessions.
04

Performance and Monitoring


Performance optimization includes multi-data center setup with edge servers to reduce latency, and eventual consistency for data synchronization. Monitoring ensures algorithms and rules are effective; adjust rules or switch to token bucket for burst traffic.

Edge servers
194
Cloudflare edge servers as of 5/20/2020
Q&A

Check yourself


Q1Which rate limiting algorithm allows bursts of traffic?
  • Token bucket
  • Leaking bucket
  • Fixed window counter
✓ Token bucket — Token bucket allows bursts as long as tokens are available.
Q2What is a major drawback of the fixed window counter algorithm?
  • High memory usage
  • Spikes at window edges can exceed quota
  • Complex implementation
✓ Spikes at window edges can exceed quota — Fixed window counter can allow more requests than allowed at window boundaries.
Q3In a distributed rate limiter, what is the recommended solution for synchronization?
  • Sticky sessions
  • Centralized data store like Redis
  • Local counters per server
✓ Centralized data store like Redis — Centralized Redis ensures consistent counters across multiple rate limiter servers.
Sources: Book, Ch. 4, Design a Rate Limiter (pp. 1-20)