Imagine you are building the backend for a massive flash sale on an Indian e-commerce platform. Millions of users hit your API simultaneously the second the sale goes live. Without a rate limiter, your backend services would be overwhelmed, databases would lock up, and the entire system would crash. A rate limiter acts as the bouncer for your API, controlling the rate of traffic sent by a client or a service. It prevents resource starvation, mitigates DDoS attacks, and helps enforce tiered pricing models.
Requirements (functional and non-functional)
Before jumping into the architecture, we need to clearly define what our rate limiter is expected to do.
Functional Requirements
- Allow/Deny Requests: The system should take an incoming request and return a boolean indicating whether the request should be processed or blocked.
- Rule Enforcement: It must support rules based on various dimensions (e.g., 100 requests per minute per
user_id, or 50 requests per second perIP_address). - Client Feedback: When a request is throttled, the system should inform the client by returning an HTTP
429 Too Many Requestsstatus code, ideally with headers indicating when they can retry (X-RateLimit-Reset).
Non-functional Requirements
- Extremely Low Latency: The rate limiter is on the critical path of every API request. It should add minimal latency (ideally < 5ms).
- High Availability: If the rate limiter goes down, it should not take the entire API down with it (fail-open strategy).
- Scalability: It must handle high throughput, scaling seamlessly as API traffic increases.
- Accuracy: In a distributed environment with multiple API gateway instances, the rate limit counts must be as accurate as possible without severely compromising latency.
Capacity estimates
Let's assume we are designing for a large-scale application like a popular UPI payment app or a food delivery service.
- Traffic: 100 million Daily Active Users (DAU).
- Throughput: On average, a user makes 10 requests per day.
- Average RPS = (100M * 10) / 86400 ≈ 11,500 RPS.
- Peak RPS (during lunch hours or flash sales) = 10x Average ≈ 115,000 RPS.
- Memory sizing (Redis): We need to store counters. Let's assume we use a Fixed Window algorithm.
- Key:
user_id:endpoint:timestamp(approx 32 bytes). - Value: Counter (4 bytes).
- Total per active user window: ~36 bytes.
- If 10 million users are active in a given minute: 10M * 36 bytes ≈ 360 MB.
- This easily fits into the RAM of a single Redis node, though we will use a cluster for high availability and throughput.
- Key:
API design
The rate limiter is typically an internal service called by the API Gateway. We can use a fast RPC framework like gRPC, but for simplicity, here is the conceptual API:
isAllowed(client_identifier, api_endpoint, rate_limit_rules)
client_identifier: Can be auser_id,API_key, orIP_address.api_endpoint: The specific API route being accessed (e.g.,/v1/orders/create).rate_limit_rules: The threshold and window (e.g.,[100, "1M"]for 100 requests per minute).
Returns:
allowed(boolean):trueif the request can proceed.current_usage(integer): How many requests the user has made.retry_after(integer): Seconds until the window resets (useful for HTTP 429 headers).
Data model
Since we need sub-millisecond read/write access, a traditional relational database (SQL) is too slow. We need an in-memory Key-Value store. Redis is the industry standard for this.
The data model depends on the algorithm, but for a standard counter-based approach, the key structure looks like this:
rate_limit:{identifier}:{endpoint}:{window_timestamp}
For example, if user U123 accesses /api/checkout at 10:05 AM, and the limit is per minute, the Redis key would be:
rate_limit:U123:/api/checkout:1697018700
The value stored at this key is a simple integer that increments with each request. We also set a Time-To-Live (TTL) on this key equal to the window size so Redis automatically cleans up old data.
High-level architecture
Here is how the components interact in a production environment:
- The client sends a request to the Load Balancer, which routes it to the API Gateway.
- The API Gateway invokes the Rate Limiter Middleware.
- The middleware queries the Redis Cluster (either directly or via a dedicated Rate Limiter Service) to check if the limit is exceeded.
- If the limit is exceeded, the Gateway short-circuits the request and returns
429 Too Many Requests. - If allowed, the request is forwarded to the Backend Microservices.
Deep dives
1. Choosing the right algorithm
There are several algorithms for rate limiting, each with distinct trade-offs.
| Algorithm | Pros | Cons |
|---|---|---|
| Token Bucket | Smooths out bursts, memory efficient. | Requires complex concurrent token refilling logic. |
| Leaking Bucket | Enforces a strict, constant processing rate. | Bursts of traffic are dropped immediately if the queue is full. |
| Fixed Window Counter | Very easy to implement, memory efficient. | Suffers from the "boundary problem" (2x traffic allowed at the edge of windows). |
| Sliding Window Log | 100% accurate. | High memory usage (stores a timestamp for every request). |
| Sliding Window Counter | Good balance of accuracy and memory. | Slightly more complex to implement. |
For most distributed systems, Token Bucket or Fixed Window Counter (with small windows) are the most practical. If you want to dive deeper into how each of these works mathematically, check out our article on rate-limiting-algorithms.
2. Handling Race Conditions in a Distributed Environment
This is the most critical part of the interview. If you have 10 instances of your API Gateway, and a user sends 10 concurrent requests, all gateways might read the Redis counter simultaneously. They all read current_count = 99, increment it locally, and write back 100. The user just bypassed your 100-request limit and made 109 requests!
Solution: We must use atomic operations. Redis provides INCR, which is atomic. However, we also need to set an expiration (EXPIRE) on the key the first time it is created. To ensure both INCR and EXPIRE happen atomically without multiple network round trips, we use Redis Lua Scripts.
Redis guarantees that Lua scripts are executed atomically. No other script or Redis command will be executed while a script is running.
Here is how you implement an atomic Fixed Window counter in different languages using Lua:
import time
import redis
class RateLimiter:
def __init__(self, redis_client):
self.redis = redis_client
# Lua script executes atomically in Redis
self.lua_script = """
local current = redis.call("INCR", KEYS[1])
if current == 1 then
redis.call("EXPIRE", KEYS[1], ARGV[1])
end
if current > tonumber(ARGV[2]) then
return 0
end
return 1
"""
self.script = self.redis.register_script(self.lua_script)
def is_allowed(self, user_id, limit, window_sec):
current_window = int(time.time() // window_sec)
key = f"rate_limit:{user_id}:{current_window}"
# Returns 1 if allowed, 0 if blocked
return self.script(keys=[key], args=[window_sec, limit]) == 13. Latency vs. Consistency Trade-offs
Even with Redis, making a network call for every single incoming request adds latency. If Redis is in a different availability zone, this could add 2-5ms per request. At 115,000 RPS, this network I/O becomes a massive bottleneck.
To optimize this, we can introduce Local Caching with Eventual Consistency.
Instead of hitting Redis for every request, the API Gateway keeps a local in-memory counter. It increments this local counter and only syncs with the central Redis cluster periodically (e.g., every 1 second or every 10 requests).
The Trade-off: By syncing asynchronously, we gain massive performance improvements (zero network latency on the critical path). However, we sacrifice strict accuracy. If the limit is 100, a user might be able to sneak in 110 requests before the local caches sync with Redis and realize the limit was breached. For most businesses, allowing a slight overage is perfectly acceptable in exchange for a blazing-fast API.
Bottlenecks and trade-offs
- Single Point of Failure: If the Redis cluster goes down, the rate limiter cannot function.
- Mitigation: Implement a Fail-Open strategy. If the API Gateway cannot reach Redis within a strict timeout (e.g., 10ms), it should assume the request is allowed. It is better to temporarily overload the backend than to drop 100% of legitimate user traffic.
- Clock Synchronization: If you use a Fixed Window algorithm relying on timestamps, clock drift between different API Gateway servers can cause inaccurate rate limiting.
- Mitigation: Rely on the centralized Redis server's clock, or use NTP (Network Time Protocol) to keep server clocks tightly synchronized.
- Hot Keys: If a single IP or user is maliciously spamming the system (e.g., a DDoS attack), the specific Redis shard holding that user's counter will become a bottleneck.
- Mitigation: The API Gateway's local cache (L1 cache) will quickly realize this user is blocked and can drop the requests locally without even querying Redis for the remainder of the window.
Questions an interviewer will ask next
1. How do you handle rate limiting by IP address vs. User ID? Answer: IP-based limiting is good for unauthenticated traffic (e.g., login endpoints to prevent brute force), but it penalizes users sharing a NAT/Corporate network. User ID-based limiting is better for authenticated traffic. In practice, you use both: a generous IP limit to prevent DDoS, and a stricter User ID limit for business logic.
2. What if our application is deployed across multiple global regions (e.g., India and US)? Answer: Cross-region Redis replication is too slow for strict rate limiting. We should maintain separate rate limiters per region. If a user's global limit is 100, we can either divide the quota (50 per region) or accept that they might get 100 per region. If strict global consistency is required, we must use a globally replicated datastore like Spanner or CosmosDB, accepting the latency hit.
3. How would you implement tiered pricing (e.g., Free users get 100 req/min, Premium users get 1000 req/min)?
Answer: The API Gateway would first fetch the user's tier from a fast cache (like a JWT token or a user-profile Redis cache). It then passes the dynamic limit as a parameter to the isAllowed function, rather than hardcoding a global limit.