We are going to design a comprehensive rate limiting and throttling system that includes multiple algorithms and considerations.
We'll cover:
- Token Bucket
- Leaky Bucket
- Sliding Window
- Distributed Counters (using Redis)
- Per-user/IP keys
- Burst handling
- Idempotency
- Backoff (on client side, but we can provide server-side hints)
- Observability (metrics, logging)
We'll provide example configurations and code snippets in Python using popular libraries where applicable.
Note: For distributed systems, we assume the use of Redis for shared state.
Let's break it down:
-
Token Bucket:
- Tokens are added at a fixed rate to a bucket (capacity).
- Each request consumes a token. If no token, reject or wait.
-
Leaky Bucket:
- Requests are queued and processed at a fixed rate. If queue is full, reject.
-
Sliding Window:
- Tracks the number of requests in a time window that slides.
-
Distributed Counters (Redis):
- Using Redis to store counters with expiration (for fixed window) or sorted sets (for sliding window).
-
Per-user/IP keys:
- Keys in the rate limiter should include user identifier or IP address.
-
Burst handling:
- Allow temporary bursts by having a bucket capacity or queue.
-
Idempotency:
- For safe retries, we can use idempotency keys (client provided) to avoid duplicate processing.
-
Backoff:
- When rate limited, the client should back off. We can provide Retry-After header.
-
Observability:
- Metrics: number of allowed/blocked requests, current bucket levels, etc.
- Logging: when a request is blocked.
We'll implement:
- A base class for rate limiters.
- TokenBucketLimiter (in-memory and Redis-backed)
- LeakyBucketLimiter (in-memory and Redis-backed)
- SlidingWindowLimiter (Redis-backed with sorted set)
However, note that for distributed systems, we need a distributed version of each.
Let's start with a simple in-memory token bucket for a single process.
But note: the requirement is for distributed counters (Redis) so we'll focus on that for the distributed ones.
We'll use the redis library for Redis examples.
Let's design:
For Token Bucket (distributed):
We can use a Redis key that stores:
- tokens: current number of tokens (float or integer)
- last_update: timestamp of last refill
However, this requires a critical section (using Redis locks or Lua script) to avoid race conditions.
Alternatively, we can use a Redis script (Lua) to atomically update and check.
Steps in the script:
1. Get current tokens and last_update from the key (or set defaults if not exists).
2. Calculate the new tokens based on the time passed: tokens = min(capacity, tokens + (now - last_update) * refill_rate)
3. If tokens >= required_tokens, subtract and set last_update to now, return allowed.
4. Else, return current tokens (or 0) and not allowed.
But note: we want to allow bursts, so the bucket has a capacity.
We'll write a Lua script for this.
Similarly, for Leaky Bucket (distributed):
We can model the leaky bucket as a queue with a fixed processing rate.
However, in a distributed setting, we might use a Redis list (as a queue) and a separate process to leak (pop and process) at a fixed rate.
But for rate limiting at the API gateway level, we might not want to queue requests (we want to reject when full). So we can use a fixed-size queue (list) and when the queue is full, reject.
Alternatively, we can use a token bucket for the same effect (burst handling). So maybe we don't need both.
Since token bucket is more common for API rate limiting, we might focus on that.
But the requirement says to implement both, so we'll do:
Leaky Bucket (distributed) as a fixed-size queue (using Redis list) with a background process that pops at a fixed rate? That's not typical for request rate limiting.
Actually, for request rate limiting, we usually don't queue; we reject. So the leaky bucket algorithm for rate limiting is often implemented as:
- Calculate the expected departure time of the last request and then see if the current request would exceed the rate.
But again, for distributed, we need atomicity.
Alternatively, we can use a Redis sorted set to store the timestamps of the requests and then remove the old ones (leaked) and check the count.
That's similar to sliding window.
Given the complexity and the fact that token bucket and sliding window are more common, we'll implement:
- Token Bucket (distributed) with Redis and Lua.
- Sliding Window (distributed) with Redis sorted set.
For Leaky Bucket, we can note that it's less common in distributed systems for request limiting because of the queueing requirement.
But if we must, we can implement a fixed window counter with a queue length? Not exactly.
Let me think: the leaky bucket algorithm for rate limiting is often:
- If the time since the last request is less than 1/rate, then reject.
But that doesn't allow bursts. Alternatively, we can have a queue of fixed length and a fixed rate of processing.
For an API gateway, we don't want to hold requests (we want to reject). So we can use a token bucket.
Since the requirement says to implement both, I'll provide a LeakyBucketLimiter that uses a fixed window counter and then calculate the allowed requests based on the time of the last request? That's not a leaky bucket.
Alternatively, we can use a Redis sorted set to store the request timestamps and then remove those that are older than the window and then check if the count exceeds the rate? That's sliding window.
Given the confusion, I'll stick to:
- Token Bucket (with burst)
- Sliding Window (without burst, but with a window)
And for Leaky Bucket, we can note that it's equivalent to a fixed rate with a queue, but for rate limiting we usually don't queue.
So, I'll skip the Leaky Bucket for distributed because it's not typical.
However, if we must, we can implement:
LeakyBucketLimiter:
We maintain a Redis key that is a list (queue) of request timestamps? But we don't want to store every request.
Alternatively, we can use a fixed window counter and then calculate the allowed requests based on the time elapsed since the last request? That's a different algorithm.
Given the time, I'll focus on:
- TokenBucketLimiter (distributed)
- SlidingWindowLimiter (distributed)
And we can also have a FixedWindowLimiter (which is a special case of sliding window with no滑动).
But the requirement says sliding window, so we'll do that.
-
Sliding Window:
We can use a Redis sorted set (with timestamps as scores) for each key (user/IP). We add the current timestamp for each request and then remove those that are older than the window. Then we check the count.
Steps:
current_time = now()
key = "rate_limit:{identifier}:{window}"
Use ZREMRANGEBYSCORE to remove entries older than current_time - window
Then ZCARD to get the count.
If count < limit, then ZADD the current timestamp and return allowed.
But note: this can be heavy if there are many requests because we are storing every request.
Alternatively, we can use a fixed window counter with multiple windows (like 1 minute broken into 60 seconds) to approximate sliding window.
However, for accuracy, we use sorted set.
We can also use a Redis HyperLogLog? But that's for unique counts and not time-based.
So we'll use sorted set.
-
Distributed Counters:
We are using Redis for both token bucket and sliding window.
-
Per-user/IP keys:
We'll construct the Redis key as: f"rate_limit:{limiter_name}:{identifier}"
-
Burst handling:
Token bucket naturally handles bursts.
Sliding window does not, unless we use a token bucket on top.
-
Idempotency:
We can use an idempotency key (provided by client) to avoid duplicate processing. But that's a separate concern from rate limiting.
However, we can combine: if a request with the same idempotency key is retried, we don't count it again.
We can store the idempotency key in a set with expiration? But then we have to store every idempotency key.
Alternatively, we can have a separate idempotency service.
Since the requirement is about rate limiting, we'll note that idempotency keys should not be counted multiple times.
We can do:
Check if the idempotency key (if provided) has been seen in the last X time (for the same endpoint and user). If yes, then return the same response without counting.
But that's a separate cache.
We'll leave idempotency as a note: use a separate cache (like Redis) to store idempotency keys with a TTL.
-
Backoff:
When rate limited, we return 429 with Retry-After header.
-
Observability:
We'll log when a request is blocked and increment metrics.
We can use Prometheus metrics.
Let's code:
We'll create:
class RateLimiter:
def allow(self, identifier: str) -> bool: ...
Then:
class TokenBucketRateLimiter(RateLimiter):
def init(self, rate: float, capacity: int, redis_client=None, key_prefix="token_bucket"):
# rate: tokens per second
# capacity: max tokens in bucket
# If redis_client is None, use in-memory (but not distributed)
But note: we want distributed, so we'll require Redis.
However, for completeness, we can have an in-memory version for single process.
Let's do:
If redis_client is provided, use Redis (distributed), else use in-memory (non-distributed).
Similarly for SlidingWindowRateLimiter.
But note: the requirement says distributed counters (e.g., Redis), so we'll focus on Redis.
We'll write:
- token_bucket.lua (the Lua script) and load it in Redis.
Alternatively, we can write the Lua script as a string and use EVAL.
Let's write the Lua script for token bucket:
KEYS[1] = key (the bucket key)
ARGV[1] = rate (tokens per second)
ARGV[2] = capacity (max tokens)
ARGV[3] = now (current time in seconds with fractions)
ARGV[4] = requested (number of tokens requested)
Steps:
1. Get current tokens and last_update from the key (if not exists, set tokens=capacity, last_update=now)
2. Calculate delta_time = now - last_update
3. new_tokens = tokens + delta_time * rate
4. if new_tokens > capacity: new_tokens = capacity
5. if new_tokens >= requested:
tokens = new_tokens - requested
last_update = now
set key with tokens and last_update
return 1 (allowed)
else:
set key with new_tokens and last_update? Actually, we should update the tokens to new_tokens (so that we don't lose the accumulated tokens) but not subtract.
So: set tokens = new_tokens, last_update = now? But then if we don't allow, we still update the last_update? That would reset the refill.
Actually, we should update the token count to the new_tokens (so that next time we have the correct amount) but we don't change the last_update? Wait, we are using the last_update to know when we last refilled. If we don't allow, we don't consume, but we still want to update the token count to the new_tokens (because time has passed). So we update the tokens to new_tokens and set last_update to now? That would mean that the next refill will be from now, which is correct.
But then if we don't allow, we update the bucket to have new_tokens and set the last_update to now. That's correct because the tokens have refilled until now.
However, if we allow, we set last_update to now and subtract tokens.
So in both cases, we set last_update to now and tokens to either new_tokens (if not allowed) or new_tokens - requested (if allowed).
But wait, if we are not allowed, we don't want to update the last_update? Actually, we do because we are recording the time of this request? But then if we don't allow, we are not consuming, but we are updating the bucket to reflect the time passed? That's correct.
However, note: if we are not allowed, we are not consuming, so the tokens should be set to new_tokens (which is the refilled amount until now) and then we set last_update to now. That way, the next request will start from now.
So:
if new_tokens >= requested:
tokens = new_tokens - requested
allowed = 1
else:
tokens = new_tokens
allowed = 0
Then set: key -> {tokens, last_update=now}
But note: we are setting last_update to now even if not allowed? Yes, because we are updating the bucket state to reflect the current time.
However, consider: if we have a burst of requests that are denied, we are updating the bucket on every denied request? That might be heavy.
Alternatively, we can update the bucket only when we allow? But then the token count might be stale.
Actually, we want the token count to be up to date for the next request, so we should update on every request.
But that could cause a lot of writes to Redis.
We can try to avoid updating if not necessary? But the calculation depends on the time passed.
Alternatively, we can use a different approach: store the last_update and tokens, and on each request, we calculate the new tokens and then if we allow, we update. If we don't allow, we don't update? But then the next request will use the old last_update and calculate a bigger delta? That would be incorrect because the time has passed.
So we must update the bucket state on every request.
However, we can use a Redis key that stores a hash with two fields: tokens and last_update.
We'll do:
local tokens = redis.call('HGET', KEYS[1], 'tokens')
local last_update = redis.call('HGET', KEYS[1], 'last_update')
if tokens == false then
tokens = capacity
last_update = now
else
tokens = tonumber(tokens)
last_update = tonumber(last_update)
end
local delta_time = now - last_update
local new_tokens = tokens + delta_time * rate
if new_tokens > capacity then
new_tokens = capacity
end
local allowed = 0
if new_tokens >= requested then
tokens = new_tokens - requested
allowed = 1
else
tokens = new_tokens
end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'last_update', now)
redis.call('EXPIRE', KEYS[1], 3600) -- or some TTL to clean up
return allowed
But note: we are using HMSET (deprecated) and EXPIRE. We can use HSET and EXPIRE separately.
Alternatively, we can set the TTL when we create the key? But we want to set TTL on every update? That might be heavy.
We can set a TTL when the key is created and then not update it? But then if the key is updated, the TTL resets? Actually, we want the key to expire if not used for a while.
We can set the TTL to, say, 2*capacity/rate? But if the rate is low, that could be long.
Alternatively, we can set the TTL to the time it takes to fill the bucket? But then if the bucket is full, we might not update for a while.
We can set a fixed TTL (like 1 hour) and then on every update, we reset the TTL? That might be acceptable.
But note: if we have many keys, we don't want to set TTL on every request.
We can set the TTL only when the key is created? But then if the key is not used for a while, it will stay.
We can use a Redis key event to clean up? Not necessary.
Alternatively, we can not set TTL and let the keys accumulate? That's bad.
So we set TTL on every update? That's O(1) but still a write.
We can set the TTL to a multiple of the window? For example, if the bucket can hold 1 minute of tokens, then set TTL to 2 minutes.
Let's do: TTL = capacity / rate * 2? But if rate is 0? We assume rate>0.
We'll set TTL = capacity / rate * 2, but at least 60 seconds.
However, if the bucket is full and not used, we still want it to expire.
We can do:
ttl = math.max(60, capacity / rate * 2)
But note: if rate is 1000 tokens per second and capacity is 1000, then ttl=2 seconds? That might be too short.
Alternatively, we can set a fixed TTL (like 1 hour) and then on every update, we reset the TTL? That's simpler.
Let's do:
redis.call('EXPIRE', KEYS[1], 3600)
on every update.
But note: if we have many keys, this might be heavy. However, for rate limiting, we don't have that many keys (per user/IP).
We'll do:
redis.call('EXPIRE', KEYS[1], 3600)
Now, for the sliding window:
We'll use a sorted set.
Steps:
current_time = now()
key = "sliding_window:{identifier}:{window}" # window in seconds
Remove all elements with score < current_time - window
Count = ZCARD key
If count < limit:
ZADD key current_time
EXPIRE key window * 2? (to allow for the window to pass and then some extra)
return 1
else:
return 0
But note: ZREMRANGEBYSCORE is O(log(N)+M) where M is the number of removed elements. This can be heavy if we have many requests.
Alternatively, we can use a fixed window with multiple buckets (like 1 minute window broken into 60 seconds) but that's an approximation.
We'll use the sorted set for accuracy.
We can also set a TTL on the key: window * 2.
Now, let's code:
We'll have:
class RedisTokenBucketRateLimiter:
def init(self, rate: float, capacity: int, redis_client, key_prefix="token_bucket"):
self.rate = rate
self.capacity = capacity
self.redis = redis_client
self.key_prefix = key_prefix
self.script = self._load_script()
def _load_script(self):
# Lua script as string
script = """
local tokens = redis.call('HGET', KEYS[1], 'tokens')
local last_update = redis.call('HGET', KEYS[1], 'last_update')
local now = tonumber(ARGV[1])
local requested = tonumber(ARGV[2])
local rate = tonumber(ARGV[3])
local capacity = tonumber(ARGV[4])
if tokens == false then
tokens = capacity
last_update = now
else
tokens = tonumber(tokens)
last_update = tonumber(last_update)
end
local delta_time = now - last_update
local new_tokens = tokens + delta_time * rate
if new_tokens > capacity then
new_tokens = capacity
end
local allowed = 0
if new_tokens >= requested then
tokens = new_tokens - requested
allowed = 1
else
tokens = new_tokens
end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'last_update', now)
redis.call('EXPIRE', KEYS[1], 3600)
return allowed
"""
return self.redis.register_script(script)
def allow(self, identifier: str, requested: int = 1) -> bool:
key = f"{self.key_prefix}:{identifier}"
now = time.time()
allowed = self.script(keys=[key], args=[now, requested, self.rate, self.capacity])
return allowed == 1
But note: we are using HMSET which is deprecated in Redis 4. We can use HSET with multiple fields.
Alternatively, we can do:
redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_update', now)
But that's not a single command. We can use:
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'last_update', now)
Since we are using a recent Redis? HMSET is deprecated in Redis 4.0 but still works. We can use:
redis.call('HSET', KEYS[1], 'tokens', tokens)
redis.call('HSET', KEYS[1], 'last_update', now)
But that's two commands and not atomic? Actually, the entire script is atomic.
Alternatively, we can use a single HSET with multiple field-value pairs:
redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_update', now)
That's acceptable.
Let's change to:
redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_update', now)
Now, for SlidingWindowRateLimiter:
class RedisSlidingWindowRateLimiter:
def init(self, limit: int, window: float, redis_client, key_prefix="sliding_window"):
self.limit = limit
self.window = window
self.redis = redis_client
self.key_prefix = key_prefix
self.script = self._load_script()
def _load_script(self):
script = """
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local key = KEYS[1]
-- Remove old entries
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
local allowed = 0
if count < limit then
redis.call('ZADD', key, now, now) -- use the same timestamp as member and score? We need unique members.
-- But if we use the same timestamp, we might have duplicate members? We can use a unique ID for each request? Or use the timestamp plus a random? But then we can't remove by score easily.
-- We can use the current time in milliseconds as the member? But then if two requests come at the same millisecond, they will be the same.
-- Alternatively, we can use a unique string for each request, but we don't have one. We can use the current time plus a random string? But then we don't need the member, we just need the score.
-- Actually, we don't care about the member, we just need to count. So we can use the same member? But then ZADD will update the existing member? No, if the member is the same, it will update the score. But we are adding the same member (now) multiple times? That's not allowed.
-- So we need a unique member for each request. We can use the current time in microseconds? But still, two requests in the same microsecond? Unlikely but possible.
-- We can use a combination of time and a random string? Or we can use an incrementing counter? But we don't have a global counter.
-- Alternatively, we can use the current time in milliseconds and a random 6-digit number? But that's not guaranteed unique.
-- We can use the current time in nanoseconds? But Redis scores are floats? Actually, ZADD uses double for score and the member is a string.
-- We can use the current time in milliseconds as the score and a unique string (like a UUID) as the member? But then we are storing a UUID for each request, which is heavy.
-- Alternatively, we can use the current time in milliseconds as the score and the same timestamp as the member? But then if two requests have the same millisecond, they will be the same member and the second will update the first? That's not what we want.
-- We want to store each request as a separate entry.
-- So we need a unique member. We can generate a random string for each request? But then we are storing a lot of data.
-- Alternatively, we can use a fixed-length string that is unique per request? We can use the current time in nanoseconds and a random string? But that's 20+ bytes per request.
-- Since we are only counting, we don't need the member to be anything specific. We can use the current time in milliseconds and a random 6-digit number? But then the probability of collision is low but not zero.
-- Given the rate limit, we are not going to have too many requests in the same millisecond? But for high rates, we might.
-- We can use the current time in microseconds? That gives 1e6 increments per second. If we have 1000 requests per second, then the chance of collision in the same microsecond is low? But still possible.
-- Alternatively, we can use a combination of the current time in milliseconds and a per-millisecond counter? But we don't have a per-millisecond counter in Redis.
-- Given the complexity, and since we are only counting, we can use the current time in milliseconds as the score and a random 8-character string as the member? That's 8 bytes per request.
-- But we are in a Lua script, we can generate a random string? Not easily.
-- We can use the current time in nanoseconds as the score and the same as the member? But then two requests in the same nanosecond? Unlikely.
-- Let's use the current time in nanoseconds (with microsecond precision) and the same as the member? But Redis scores are doubles, and we can use integer up to 2^53? We can use the current time in milliseconds with a fractional part? We can use the current time in seconds with fractional part.
-- We can use the current time in seconds with fractional part (from time.time()) as the score and then use the same as the member? But then if two requests have the same fractional seconds (same time.time() value), they will have the same member.
-- Since time.time() in Python returns a float with microsecond precision, two requests in the same microsecond will have the same value? Yes, if they are in the same microsecond.
-- So we need to add a random component to the member.
-- We can do:
local member = now .. math.random()
-- But then the member is a string and the score is now.
-- But note: we are using the same now for score and member? We can use the same now for score and then member = now .. math.random()? That way, the member is unique and the score is the time.
-- But then we are storing a string that is the time plus a random number. That's about 20 bytes.
-- Alternatively, we can use a UUID? But generating a UUID in Lua is not built-in.
-- We can use the current time in nanoseconds (if available) and then use that as the score and as the member? But we don't have nanosecond precision in Lua.
-- Given the constraints, let's use:
local member = now .. '-' .. math.random(1000000, 9999999)
-- But note: math.random in Lua is not cryptographically secure, but for rate limiting it's okay.
-- However, we are in a Redis Lua script, and we don't have math.random? Actually, Redis Lua has math.random.
-- But we want to avoid collisions. We can use the current time in milliseconds and a 6-digit random number? That gives 1e6 possibilities per millisecond. If we have 1000 requests per second, that's 1 request per millisecond on average, so the chance of collision is very low.
-- We'll do:
local member = now .. '-' .. math.random(100000, 999999)
-- But note: now is a float, we can convert to string.
-- Alternatively, we can use the current time in microseconds as an integer? We can get the current time in seconds with fractional part and multiply by 1e6 to get microseconds? But then we lose the random.
-- Let's do:
local now_micro = math.floor(now * 1000000)
local member = now_micro .. '-' .. math.random(100000, 999999)
-- Then we use now_micro as the score? But then we lose the fractional part? We can use now as the score (which is a float) and the member as a string.
-- Actually, we don't care about the member, only the score. So we can use a fixed string for the member? But then if we add two with the same member, the second will update the first? We don't want that.
-- So we must have a unique member.
-- We can use the current time in nanoseconds? But we don't have that.
-- Given the trade-offs, we'll use:
local member = now .. math.random()
-- This will be unique because now is a float and math.random() returns a float between 0 and 1? Actually, math.random() without arguments returns a float in [0,1). So the string will be unique.
-- But note: if two requests come at the exact same now (same float) and the same random number? Unlikely.
-- So:
local member = tostring(now) .. tostring(math.random())
-- But then the member is a long string? We can use a shorter random.
-- Alternatively, we can use the current time in milliseconds and a 3-digit random? That might collide.
-- We'll use:
local member = string.format("%.6f", now) .. math.random(1000, 9999)
-- But then we are using a fixed format for now (6 decimal places) and a 4-digit random.
-- Given the rate, we are not going to have more than 10000 requests in the same 0.000001 second? That's 10 million requests per second? Unlikely.
-- So we'll do:
local member = string.format("%.6f", now) .. '-' .. math.random(1000, 9999)
-- But note: the score is now (a float). We are using the same now for score and the member is based on now.
-- Actually, we can use the same now for score and then member = now .. math.random()? But then the member is a string and the score is a float.
-- We'll do:
local member = tostring(now) .. tostring(math.random())
-- Then:
redis.call('ZADD', key, now, member)
-- But note: the member is a string and the score is a float.
-- Then we set TTL?
-- We'll set TTL to window * 2.
redis.call('EXPIRE', key, window * 2)
allowed = 1
else
allowed = 0
end
return allowed
"""
return self.redis.register_script(script)
def allow(self, identifier: str) -> bool:
key = f"{self.key_prefix}:{identifier}"
now = time.time()
allowed = self.script(keys=[key], args=[now, self.window, self.limit])
return allowed == 1
However, note: the sliding window as implemented above uses a sorted set and removes old entries on every request. That can be heavy if there are many requests.
We can also use a fixed window with multiple buckets (like 1 minute window broken into 60 seconds) but that's an approximation.
Since the requirement is for sliding window, we'll use the sorted set.
But note: the sorted set can grow to (limit * 2) in the worst case? Because we remove only the ones older than window. And we set TTL to window2, so the key will expire after window2.
So the size of the sorted set is at most the number of requests in the last window, which is at most the limit? Not exactly, because we might have bursts that exceed the limit? Actually, we only add if count < limit, so the maximum size is limit? But wait, we remove only the ones older than window, and then we add one. So the size can be up to limit? Yes, because we only add when count < limit, so the maximum count after adding is limit.
But note: we remove old ones and then check count, then add. So the maximum size is limit.
So it's bounded by limit.
Now, let's talk about per-user/IP keys:
We are using identifier. So the caller should pass a user id or IP.
For burst handling:
Token bucket handles bursts.
For idempotency:
We can have a separate cache (Redis) that stores idempotency keys with a TTL.
We can do:
idempotency_key = request.headers.get("Idempotency-Key")
if idempotency_key:
# Check if we have seen this key for this user and endpoint
key = f"idempotency:{user_id}:{endpoint}:{idempotency_key}"
if redis.get(key):
# return the cached response
else:
# process and then set the key with the response (or just a marker) and TTL
But that's a separate concern.
For backoff:
We return 429 with Retry-After header.
We can calculate the Retry-After as:
For token bucket: (requested - tokens) / rate? But that's not exact because we update the bucket.
Alternatively, we can return the time until the next token? We can calculate:
time_until_next_token = (requested - tokens) / rate [if tokens < requested]
But note: we are updating the bucket on every request, so we know the current tokens.
In the token bucket script, if not allowed, we can return the current tokens and then the server can calculate the wait time.
But we are only returning allowed or not.
We can modify the script to return the wait time (in seconds) if not allowed.
Alternatively, we can return the current tokens and the rate, and then the server calculates:
wait_time = (requested - current_tokens) / rate
But note: the bucket might be refilling while we wait.
Actually, the time to wait until we have enough tokens is:
(requested - current_tokens) / rate
But if we have multiple requests in the same second, we might have to wait for the next refill.
We can return the wait time from the script.
Let's change the token bucket script to return:
if allowed: 1
else: the current tokens (or the wait time?).
But we want to return the wait time for Retry-After.
We can return the wait time in seconds (as a float) and then round up.
Alternatively, we can return the number of tokens missing and the rate, and then calculate.
We'll change the script to return:
if allowed: 1
else: 0 and the current tokens? But we want the wait time.
Actually, the wait time is (requested - new_tokens) / rate.
But note: new_tokens is the tokens after refill until now. So if we have 0 tokens and we request 1, then wait time = 1/rate.
But if we have 0.5 tokens and request 1, then wait time = 0.5/rate.
So we can return:
if allowed: 1
else: (requested - new_tokens) / rate
But note: if new_tokens is 0, then wait_time = requested / rate.
However, if the requested is 1 and rate is 1 per second, then wait_time=1 second.
But we might have to wait for the next token to arrive.
We'll change the script to return:
if allowed: 1
else: (requested - new_tokens) / rate
But note: if new_tokens is 0 and requested is 1, then wait_time = 1/rate.
But what if the bucket is empty and we request 2? Then wait_time = 2/rate.
However, we are only requesting 1 in most cases.
We'll do:
if new_tokens >= requested then
... allowed ...
else
local wait_time = (requested - new_tokens) / rate
return wait_time
end
But then the return type is not consistent (number vs 1). We can return a table? But the script returns a number.
We can return:
if allowed: 1
else: 0 and the wait_time? But we can only return one value.
Alternatively, we can return two values? In Lua, we can return multiple values, but the Redis client might not handle that.
We can return a string: "1" for allowed, or the wait_time as a string? But then we have to parse.
We can return:
if allowed: 1
else: -wait_time (negative to indicate not allowed)
Then the client can check if the return value is 1 (allowed) or a negative number (wait_time = -return_value).
But then if the wait_time is 0? That would be 0, but we are not allowed? Actually, if wait_time is 0, that means we have exactly the tokens? But then we are allowed? So wait_time should be positive.
We can return:
if allowed: 1
else: wait_time (as a positive float)
Then the client can check: if result == 1 -> allowed, else wait_time = result.
But then if the wait_time is 0? That shouldn't happen because if new_tokens < requested, then wait_time > 0.
So:
if new_tokens >= requested then
return 1
else
return (requested - new_tokens) / rate
end
But note: the rate is per second, so wait_time is in seconds.
Then we can set Retry-After to math.ceil(wait_time) (in seconds).
However, we are only requesting 1 token at a time? We can allow multiple tokens per request? We have a parameter `requested`.
We'll change the `allow` method to take `requested` (default 1).
And then the script returns either 1 or the wait_time.
But wait: if we are not allowed, we are updating the bucket to have new_tokens (which is less than requested) and setting last_update to now? That's correct.
So we return the wait_time.
Let's adjust the token bucket script:
local tokens = ... (as before)
... (same until after calculating new_tokens)
local allowed = 0
local wait_time = 0
if new_tokens >= requested then
tokens = new_tokens - requested
allowed = 1
else
tokens = new_tokens
wait_time = (requested - new_tokens) / rate
end
... (update the bucket)
if allowed == 1 then
return 1
else
return wait_time
end
But note: if rate is 0, we divide by zero. We assume rate>0.
Now, for the sliding window, we don't have a concept of tokens, so we can't calculate a wait time? We can calculate the time until the oldest entry in the window expires? But that's not accurate because we are removing old entries.
Alternatively, we can return the current count and the limit, and then the server can calculate the time until the next slot? But sliding window doesn't have slots.
We can return the time until the earliest request in the current window expires? That would be:
earliest = ZRANGE key 0 0 WITHSCORES -- get the first element (oldest) and its score (timestamp)
then wait_time = (earliest_score + window) - now
But if there are no entries? Then we are allowed.
But we are in the case where we are not allowed, so there is at least limit entries.
So we can do:
local earliest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
if earliest and #earliest == 2 then
local earliest_time = tonumber(earliest[2])
local wait_time = (earliest_time + window) - now
if wait_time < 0 then
wait_time = 0
end
return wait_time
else
return 0 -- should not happen because we are not allowed and count>=limit
end
But note: we are removing old entries before counting, so the earliest in the set is within the window.
So the wait_time is the time until that earliest entry expires (i.e., leaves the window).
But that's not the time until we can make another request? Because if we wait until that earliest entry expires, then the count becomes limit-1 and we can make one request.
So that's correct.
However, if multiple requests come at the same time, we might have multiple entries with the same score? We are using a unique member, so we can have multiple entries with the same score? Yes, but the score is the time (with high precision). So they might have the same score? If two requests come at the same time (same now), then they have the same score? But we are using a unique member, so they are different entries with the same score.
Then the earliest score might be the same for multiple? Then we remove by score, so we remove all with score < now - window. So the earliest in the set is the minimum score.
So we can do:
local earliest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
if earliest and #earliest == 2 then
local earliest_time = tonumber(earliest[2])
local wait_time = (earliest_time + window) - now
if wait_time < 0 then
wait_time = 0
end
return wait_time
else
return 0
end
But note: we are in the branch where count >= limit, so there is at least one element.
However, what if the ZRANGE returns nothing? That shouldn't happen.
We'll do:
local earliest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
if not earliest or #earliest < 2 then
return 0
end
Then we return wait_time.
But wait: we are removing old entries and then counting. If the count is >= limit, then the set has at least limit elements, so ZRANGE should return something.
So we can assume earliest is there.
We'll return wait_time.
Then the sliding window script returns:
if allowed: 1
else: wait_time (in seconds)
But note: the sliding window doesn't have a concept of tokens, so the wait_time is the time until the oldest entry in the window expires.
However, if we have a burst of requests at the same time, we might have multiple entries with the same score? Then the earliest time might be the same for many? Then wait_time would be the same until that time passes.
That's acceptable.
Now, let's adjust the sliding window script:
... (remove old entries)
local count = redis.call('ZCARD', key)
if count < limit then
... add ...
return 1
else
-- not allowed, calculate wait_time
local earliest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
if earliest and #earliest == 2 then
local earliest_time = tonumber(earliest[2])
local wait_time = (earliest_time + window) - now
if wait_time < 0 then
wait_time = 0
end
return wait_time
else
return 0
end
end
But note: we are removing old entries, so the earliest_time is at least now - window? Yes.
So wait_time is at most window? Actually, it can be up to window? Because the earliest entry could be just now - window? Then wait_time = window? But that would mean we have to wait the entire window? That's correct if we have a full window of requests at the same time? Actually, if we have a full window of requests at time T, then the earliest is T and we have to wait until T+window? That's the entire window? But that's not correct because we are removing entries older than now-window, so the earliest in the set is within the window. The wait_time is the time until that earliest entry leaves the window.
Example:
window=60, now=1000, and the requests in the last 60 seconds are at times: 940, 950, 960, 970, 980, 990, 1000 (7 requests, limit=6). The earliest is 940. Then wait_time = (940+60) - 1000 = 1000 - 1000 = 0? Actually, 940+60=1000, so wait_time=0. That means we can make a request now? But we have 7 requests in the last 60 seconds? Wait, the window is 60 seconds, so at time 1000, the window is [940, 1000). The request at 940 is exactly at the boundary? We remove entries with score < now-window, which is <940? So the entry at 940 is not removed? Because 940 >= 940? Actually, we remove if score < now-window, so if now-window=940, then we remove scores <940. So 940 is kept.
Then at time 1000, we have 7 entries? But we only allow 6. So we are not allowed. The earliest is 940, and it will leave the window at 940+60=1000. So at time 1000, it leaves? But we are at exactly 1000? Then wait_time=0? That means we can make a request at 1000? But we just removed entries with score <940, so at 1000, the set has entries from 940 to 1000 (including 940). Then at 1000, the entry at 940 is exactly at the boundary? It will be removed at the next request? Actually, the next request at 1000.1 will remove entries <940.1? Then at 1000.1, 940 is removed? So at 1000, we have 7 entries? But we are at the exact boundary.
This is a common issue with sliding windows.
We can adjust the removal to be <= now-window? But then we remove the entry at the boundary.
Typically, we consider the window as [now-window, now). So we remove entries with score <= now-window? Then at time 1000, we remove entries with score <=940, so 940 is removed.
Then the earliest would be 950? Then wait_time = (950+60)-1000 = 1010-1000=10 seconds.
That seems more correct.
So let's change the removal to:
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
to
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
But note: ZREMRANGEBYSCORE removes members with scores between min and max inclusive? Actually, the command is:
ZREMRANGEBYSCORE key min max
It removes all elements in the sorted set with a score between min and max (inclusive).
So if we do:
ZREMRANGEBYSCORE key 0 now-window
Then it removes scores <= now-window.
So the entry at exactly now-window is removed.
Then the window is (now-window, now]? Actually, we are removing scores <= now-window, so the remaining scores are > now-window.
So the window is (now-window, now].
That's a common implementation.
So we change the removal to remove scores <= now-window.
Then the earliest in the set is > now-window.
Then the wait_time is:
wait_time = (earliest_score + window) - now
But note: earliest_score > now-window, so earliest_score + window > now.
So wait_time is positive.
Example:
now=1000, window=60, earliest_score=941 (because we removed 940 and below). Then wait_time = 941+60 - 1000 = 1001-1000=1 second.
That means we have to wait 1 second until the entry at 941 leaves the window? Actually, the entry at 941 will leave when the window moves to 941? That is, at time 941+60=1001.
So at time 1001, the entry at 941 will be removed (because then now-window=1001-60=941, and we remove <=941).
So wait_time is correct.
So we change the removal to:
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
and then the wait_time calculation as above.
Now, let's code the sliding window script accordingly.
Also, note: we are using the same key for the same identifier and window? Yes.
We are setting TTL to window2? That might be too long? We can set TTL to window2 to be safe.
But note: the key will have entries with scores up to now, so the key will expire after window*2 from the last update? That's acceptable.
Now, for observability:
We can increment counters:
For each request, we can have:
metrics.rate_limit_attempts_total.inc()
if allowed:
metrics.rate_limit_allowed_total.inc()
else:
metrics.rate_limit_denied_total.inc()
metrics.rate_limit_wait_time_seconds.observe(wait_time)
We can also log the denied requests.
Now, let's write the code for the rate limiters with metrics.
We'll use the prometheus_client library for metrics.
But note: we are in a web server? We can assume we are in a FastAPI or Flask app.
We'll create a middleware or decorator.
But the requirement is to implement the patterns and provide example configs/snippets.
We'll provide:
- The rate limiter classes (RedisTokenBucketRateLimiter and RedisSlidingWindowRateLimiter)
- Example of how to use them in a web framework (FastAPI)
We'll also provide an in-memory version for testing.
Let's code:
We'll create:
rate_limiter.py:
import time
import redis
from redis import Redis
class RateLimiter:
def allow(self, identifier: str, requested: int = 1) -> (bool, float):
"""
Returns (allowed, wait_time) where wait_time is in seconds (if not allowed, otherwise 0).
"""
raise NotImplementedError
class InMemoryTokenBucketRateLimiter(RateLimiter):
def __init__(self, rate: float, capacity: int):
self.rate = rate
self.capacity = capacity
self.buckets = {} # identifier -> (tokens, last_update)
def allow(self, identifier: str, requested: int = 1) -> (bool, float):
now = time.time()
if identifier not in self.buckets:
tokens = self.capacity
last_update = now
else:
tokens, last_update = self.buckets[identifier]
delta = now - last_update
tokens = min(self.capacity, tokens + delta * self.rate)
if tokens >= requested:
tokens -= requested
allowed = True
wait_time = 0
else:
allowed = False
wait_time = (requested - tokens) / self.rate
self.buckets[identifier] = (tokens, now)
return allowed, wait_time
class RedisTokenBucketRateLimiter(RateLimiter):
def __init__(self, rate: float, capacity: int, redis_client: Redis, key_prefix="token_bucket"):
self.rate = rate
self.capacity = capacity
self.redis = redis_client
self.key_prefix = key_prefix
self.script = self._load_script()
def _load_script(self):
script = """
local tokens = redis.call('HGET', KEYS[1], 'tokens')
local last_update = redis.call('HGET', KEYS[1], 'last_update')
local now = tonumber(ARGV[1])
local requested = tonumber(ARGV[2])
local rate = tonumber(ARGV[3])
local capacity = tonumber(ARGV[4])
if tokens == false then
tokens = capacity
last_update = now
else
tokens = tonumber(tokens)
last_update = tonumber(last_update)
end
local delta_time = now - last_update
local new_tokens = tokens + delta_time * rate
if new_tokens > capacity then
new_tokens = capacity
end
local allowed = 0
local wait_time = 0
if new_tokens >= requested then
tokens = new_tokens - requested
allowed = 1
else
tokens = new_tokens
wait_time = (requested - new_tokens) / rate
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'last_update', now)
redis.call('EXPIRE', KEYS[1], 3600)
if allowed == 1 then
return 1
else
return wait_time
end
"""
return self.redis.register_script(script)
def allow(self, identifier: str, requested: int = 1) -> (bool, float):
key = f"{self.key_prefix}:{identifier}"
now = time.time()
result = self.script(keys=[key], args=[now, requested, self.rate, self.capacity])
if result == 1:
return True, 0
else:
return False, result
class RedisSlidingWindowRateLimiter(RateLimiter):
def __init__(self, limit: int, window: float, redis_client: Redis, key_prefix="sliding_window"):
self.limit = limit
self.window = window
self.redis = redis_client
self.key_prefix = key_prefix
self.script = self._load_script()
def _load_script(self):
script = """
local now = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local key = KEYS[1]
-- Remove old entries (scores <= now - window)
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local count = redis.call('ZCARD', key)
if count < limit then
-- Generate a unique member: we use the current time and a random number
local member = tostring(now) .. tostring(math.random())
redis.call('ZADD', key, now, member)
redis.call('EXPIRE', key, window * 2)
return 1
else
-- Get the earliest entry's score
local earliest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
if earliest and #earliest == 2 then
local earliest_time = tonumber(earliest[2])
local wait_time = (earliest_time + window) - now
if wait_time < 0 then
wait_time = 0
end
return wait_time
else
return 0
end
end
"""
return self.redis.register_script(script)
def allow(self, identifier: str, requested: int = 1) -> (bool, float):
# Note: sliding window doesn't support multiple tokens per request? We can adjust but typically 1.
if requested != 1:
raise ValueError("SlidingWindowRateLimiter only supports requested=1")
key = f"{self.key_prefix}:{identifier}"
now = time.time()
result = self.script(keys=[key], args=[now, self.window, self.limit])
if result == 1:
return True, 0
else:
return False, result
Now, example usage in FastAPI:
from fastapi import FastAPI, Request, HTTPException
from redis import Redis
from rate_limiter import RedisTokenBucketRateLimiter
app = FastAPI()
redis_client = Redis(host='localhost', port=6379, db=0)
# 10 requests per second, burst up to 20
limiter = RedisTokenBucketRateLimiter(rate=10, capacity=20, redis_client=redis_client)
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
# Get user identifier: from token or IP
user_id = request.headers.get("X-User-Id") or request.client.host
allowed, wait_time = limiter.allow(user_id)
if not allowed:
raise HTTPException(status_code=429, detail="Too many requests", headers={"Retry-After": str(int(wait_time) + 1)})
response = await call_next(request)
return response
For sliding window:
limiter = RedisSlidingWindowRateLimiter(limit=10, window=60, redis_client=redis_client)
But note: the sliding window limiter only supports requested=1.
For idempotency, we can have:
idempotency_key = request.headers.get("Idempotency-Key")
if idempotency_key:
cache_key = f"idempotency:{user_id}:{request.url.path}:{idempotency_key}"
cached_response = redis_client.get(cache_key)
if cached_response:
return Response(cached_response)
else:
response = await call_next(request)
redis_client.setex(cache_key, 3600, response.body)
return response
But we have to cache the entire response? And we have to set the TTL appropriately.
For backoff: we are returning Retry-After.
For observability: we can use Prometheus.
from prometheus_client import Counter, Histogram
RATE_LIMIT_ATTEMPTS = Counter('rate_limit_attempts_total', 'Total rate limit attempts', ['identifier', 'limiter'])
RATE_LIMIT_ALLOWED = Counter('rate_limit_allowed_total', 'Total rate limit allowed', ['identifier', 'limiter'])
RATE_LIMIT_DENIED = Counter('rate_limit_denied_total', 'Total rate limit denied', ['identifier', 'limiter'])
RATE_LIMIT_WAIT_TIME = Histogram('rate_limit_wait_time_seconds', 'Wait time for rate limited requests', ['identifier', 'limiter'])
Then in the middleware:
RATE_LIMIT_ATTEMPTS.labels(identifier=user_id, limiter='token_bucket').inc()
if allowed:
RATE_LIMIT_ALLOWED.labels(identifier=user_id, limiter='token_bucket').inc()
else:
RATE_LIMIT_DENIED.labels(identifier=user_id, limiter='token_bucket').inc()
RATE_LIMIT_WAIT_TIME.labels(identifier=user_id, limiter='token_bucket').observe(wait_time)
But note: we are using the limiter type in the label.
We can also have a label for the endpoint? But that might be too many.
We'll keep it simple.
This is a basic implementation.
Note: The token bucket script uses a fixed TTL of 3600 seconds. We can make that configurable.
Also, the sliding window script uses window*2 as TTL.
We can adjust.
Also, note that the token bucket script uses a hash with two fields. We can also use a single string with serialization, but hash is easier.
Now, what about burst handling?
Token bucket handles bursts by allowing up to capacity tokens to be consumed at once.
Sliding window does not allow bursts beyond the limit in the window.
For per-user/IP keys: we are using the identifier.
For distributed counters: we are using Redis.
For idempotency: we provided an example.
For backoff: we return Retry-After.
For observability: we provided Prometheus metrics.
This should cover the requirements.
However, note: the token bucket script might have a race condition? The entire script is atomic, so it's safe.
The sliding window script is also atomic.
We are using Redis Lua scripts to ensure atomicity.
Now, let's write the example configs:
We can have a config file (YAML) for the rate limiter:
rate_limiting:
enabled: true
algorithm: token_bucket # or sliding_window
token_bucket:
rate: 10.0
capacity: 20
sliding_window:
limit: 10
window: 60
per_user: true # if false, then use IP only? Or we can have a key_prefix that includes the type.
But we are constructing the key as: f"{key_prefix}:{identifier}"
We can have:
key_prefix = f"rate_limit:{algorithm}:{user_type}" where user_type is 'user' or 'ip'
But we are passing the identifier, which can be user_id or IP.
We can let the user of the limiter decide the identifier.
So the configuration would be:
rate_limiter:
type: token_bucket
rate: 10
capacity: 20
key_prefix: "rate_limit:token_bucket"
Then in the middleware, we get the identifier (user_id or IP) and then:
key = f"{key_prefix}:{identifier}"
Alternatively, we can have:
key_prefix: "rate_limit"
algorithm: "token_bucket"
and then the key is: f"{key_prefix}:{algorithm}:{identifier}"
We'll leave that to the user.
We have provided the classes that take a key_prefix.
Now, for the example config, we can write:
# config.yaml
rate_limiting:
enabled: true
limiter:
type: "token_bucket"
rate: 10.0
capacity: 20
key_prefix: "rate_limit:token_bucket"
identifier:
type: "user_id" # or "ip"
header: "X-User-Id" # if type is user_id, then get from header, else use request.client.host
Then in the middleware, we get the identifier accordingly.
We can also have multiple limiters (per endpoint) by having different key_prefix per endpoint.
We can have:
limiter_by_endpoint:
"/login": { type: "token_bucket", rate: 5, capacity: 10, key_prefix: "rate_limit:login" }
default: { type: "token_bucket", rate: 10, capacity: 20, key_prefix: "rate_limit:default" }
Then in the middleware, we get the endpoint and use the corresponding limiter.
But that's more complex.
We'll leave that as an extension.
Now, let's write the example snippets.
We have provided:
- The rate limiter classes.
- The FastAPI middleware example.
- The Prometheus metrics example.
- The idempotency example.
We can also provide a simple script to test:
if __name__ == "__main__":
import redis
r = redis.Redis()
limiter = RedisTokenBucketRateLimiter(rate=1, capacity=2, redis_client=r)
for i in range(5):
allowed, wait = limiter.allow("test_user")
print(f"Request {i}: allowed={allowed}, wait={wait}")
This should show: first two allowed, then denied with wait time 1 second, then after waiting, allowed again.
But note: the token bucket refills at 1 token per second, so after 2 requests, we have 0 tokens. Then the third request is denied and wait_time=1. Then if we wait 1 second and try again, we should have 1 token? But the bucket refills continuously.
We can test.
Now, note: the token bucket script uses the current time to refill. So if we wait, the tokens will refill.
This should work.
We'll also note that the sliding window limiter only supports requested=1.
If we want to support multiple tokens, we can adjust the sliding window to add multiple entries? But that would be multiple requests.
Alternatively, we can adjust the limit and window accordingly.
We'll leave it as is.
This is a comprehensive implementation.
Let me know if you have any questions.
I'll provide a comprehensive implementation guide for rate limiting and throttling patterns with practical examples and configurations.
1. Token Bucket Algorithm
Concept
- Tokens are added to a bucket at a fixed rate
- Each request consumes tokens
- Burst allowed up to bucket capacity
Redis Implementation (Lua Script)
-- token_bucket.lua
local key = KEYS[1]
local now = tonumber(ARGV[1])
local requested = tonumber(ARGV[2])
local refill_rate = tonumber(ARGV[3])
local capacity = tonumber(ARGV[4])
local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
local tokens = bucket[1] and tonumber(bucket[1]) or capacity
local last_refill = bucket[2] and tonumber(bucket[2]) or now
-- Calculate refill
local delta = math.max(0, now - last_refill)
local refill = delta * refill_rate
tokens = math.min(capacity, tokens + refill)
if tokens >= requested then
tokens = tokens - requested
redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
redis.call('EXPIRE', key, math.ceil(capacity / refill_rate * 2))
return 1 -- allowed
else
redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
redis.call('EXPIRE', key, math.ceil(capacity / refill_rate * 2))
return 0 -- denied
end
Python Implementation
import redis
import time
class TokenBucketRateLimiter:
def __init__(self, redis_client, rate, capacity, key_prefix="ratelimit:tb"):
self.redis = redis_client
self.rate = rate # tokens per second
self.capacity = capacity
self.key_prefix = key_prefix
with open('token_bucket.lua') as f:
self.script = self.redis.register_script(f.read())
def is_allowed(self, identifier, tokens=1):
key = f"{self.key_prefix}:{identifier}"
now = time.time()
result = self.script(keys=[key], args=[now, tokens, self.rate, self.capacity])
return bool(result)
2. Leaky Bucket Algorithm
Concept
- Requests enter a queue at variable rates
- Processed at fixed rate (leak rate)
- Overflow when queue full
Redis Implementation (List + Consumer)
-- leaky_bucket.lua
local key = KEYS[1]
local now = tonumber(ARGV[1])
local leak_rate = tonumber(ARGV[2]) -- requests per second
local queue_max = tonumber(ARGV[3])
-- Get current queue size
local queue_len = redis.call('LLEN', key)
-- Check if we can accept
if queue_len >= queue_max then
return 0 -- reject
end
-- Add request to queue with timestamp
local request_id = ARGV[4] -- unique request ID
redis.call('LPUSH', key, request_id .. ':' .. now)
redis.call('EXPIRE', key, 3600) -- cleanup after 1 hour
-- Try to process (simulate consumer)
local process_interval = 1 / leak_rate
local last_processed = redis.call('HGET', key .. ':meta', 'last_processed')
last_processed = last_processed and tonumber(last_processed) or 0
if now - last_processed >= process_interval then
-- Process one request
local item = redis.call('RPOP', key)
if item then
redis.call('HSET', key .. ':meta', 'last_processed', now)
return 1 -- accepted and processed
end
end
return 1 -- accepted, waiting in queue
3. Sliding Window Counter
Concept
- Track requests in moving time window
- More accurate than fixed window
Redis Sorted Set Implementation
import time
import uuid
class SlidingWindowRateLimiter:
def __init__(self, redis_client, limit, window_seconds, key_prefix="ratelimit:sw"):
self.redis = redis_client
self.limit = limit
self.window = window_seconds
self.key_prefix = key_prefix
def is_allowed(self, identifier):
key = f"{self.key_prefix}:{identifier}"
now = time.time()
window_start = now - self.window
# Remove old entries
self.redis.zremrangebyscore(key, 0, window_start)
# Count current entries
current = self.redis.zcard(key)
if current < self.limit:
# Add new request
request_id = str(uuid.uuid4())
self.redis.zadd(key, {request_id: now})
self.redis.expire(key, self.window * 2)
return True
return False
4. Distributed Counter (Redis)
Fixed Window Counter with Auto-Reset
class FixedWindowRateLimiter:
def __init__(self, redis_client, limit, window_seconds, key_prefix="ratelimit:fw"):
self.redis = redis_client
self.limit = limit
self.window = window_seconds
self.key_prefix = key_prefix
def is_allowed(self, identifier):
key = f"{self.key_prefix}:{identifier}:{int(time.time() // self.window)}"
# Increment and check
current = self.redis.incr(key)
if current == 1:
self.redis.expire(key, self.window + 1)
return current <= self.limit
5. Per-User/IP Keys with Configuration
# config.yaml
rate_limiting:
enabled: true
strategies:
- type: token_bucket
identifier:
type: user_id # or "ip", "api_key", "combination"
header: "X-User-ID" # header to extract from
fallback: "ip" # fallback identifier
rate: 10
capacity: 20
key_template: "rl:tb:{env}:{identifier}"
- type: sliding_window
path: "/api/expensive" # apply only to specific paths
limit: 100
window: 60
key_template: "rl:sw:{env}:{path}:{identifier}"
# Middleware extraction
def get_identifier(request, config):
identifier_type = config['identifier']['type']
header = config['identifier'].get('header')
if identifier_type == "user_id" and header:
return request.headers.get(header, request.client.host)
elif identifier_type == "ip":
return request.client.host
elif identifier_type == "api_key":
return request.headers.get("X-API-Key", "anonymous")
elif identifier_type == "combination":
user_id = request.headers.get("X-User-ID", "anon")
ip = request.client.host
return f"{user_id}:{ip}"
return request.client.host
6. Burst Handling
Burst Buffer Pattern
class BurstHandlingLimiter:
def __init__(self, limiter, burst_capacity=50, burst_window=10):
self.limiter = limiter
self.burst_capacity = burst_capacity
self.burst_window = burst_window
self.redis = limiter.redis
def is_allowed(self, identifier):
burst_key = f"burst:{identifier}"
now = time.time()
# Check burst usage
burst_current = self.redis.get(burst_key)
if burst_current and int(burst_current) >= self.burst_capacity:
return self.limiter.is_allowed(identifier)
# Allow if burst available
if self.limiter.is_allowed(identifier):
# Increment burst counter
self.redis.incr(burst_key)
self.redis.expire(burst_key, self.burst_window)
return True
return False
7. Idempotency Keys
class IdempotencyMiddleware:
def __init__(self, redis_client, ttl_seconds=86400):
self.redis = redis_client
self.ttl = ttl_seconds
def check_idempotency(self, request_id, identifier, endpoint):
key = f"idem:{identifier}:{endpoint}:{request_id}"
if self.redis.exists(key):
# Return cached response
cached = self.redis.get(key)
return False, cached
return True, None
def store_response(self, request_id, identifier, endpoint, response_body, status_code):
key = f"idem:{identifier}:{endpoint}:{request_id}"
value = f"{status_code}:{response_body}"
self.redis.setex(key, self.ttl, value)
# Usage in FastAPI
@app.middleware("http")
async def idempotency_middleware(request: Request, call_next):
request_id = request.headers.get("Idempotency-Key")
if request_id:
allowed, cached = idempotency.check_idempotency(
request_id,
get_identifier(request),
request.url.path
)
if not allowed:
status, body = cached.split(":", 1)
return Response(body, status_code=int(status))
response = await call_next(request)
if request_id and response.status_code < 500: # Only cache successful responses
idempotency.store_response(
request_id,
get_identifier(request),
request.url.path,
response.body,
response.status_code
)
return response
8. Exponential Backoff for Clients
Server Response Headers
class RateLimitMiddleware:
def __init__(self, app, limiter):
self.app = app
self.limiter = limiter
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request = Request(scope, receive)
identifier = get_identifier(request)
allowed, retry_after = self.limiter.is_allowed_with_retry(identifier)
if not allowed:
# Calculate exponential backoff based on current load
current_load = self.limiter.get_current_load(identifier)
backoff_seconds = min(300, 2 ** min(current_load, 8))
response = JSONResponse(
{"error": "rate_limit_exceeded"},
status_code=429,
headers={
"Retry-After": str(backoff_seconds),
"X-RateLimit-Limit": str(self.limiter.limit),
"X-RateLimit-Remaining": "0",
"X-RateLimit-Reset": str(int(time.time() + backoff_seconds))
}
)
await response(scope, receive, send)
return
await self.app(scope, receive, send)
9. Observability & Metrics
Prometheus Metrics
from prometheus_client import Counter, Histogram, Gauge, Summary
# Metrics
REQUESTS_TOTAL = Counter(
'rate_limit_requests_total',
'Total rate limit requests',
['limiter_type', 'identifier', 'endpoint', 'decision']
)
REQUESTS_IN_PROGRESS = Gauge(
'rate_limit_requests_in_progress',
'Currently executing rate limit checks',
['limiter_type']
)
WAIT_TIME_SECONDS = Histogram(
'rate_limit_wait_time_seconds',
'Time clients waited due to rate limiting',
['limiter_type'],
buckets=(0.1, 0.5, 1, 5, 10, 30, 60)
)
CURRENT_LOAD = Gauge(
'rate_limit_current_load',
'Current load per identifier',
['limiter_type', 'identifier']
)
def observe_rate_limit(limiter_type, identifier, endpoint, allowed, wait_time=0):
decision = "allowed" if allowed else "denied"
REQUESTS_TOTAL.labels(
limiter_type=limiter_type,
identifier=identifier,
endpoint=endpoint,
decision=decision
).inc()
if not allowed and wait_time > 0:
WAIT_TIME_SECONDS.labels(limiter_type=limiter_type).observe(wait_time)
# Decorator for instrumentation
def instrument_limiter(limiter_class):
original_is_allowed = limiter_class.is_allowed
def wrapped_is_allowed(self, identifier, *args, **kwargs):
with REQUESTS_IN_PROGRESS.labels(limiter_type=self.__class__.__name__).track_inprogress():
result = original_is_allowed(self, identifier, *args, **kwargs)
observe_rate_limit(
self.__class__.__name__,
identifier,
getattr(self, 'current_endpoint', 'unknown'),
result[0] if isinstance(result, tuple) else result,
result[1] if isinstance(result, tuple) and not result[0] else 0
)
return result
limiter_class.is_allowed = wrapped_is_allowed
return limiter_class
Structured Logging
import json
import logging
class RateLimitLogger:
def __init__(self):
self.logger = logging.getLogger("rate_limiter")
handler = logging.StreamHandler()
formatter = json.JSONFormatter()
handler.setFormatter(formatter)
self.logger.addHandler(handler)
self.logger.setLevel(logging.INFO)
def log_decision(self, identifier, limiter_type, allowed,
remaining=0, reset_time=None, wait_time=0,
user_agent=None, ip=None, endpoint=None):
log_data = {
"timestamp": time.time(),
"identifier": identifier,
"limiter": limiter_type,
"allowed": allowed,
"remaining": remaining,
"reset_time": reset_time,
"wait_time": wait_time,
"user_agent": user_agent,
"ip": ip,
"endpoint": endpoint
}
self.logger.info("rate_limit_decision", extra=log_data)
10. Complete Configuration Example
# rate_limiting_config.yaml
global:
default_limiter:
type: "token_bucket"
rate: 100
capacity: 200
burst_buffer: 50
burst_window: 10
rules:
- path: "/api/auth/*"
limiter:
type: "fixed_window"
limit: 5
window: 60
identifier:
type: "ip"
- path: "/api/payments/*"
limiter:
type: "sliding_window"
limit: 10
window: 60
burst_capacity: 5 # allow small bursts
identifier:
type: "user_id"
header: "Authorization"
extract_from_token: true # extract user_id from JWT
- path: "/api/export/*"
limiter:
type: "leaky_bucket"
rate: 1
queue_size: 10
identifier:
type: "api_key"
header: "X-API-Key"
- path: "/api/admin/*"
limiter:
type: "token_bucket"
rate: 1000
capacity: 2000
identifier:
type: "combination"
template: "{user_id}:{ip}"
monitoring:
metrics:
enabled: true
prometheus_endpoint: "/metrics"
logging:
level: "INFO"
format: "json"
alerts:
- metric: "rate_limit_denied_total"
threshold: 1000
window: 60
severity: "warning"
11. Docker Compose with Redis Stack
version: '3.8'
services:
redis:
image: redis/redis-stack:latest
ports:
- "6379:6379"
- "8001:8001" # RedisInsight
volumes:
- redis_data:/data
command: redis-server --appendonly yes
app:
build: .
environment:
REDIS_URL: "redis://redis:6379"
RATE_LIMITING_CONFIG: "/config/rate_limiting_config.yaml"
depends_on:
- redis
ports:
- "8000:8000"
volumes:
redis_data:
12. Kubernetes Resource Limits
apiVersion: apps/v1
kind: Deployment
metadata:
name: rate-limited-app
spec:
replicas: 3
template:
spec:
containers:
- name: app
image: myapp:latest
env:
- name: REDIS_URL
value: "redis://redis-master:6379"
resources:
limits:
memory: "512Mi"
cpu: "500m"
requests:
memory: "256Mi"
cpu: "250m"
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
Best Practices Summary
- Identifier Strategy: Use combination of user+IP for better accuracy
- Burst Handling: Always define burst capacity separate from sustained rate
- Observability: Track denied/allowed ratios, wait times, and identifier popularity
- Graceful Degradation: Return 429 with
Retry-After header
- Distributed Consistency: Use Redis Lua scripts for atomic operations
- Cleanup: Set appropriate TTLs to prevent memory leaks
- Testing: Simulate burst traffic patterns in staging
- Monitoring: Alert on high denial rates (>1% of traffic)
- Configuration: Hot-reload configuration without restart
- Fallback: Have circuit breaker pattern if Redis fails
This implementation provides production-ready patterns with proper distributed coordination, observability, and configuration management. Remember to adjust parameters based on your specific traffic patterns and SLA requirements.