Rate limiting is a critical defensive mechanism in modern software architecture, acting as a traffic cop for your APIs. Whether you are protecting a database from being overwhelmed, preventing brute-force login attempts, or monetizing an API by tier, rate limiting is the tool you reach for. In system design interviews, especially for mid-to-senior roles, simply stating "I will add a rate limiter" is never enough. Interviewers expect you to understand the underlying algorithms, their mathematical trade-offs, and how they behave in a distributed environment. This article breaks down everything you need to know to ace rate limiting discussions.
What is Rate Limiting and Why Does it Matter?
At its core, rate limiting restricts the number of events (usually HTTP requests or function calls) a particular entity can perform within a specified time window. If a user is allowed 100 requests per minute, the 101st request within that minute will be rejected or delayed.
Why do we need this?
- Preventing Resource Exhaustion: Servers have finite CPU, memory, and database connections. A sudden spike in traffic, whether malicious (DDoS) or accidental (a viral marketing campaign), can crash your system. Rate limiting ensures your system degrades gracefully rather than failing catastrophically.
- Cost Management: In the era of cloud computing and third-party APIs (like OpenAI's LLMs or AWS services), every request costs money. Rate limiting prevents runaway scripts from generating massive bills.
- Fairness: In a multi-tenant system, you don't want one noisy neighbor consuming 90% of your system's resources, starving other users.
- Security: Rate limiting mitigates brute-force attacks on login endpoints and scraping bots trying to steal your data.
How Rate Limiting Works
In a typical web architecture, the rate limiter sits at the edge of your network, often within an API Gateway or a dedicated middleware layer. It intercepts incoming requests, identifies the user (via IP address, API key, or user ID), and checks their current usage against the allowed limit.
When a request is rejected, the standard HTTP response is 429 Too Many Requests. Well-designed APIs also return specific HTTP headers to inform the client about their status, such as X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After.
The 5 Core Rate Limiting Algorithms
There is no single "best" rate limiting algorithm. The choice depends on your specific requirements regarding memory usage, accuracy, and how you want to handle bursts of traffic. Let's explore the five most common algorithms.
1. Token Bucket
The Token Bucket algorithm is arguably the most popular and widely used rate limiting algorithm (used by companies like Stripe and Amazon).
Imagine a bucket that can hold a maximum number of tokens (the capacity). Tokens are added to this bucket at a fixed rate (the refill rate). When a request arrives, it attempts to take a token from the bucket. If a token is available, the request is processed. If the bucket is empty, the request is dropped.
Pros:
- Allows bursts of traffic: If the bucket is full, a user can send a burst of requests up to the bucket's capacity.
- Memory efficient: You only need to store two variables per user: the number of tokens currently in the bucket and the timestamp of the last refill.
Cons:
- Tuning the two parameters (bucket size and refill rate) can be challenging depending on the traffic pattern.
Here is how you might implement a thread-safe Token Bucket in memory:
import time
import threading
class TokenBucket:
def __init__(self, capacity, refill_rate):
self.capacity = capacity
self.refill_rate = refill_rate # tokens per second
self.tokens = capacity
self.last_refill = time.time()
self.lock = threading.Lock()
def allow_request(self, tokens_needed=1):
with self.lock:
now = time.time()
# Calculate tokens to add based on time passed
time_passed = now - self.last_refill
new_tokens = time_passed * self.refill_rate
self.tokens = min(self.capacity, self.tokens + new_tokens)
self.last_refill = now
if self.tokens >= tokens_needed:
self.tokens -= tokens_needed
return True
return False2. Leaking Bucket
The Leaking Bucket algorithm is similar to the Token Bucket but focuses on smoothing out traffic. Imagine a bucket with a hole in the bottom. Water (requests) is poured into the top. If water is poured in faster than it leaks out, the bucket overflows, and new requests are dropped. The requests leak out of the bottom at a strictly constant rate.
In practice, this is usually implemented using a First-In-First-Out (FIFO) queue. Requests are added to the queue, and a background worker pulls requests from the queue at a fixed rate.
Pros:
- Smooths traffic: It enforces a strictly constant output rate, which is excellent if your backend database cannot handle bursts at all.
- Memory efficient: The queue size is fixed.
Cons:
- Bursts are penalized: A sudden burst of legitimate traffic will fill the queue, causing subsequent requests to be dropped or severely delayed, even if the system is currently idle.
3. Fixed Window Counter
This is the simplest algorithm. Time is divided into fixed windows (e.g., 12:00:00 to 12:01:00, 12:01:00 to 12:02:00). Each window has a counter. When a request comes in, the counter for the current window is incremented. If the counter exceeds the limit, requests are dropped until the next window begins.
Pros:
- Extremely simple to implement: You just need a key-value store where the key is
user_id + timestamp_minute. - Memory efficient: Only one counter per user per window.
Cons:
- The Edge Case Spike: This is the critical flaw. Imagine a limit of 100 requests per minute. A user sends 100 requests at 12:00:59, and another 100 requests at 12:01:01. The user has just sent 200 requests in a 2-second window, completely bypassing the intended 100/min limit. This can overwhelm your servers.
4. Sliding Window Log
To solve the edge-case spike of the Fixed Window, the Sliding Window Log algorithm keeps a precise log of timestamps for every single request a user makes.
When a new request arrives, the algorithm removes all timestamps older than the time window (e.g., older than 1 minute ago). It then counts the remaining timestamps. If the count is below the limit, the new request's timestamp is added to the log, and the request is allowed.
Pros:
- Perfect accuracy: It completely eliminates the edge-case spike. The rate limit is strictly enforced at any rolling fraction of time.
Cons:
- High memory footprint: You must store the timestamp of every request. If the limit is 10,000 requests per hour, you are storing 10,000 timestamps per user.
- High computational cost: Cleaning up old logs and counting elements on every request is expensive, especially at scale.
5. Sliding Window Counter
This algorithm is a hybrid that combines the low memory footprint of the Fixed Window Counter with the accuracy of the Sliding Window Log. It uses the counters from the previous and current fixed windows to estimate the traffic in the rolling window.
Here is the formula:
Estimated Requests = (Requests in Previous Window * Overlap Percentage) + Requests in Current Window
Example: Let's say the limit is 100 requests per minute.
- In the previous minute (12:00 - 12:01), the user made 80 requests.
- In the current minute (12:01 - 12:02), the user has made 20 requests so far.
- A new request arrives at exactly 12:01:15 (which is 25% into the current minute).
The overlap with the previous minute is 75% (since we are 25% into the new minute, 75% of our rolling 60-second window falls in the previous minute).
Estimated Requests = (80 * 0.75) + 20 = 60 + 20 = 80
Since 80 is less than 100, the request is allowed.
Pros:
- Memory efficient: Only requires storing two counters per user.
- Smooths edge spikes: Significantly reduces the burst effect seen in the pure Fixed Window approach.
Cons:
- Slightly inaccurate: It assumes that traffic in the previous window was evenly distributed. In reality, all 80 requests in the previous window might have happened at 12:00:59. However, for large volumes of traffic, this approximation is statistically very accurate (usually over 99% accurate).
Comparison of Algorithms
| Algorithm | Memory Usage | Accuracy | Best For |
|---|---|---|---|
| Token Bucket | Low (2 variables) | High | General purpose APIs, allowing bursts. |
| Leaking Bucket | Medium (Queue) | High | Protecting fragile backends, strict smoothing. |
| Fixed Window | Low (1 counter) | Low (Edge spikes) | Simple use cases, daily quotas. |
| Sliding Window Log | High (All timestamps) | Perfect | High-security endpoints (e.g., login). |
| Sliding Window Counter | Low (2 counters) | Very High | High-scale APIs needing accuracy without memory bloat. |
Trade-offs and Distributed Systems Challenges
Implementing a rate limiter in a single-node application is trivial (as seen in the code blocks above). However, in the real world, your API is deployed across dozens of servers behind a load balancer. This introduces significant distributed systems challenges.
1. Data Store Selection
If Server A and Server B both handle requests for User X, they need a shared source of truth for the rate limit counters. A relational database (SQL) is too slow for this. You need an in-memory cache.
Redis is the industry standard for distributed rate limiting. It is incredibly fast, operates in memory, and supports atomic operations.
2. Race Conditions
Imagine User X has 1 token left. They send two requests simultaneously.
- Server A reads the token count (1).
- Server B reads the token count (1).
- Server A decrements to 0 and allows the request.
- Server B decrements to 0 and allows the request.
You just allowed 2 requests when only 1 should have been allowed. This is a classic race condition.
Solutions:
- Locks: You could use distributed locks, but they introduce massive latency and bottleneck your system.
- Redis INCR: For fixed window counters, you can use Redis's atomic
INCRcommand. - Lua Scripts: For more complex algorithms like Token Bucket, you can write a Lua script and execute it on Redis. Redis executes Lua scripts atomically, guaranteeing that no other operations run concurrently. This is the most common and performant solution.
3. Latency Overhead
Adding a network hop to Redis for every incoming API request adds latency (typically 1-3ms). To mitigate this, some systems use a local cache on each server and periodically sync with the global Redis cache. This trades strict accuracy for lower latency (eventual consistency).
4. Failure Modes (Fail-Open vs. Fail-Closed)
What happens if your Redis cluster goes down?
- Fail-Closed: You reject all traffic. Your system is completely down until Redis recovers.
- Fail-Open: You allow all traffic through, bypassing the rate limiter.
Usually, fail-open is the preferred strategy. It is better to risk overloading the backend than to guarantee 100% downtime for your users. You can mitigate the risk by having a fallback local rate limiter on the API gateway that activates when Redis is unreachable.
Real-World Implementations
- Stripe: Uses the Token Bucket algorithm backed by Redis. They actually use multiple rate limiters in series (e.g., one for the specific endpoint, one for the user's overall account, and one for the IP address).
- API Gateways: Tools like Kong, Nginx, and AWS API Gateway have built-in rate limiting modules, usually utilizing sliding window counters or token buckets.
- Throttling Dimensions: Real systems rarely limit just by User ID. They limit by
[IP Address],[User ID],[API Key], and[Endpoint]. For example, a user might be allowed 1000 requests/min globally, but only 5 requests/min to the/export-dataendpoint.
Interview Questions
Here are the types of questions you can expect in a system design interview, along with model answers.
1. How do you handle race conditions in a distributed rate limiter?
Model Answer: I would use Redis as the centralized data store. To prevent race conditions without the performance penalty of distributed locks, I would use Redis Lua scripts. Redis guarantees that Lua scripts are executed atomically, meaning the read, evaluate, and update steps of a Token Bucket algorithm happen as a single, uninterrupted operation.
2. We have a strict requirement that users cannot exceed their limit at any given rolling second, but we have millions of users. Which algorithm do you choose?
Model Answer: Since strict accuracy in a rolling window is required, Fixed Window is out. Sliding Window Log provides perfect accuracy but storing timestamps for millions of users would consume too much memory. Therefore, I would choose the Sliding Window Counter. It provides a highly accurate approximation of the rolling window while only requiring the storage of two integers per user, making it highly memory-efficient at scale.
3. What happens to your system if the Redis cache used for rate limiting crashes?
Model Answer: I would design the system to "fail-open." If the API gateway cannot reach Redis within a strict timeout (e.g., 5ms), it should allow the request to pass through to the backend. While this risks a temporary overload, failing closed would cause a complete outage. To protect the backend during a Redis outage, I would implement a fallback, in-memory rate limiter on the API gateway nodes themselves with a conservative threshold.
4. How would you rate limit requests from an IP address that is shared by hundreds of users (like a corporate NAT or a university)?
Model Answer: Rate limiting strictly by IP address can lead to false positives, blocking legitimate users sharing a NAT. I would use a multi-dimensional approach. If the user is authenticated, I rate limit by User ID or API Key. I would only use IP-based rate limiting as a broad defense against unauthenticated DDoS attacks, and I would set the IP limits much higher than the user-level limits.
5. How do you communicate rate limit status to the client?
Model Answer: I would use standard HTTP headers. X-RateLimit-Limit to show their total quota, X-RateLimit-Remaining to show how many requests they have left in the current window, and X-RateLimit-Reset to indicate the UNIX timestamp when their quota will replenish. If they exceed the limit, I will return a 429 Too Many Requests status code with a Retry-After header.
6. Can you explain the difference between Token Bucket and Leaking Bucket?
Model Answer: Token Bucket allows for bursts of traffic up to the bucket's capacity, making it good for general APIs where users might send a batch of requests at once. Leaking Bucket enforces a strict, constant output rate, smoothing out bursts entirely. Leaking Bucket is better when the downstream service is fragile and requires a perfectly steady stream of traffic.
Common Mistakes
- Ignoring Latency: Proposing a relational database to store rate limit counters. SQL databases cannot handle the read/write throughput required for rate limiting at scale. Always use an in-memory store like Redis or Memcached.
- Over-engineering: Reaching for Sliding Window Log when Fixed Window is perfectly adequate for the business requirements. If the limit is "1000 API calls per day for billing purposes," a simple Fixed Window is best. Save the complex algorithms for high-frequency, per-second limits.
- Forgetting about Client Experience: Failing to mention HTTP 429 and the
Retry-Afterheaders. An API that just drops connections or returns 500s when rate limited is a poorly designed API. - Not asking clarifying questions: If an interviewer says "Design a rate limiter," you must ask: Is this for a single machine or distributed? What is the scale? Are we limiting by IP or User ID? Do we need to support bursts? (See more on this in our guide on thinking aloud in coding interviews).
Mastering rate limiting is a guaranteed way to score points in a system design interview. By understanding the math behind the algorithms and the realities of distributed caching, you can demonstrate that you know how to build systems that are not just scalable, but resilient.