Design a Rate Limiter: System Design Interview Guide
Master the rate limiter system design interview.
20+ years shipping production code across the stack, with years spent interviewing engineers. Drawn from code that ran under real load.
- ✓Basic understanding of system design concepts (load balancing, caching, distributed systems).
- ✓Familiarity with Redis or similar in-memory data stores.
- ✓Knowledge of HTTP status codes (429 Too Many Requests).
- Rate limiters control the rate of requests to protect backend services.
- Common algorithms: Token Bucket, Leaky Bucket, Fixed Window, Sliding Window Log, Sliding Window Counter.
- Distributed rate limiting requires a shared store like Redis and consistency considerations.
- Key design decisions: accuracy vs. memory, centralized vs. decentralized enforcement.
- Interview tip: start with requirements, then algorithm choice, then scaling.
Imagine a nightclub with a capacity limit. The bouncer (rate limiter) lets in only a certain number of people per minute. If too many try to enter, they are turned away. In computing, the rate limiter does the same for requests, preventing servers from being overwhelmed.
Rate limiting is a critical component in modern distributed systems. It protects APIs and services from abuse, ensures fair usage, and maintains system stability. In system design interviews, designing a rate limiter is a classic question that tests your understanding of algorithms, distributed systems, and trade-offs. This guide will walk you through everything you need to know: from basic algorithms like token bucket and sliding window to advanced distributed implementations using Redis. You'll also learn how to handle edge cases, common pitfalls, and how to articulate your design under interview pressure. By the end, you'll be ready to tackle any rate limiter question with confidence.
Requirements and Constraints
Before diving into algorithms, clarify the requirements. Ask your interviewer: What are we rate limiting? (e.g., API requests per user per second). What is the scale? (e.g., millions of users). Should the rate limiter be accurate or memory-efficient? Do we need to support burst traffic? Typical requirements: limit requests per user, per IP, or globally; low latency (sub-millisecond); high throughput; distributed across multiple servers; handle bursts gracefully. Non-functional: availability, durability of rate limit state, consistency (eventual vs strong).
Rate Limiting Algorithms
Several algorithms exist, each with trade-offs. Token Bucket: a bucket holds tokens that refill at a fixed rate. Each request consumes a token. Allows bursts up to bucket size. Leaky Bucket: requests are processed at a constant rate, with a queue for overflow. Fixed Window: count requests in a time window (e.g., 1 minute). Simple but can allow bursts at window boundaries. Sliding Window Log: keep a log of timestamps for each request; count requests in the last window. Accurate but memory-intensive. Sliding Window Counter: combine fixed window with a sliding average; more memory efficient. For interviews, token bucket and sliding window counter are popular choices.
Distributed Rate Limiting with Redis
For distributed systems, a centralized store like Redis is common. Use Redis INCR with expiry to implement a sliding window counter. For token bucket, store token count and last refill timestamp in Redis. Use Lua scripting for atomic operations. Example: a sorted set for sliding window log. Considerations: Redis is single-threaded, so Lua scripts are atomic. Network latency adds overhead; consider using local counters with periodic sync for lower latency. Also handle Redis failures gracefully (e.g., fallback to local rate limiting).
Handling Burst Traffic and Edge Cases
Burst traffic can overwhelm a system if not handled. Token bucket naturally allows bursts up to bucket size. For sliding window, bursts at window boundaries can double the rate. Mitigation: use a smaller window or add a jitter. Edge cases: clock skew between servers (use NTP), race conditions (use locks or atomic operations), and large number of keys (use sharding). Also consider rate limiting at different layers: API gateway, application, and database. For interview, discuss how you would handle a sudden spike in traffic (e.g., viral event).
System Design: High-Level Architecture
A typical rate limiter sits in the API gateway. For each request, extract the client identifier (user ID, IP, API key). Check the rate limit in a cache (Redis). If allowed, forward the request; else return 429. For high availability, use Redis cluster with replicas. For low latency, use local counters with periodic sync (eventual consistency). Also consider a two-tier approach: local token bucket for first line, Redis for global coordination. Discuss trade-offs: accuracy vs. performance, consistency vs. availability.
Interview Tips and Follow-Up Questions
In an interview, start with requirements, then propose an algorithm, then discuss scaling. Be prepared for follow-ups: How do you handle rate limiting for unauthenticated users? (Use IP address). How do you prevent a user from creating many accounts? (Use device fingerprint). How do you handle rate limit headers? (Return X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset). Also discuss how to test your rate limiter (unit tests, load tests). Finally, mention monitoring and alerting (e.g., track 429 rate).
The Twitter API Rate Limit Meltdown
- Always test rate limiter logic with automated tests, especially around window boundaries.
- Monitor rate limiter metrics (e.g., number of 429s) to detect anomalies.
- Implement a circuit breaker to fall back to a safe mode if the rate limiter itself fails.
- Use canary deployments for critical infrastructure changes.
- Document the exact algorithm and configuration for operational teams.
curl -I https://api.example.com/endpoint | grep -i 'x-ratelimit'redis-cli get rate_limiter:user123| File | Command / Code | Purpose |
|---|---|---|
| token_bucket.py | class TokenBucket: | Rate Limiting Algorithms |
| redis_sliding_window.lua | local key = KEYS[1] | Distributed Rate Limiting with Redis |
Key takeaways
Common mistakes to avoid
3 patternsUsing fixed window without considering boundary bursts
Not handling clock skew in distributed systems
Storing rate limit state in a database instead of cache
Interview Questions on This Topic
Design a rate limiter for a social media API that handles 1 million requests per second.
Frequently Asked Questions
20+ years shipping production code across the stack, with years spent interviewing engineers. Drawn from code that ran under real load.
That's System Design Interview. Mark it forged?
3 min read · try the examples if you haven't