We are going to design a tenant-aware rate limiter that handles quotas, fairness, and isolation.
Requirements:
- Tenant-aware: Each tenant (customer) has its own set of limits and may have multiple users (or applications) under them.
- Quotas: Each tenant has a global quota (e.g., requests per minute) and possibly per-user or per-application quotas.
- Fairness: Within a tenant, we want to distribute the quota fairly among the users/applications. This might mean that if one user is not using their share, others can use it, but if they try to use more than their share, they get limited.
- Isolation: Tenants are isolated from each other. One tenant's usage should not affect another tenant's limits.
Design considerations:
- We are rate limiting in a distributed system (multiple instances of the rate limiter). So we need a distributed store (like Redis) to keep the counters.
- We need to handle burst traffic and smooth rate limiting.
Approaches:
- Token bucket algorithm per tenant, and then per user within the tenant? But that might not be fair if we have a global bucket for the tenant and then per-user buckets that refill from the global bucket? Or we can have a two-level token bucket:
- Global tenant bucket: refills at the tenant's global rate.
- Per-user buckets: refill at the user's rate, but when they take tokens they also take from the global bucket? Alternatively, we can have the global bucket as the source for all users, and then each user has a personal bucket that gets refilled from the global bucket.
However, note that we want fairness: if a user is not using their share, others can use it. So we can have:
- A global bucket for the tenant (with the total rate) and then per-user buckets that have a maximum capacity of the user's fair share? But then if the user doesn't use, the tokens in their bucket don't go back to the global bucket? We need a way to rebalance.
Alternatively, we can use a "leaky bucket" or "smooth" algorithm that is per tenant and then track per-usage by user, and when a user exceeds their fair share (which is the global rate divided by the number of users? or a fixed share?) we limit them.
But note: the fair share might change as users come and go.
Another idea: use a weighted fair queuing (WFQ) or similar, but that might be complex for rate limiting.
Let's think of a simpler approach:
We can have:
- A distributed counter for the tenant that resets every interval (using a sliding window or fixed window). But then how do we enforce per-user fairness?
We can do:
For each request, we check:
1. Does the tenant have remaining capacity? (using a tenant-level token bucket or counter)
2. Has the user exceeded their fair share of the tenant's capacity in the current interval?
How to compute fair share?
Option 1: Predefined per-user limits. Then we have two checks: tenant global and per-user.
Option 2: Dynamic fair share: the tenant's global rate divided by the number of active users (or a minimum share per user). But then we need to track active users and their usage.
However, note that we might have a mix: some users have a guaranteed minimum (reservation) and then the rest is shared.
Let's break down:
We have two levels:
- Tenant level: total rate limit R (requests per minute, for example).
- User level: each user i has a minimum guaranteed rate r_i (which could be 0) and then the remaining (R - sum(r_i)) is shared among all users (or among users that have exceeded their minimum?).
But note: if we set r_i as the minimum, then we are reserving that for the user. Then the shared pool is R - sum(r_i). We need to distribute the shared pool fairly.
Alternatively, we can set a maximum per user? That's simpler: each user has a maximum u_i, and the tenant has a total T. Then we enforce that the sum of all users' usage does not exceed T, and no user exceeds u_i.
But then we are not allowing a user to use more than u_i even if the tenant has capacity? That might be acceptable if u_i is set appropriately (maybe u_i is the maximum the user can ever use, and the tenant's total is the sum of all u_i?).
However, the problem says "quotas" and "fairness". So maybe we want:
- Each user has a soft limit (fair share) and a hard limit (maximum). The soft limit is the fair share of the tenant's capacity, and the hard limit is the absolute maximum even if the tenant has capacity.
But how to compute the soft limit? It could be:
soft_limit_i = (tenant_total_rate * weight_i) / total_weights
where weight_i is the user's weight (maybe 1 for all, or assigned by the tenant).
Then we allow:
- User i can use up to hard_limit_i (if set) or if not set, then up to the current available in the tenant's bucket (but not more than the soft limit unless others are not using?).
This becomes complex.
Let's simplify the requirements:
We are asked for:
- Quotas: each tenant has a global quota, and possibly per-user quotas (which could be hard limits).
- Fairness: within the tenant, the usage is distributed fairly among users (so no single user can starve others, but if one user is idle, others can use more up to their hard limit?).
We can design:
For each tenant, we have:
- A global token bucket (or counter) with rate R (the tenant's quota) and burst capacity B (maybe R * burst_window).
- For each user in the tenant, we have:
- A hard limit H_i (maximum requests per minute, for example). This is a fixed number.
- A current usage counter for the user in the current interval (for the fair share calculation?).
How to enforce fairness?
We can do:
When a request comes from user i of tenant T:
1. Check if the tenant T has available tokens (in the global bucket). If not, reject.
2. Check if the user i has exceeded their hard limit H_i in the current interval (using a sliding window or fixed window). If yes, reject.
3. If both pass, then we allow and decrement the tenant's global bucket and record the request for the user.
But step 2 doesn't consider fairness: it only enforces hard limits. What if the tenant's total is 1000 and we have two users with hard limits 800 and 800? Then the tenant's total is 1000, so both can't use 800. We need to enforce that the sum of users' usage does not exceed the tenant's total? But we already have the global bucket.
The global bucket ensures that the tenant's total is not exceeded. But then the user's hard limit might be higher than the fair share? That's okay because the global bucket will limit the total.
However, what if we want to enforce that a user cannot use more than their fair share (which might be less than their hard limit) if other users are also active? That is, we want to distribute the tenant's capacity fairly among active users.
Let's define:
Let U be the set of active users (who have made at least one request in the current interval) for tenant T.
The fair share for each active user i could be: (tenant_total_rate) / |U|
But then if a user has a hard limit that is lower than the fair share, then they are limited by their hard limit? And if higher, they are limited by the fair share? But then if one user is idle, the fair share increases for the others? That's dynamic.
Alternatively, we can set a minimum guaranteed rate for each user (reservation) and then the rest is shared. But the problem says "fairness", so we want to avoid starvation.
Let's consider:
We have:
- Tenant total rate: R
- Each user i has:
- A guaranteed minimum rate: g_i (could be 0 for some users)
- A hard maximum: H_i (could be infinity, or a very high number)
We require: sum(g_i) <= R.
Then the shared pool is: S = R - sum(g_i)
For active users (those who have usage in the current interval), we distribute S among them? But how?
We can do:
For user i, the current allowed rate is at most: g_i + (S * w_i) / sum(w_j for active j)
where w_i is the user's weight (maybe 1 for all, or assigned).
But then we need to track active users and their weights.
This is getting too complicated for a rate limiter that must be fast.
Let's step back.
Perhaps the requirement is simpler:
- The tenant has a total quota.
- Each user has a maximum quota (which is <= tenant total? or can be more?).
- We want to ensure that the tenant's total is not exceeded, and that no user exceeds their maximum, but also that if the tenant's total is not fully used, then users can exceed their "fair share" (which might be the tenant total divided by number of users) up to their maximum.
But note: if we set the user's maximum to be the same as the tenant's total, then one user could use everything. That might not be fair.
So maybe we want:
- Each user has a soft limit (fair share) and a hard limit (maximum). The soft limit is the tenant's total divided by the number of users (or by weight). But then if the tenant's total is 100 and there are 2 users, each soft limit is 50. But if one user only uses 10, then the other can use up to 90? That's fair.
How to implement:
We need to track:
- Tenant global usage in the current interval (using a sliding window or fixed window).
- For each user, their usage in the current interval.
Then for a request from user i:
Let current_tenant_usage = U
Let current_user_usage = u_i
Let active_users = set of users who have made at least one request in the current interval (or in the last, say, 1 minute?).
Let N = number of active_users.
Then the fair share for each active user is: R / N (if we assume equal weights).
But wait: what if users have different weights? Then fair share for user i: (R * w_i) / sum(w_j for active j)
Then we allow if:
u_i < min( hard_limit_i, fair_share_i ) ????
But note: if the tenant's total usage is low, then the fair share might be higher than what we are actually using? Actually, the fair share is theoretical. We want to allow a user to use more than the fair share if the tenant's total is not exceeded and the user hasn't hit their hard limit? But then we are not enforcing the fair share as a limit.
Alternatively, we can think:
We want to ensure that no user can use more than their fair share if the tenant's total is being fully used? But if the tenant's total is not fully used, then we allow up to the hard limit.
So:
Let available_tenant = R - U (if we are using a fixed window, then U is the usage in the current window)
Then for user i, the maximum they can use in the current window is:
min( hard_limit_i, available_tenant, fair_share_i * (some factor?) )
But note: if we allow the user to use up to available_tenant, then one user could take all the available_tenant, which is not fair.
So we need to reserve the fair share for each active user? But then if a user is not active, we don't reserve for them.
We can do:
For each active user i, we reserve a fair share (which is the minimum they are guaranteed). Then the remaining (R - sum(reserved)) is shared among all active users? But then how do we allocate the remaining? We can let them compete for the remaining?
Alternatively, we can use a weighted fair queuing (WFQ) for the tokens? But in a distributed system, that's hard.
Given the complexity, maybe we should stick to:
Level 1: Tenant global bucket (with rate R and burst B).
Level 2: Per-user hard limits (with their own buckets, rate = H_i, burst = H_i * burst_window).
Then we allow a request if:
- Tenant global bucket has tokens.
- User i's bucket has tokens.
This ensures:
- The tenant's total rate does not exceed R (because we check the global bucket first).
- The user's rate does not exceed H_i.
But this does not enforce fairness: if H_i is set to R for all users, then one user could use all R. But that's because we set H_i too high.
So the fairness is achieved by setting the H_i appropriately (so that the sum of H_i is not much more than R, and individually H_i is not too high). But then we are relying on the tenant to set the H_i.
However, the problem says "fairness" as a feature of the rate limiter, so we might want to automatically adjust the per-user limits based on the number of active users? But that's not typical.
Another idea: we can have a "max burst" for the tenant and then for each user, but also track the average usage per user and if one user is using more than the average, we start throttling them? But that's reactive and might be complex.
Given the time, let's design a simpler system that meets the basic requirements:
We'll have:
- A distributed store (Redis) with the following keys:
For tenant T:
- `rate limiter:tenant:T:global` : a token bucket (or a sliding window counter) for the tenant's global limit.
For user i of tenant T:
- `rate limiter:tenant:T:user:i` : a token bucket (or sliding window counter) for the user's hard limit.
Operation:
On request from user i of tenant T:
1. Check the tenant's global bucket. If no token, reject.
2. Check the user's bucket. If no token, reject.
3. If both have tokens, consume one token from each and allow.
This gives:
- Isolation: tenants are separate.
- Quotas: both tenant and user have quotas (the user's quota is the hard limit).
- Fairness? Not exactly, because if we set the user's hard limit to the same as the tenant's, then one user can use all. But if we set the user's hard limit to a fraction of the tenant's, then we are enforcing that fraction. However, if the user's hard limit is set to the tenant's total, then we are not enforcing fairness.
So the fairness is in the configuration: the tenant must set the user's hard limit to a fair share.
But what if we want the rate limiter to automatically enforce that no user uses more than, say, 1/N of the tenant's total (where N is the number of active users)? Then we need to track active users and adjust the per-user limits dynamically.
Let's consider a dynamic fair share:
We track for the tenant T:
- The number of active users in the current interval (or sliding window). Let's call it N.
Then for each user i, we set a dynamic limit: (R / N) * weight_i, but we also have a hard limit H_i.
So the effective limit for user i is min(H_i, (R * weight_i) / N).
But note: if N changes, the limit changes. Also, if a user is inactive, they don't count in N.
Implementation:
We need to update N? How do we define active? A user is active in the current interval if they have made at least one request in the last, say, 1 minute (the same as the rate limiting window).
We can use a sliding window for the tenant's global usage, and then for each user we also have a sliding window. Then we can compute N as the number of users who have at least one request in the current window? But then we need to track per-user usage in the window to know if they are active.
Alternatively, we can use a Bloom filter or a set in Redis that records the users that have made a request in the current window? But then we need to clean up old users.
This becomes very heavy.
Given the complexity, I think the initial design (two-level token buckets) is more practical and meets the basic requirements of quotas and isolation. Fairness is achieved by setting the user's hard limit appropriately (so that the sum of all user hard limits is not more than the tenant's total, and each user's hard limit is set to a fair share).
However, the problem says "fairness" and "isolation". The two-level token bucket with hard limits per user and a global tenant limit does provide isolation (tenants are separate) and quotas (both tenant and user). Fairness is in the hands of the configuration.
But if we want the system to automatically enforce fairness (without the tenant having to set per-user limits), then we need a different approach.
Let's re-read: "tenant-aware rate limiter: quotas, fairness, and isolation."
Maybe the intended design is:
- Each tenant has a global rate limit.
- Within a tenant, the rate limit is shared equally among all users (or by weight) without any per-user configuration.
Then we can do:
For tenant T with rate R, and for each request from user i:
1. Check the tenant's global bucket (with rate R). If no token, reject.
2. Then, we need to check if the user i has exceeded their fair share in the current interval.
How to compute fair share? We need to know the number of active users in the current interval.
We can do:
Let N = number of distinct users of tenant T that have made at least one request in the current interval (say, the last 60 seconds).
Then the fair share for each user is R / N.
But then if a user makes multiple requests, we need to track how many requests they have made in the interval.
So we need:
- A global tenant bucket (to enforce total R).
- A per-user counter for the current interval (to track u_i).
Then for a request from user i:
if u_i >= (R / N) then reject? But note: if the tenant's global bucket has tokens, but the user has exceeded their fair share, we reject.
However, what if the tenant's global bucket is not empty and the user has not exceeded their fair share? We allow and then:
- Decrement the global bucket.
- Increment u_i.
But wait: if we do that, then the global bucket might run out before all users have reached their fair share? That's okay because the global bucket is the total.
But consider: if there are 2 users, and R=100, then each fair share is 50. If user1 makes 50 requests, then user2 can make 50. But what if user1 makes 60? Then at the 51st request for user1, we would reject because u_i > 50? But the global bucket might still have tokens? Then we are not using the global bucket fully? That's okay because we are enforcing fairness.
However, if user2 is idle, then user1 should be able to use more than 50? But in this algorithm, if user2 is idle, then N=1, so fair share for user1 becomes R/1 = 100. So user1 can use up to 100.
So we need to update N dynamically? How?
We can define active users as those who have made at least one request in the current interval. But then if user2 hasn't made any request, then N=1? But what if user2 made a request 59 seconds ago and then nothing? Then in a 60-second window, if we are using a sliding window of 60 seconds, then user2's request from 59 seconds ago is still in the window? Then N=2? But then user1's fair share is 50, but user2 hasn't made a request in the last, say, 50 seconds? That's not fair.
Alternatively, we can define active users as those who have made a request in the last T seconds (where T is the rate limiting window). Then if user2 made a request 59 seconds ago (in a 60-second window) then they are active? But if they only made one request 59 seconds ago, then they are using only 1/60 of their fair share? Then user1 is limited to 50 even though user2 is almost idle?
This is getting messy.
Given the time, I think we should go with a simpler design that is commonly used:
Design 1: Two-level token buckets with fixed per-user limits (hard limits) and a global tenant limit.
This is simple and meets:
- Quotas: both tenant and user have quotas (the user's quota is the hard limit, and the tenant's is the global).
- Isolation: tenants are separate.
- Fairness: if the per-user limits are set to fair shares (e.g., each user gets an equal share of the tenant's total), then it's fair. But if the tenant sets one user's limit to the tenant's total, then that user can take all.
But note: the global tenant limit will prevent the sum of users from exceeding the tenant's total. So even if we set each user's limit to the tenant's total, the global limit will ensure that the total doesn't exceed. However, if one user tries to use the tenant's total, they might be blocked by the global limit if other users are also active? Actually, no: the global limit is shared. So if user1 tries to use 100 and user2 tries to use 100, and the tenant total is 100, then both will be limited by the global bucket. But the per-user bucket for user1 and user2 are 100 each, so they won't be limited by their own bucket until they hit 100. But the global bucket will run out quickly and then both will be rejected. So it's as if we have a global bucket and then per-user buckets that are larger (or equal) to the global bucket? Then the per-user bucket is not the limiting factor, the global is.
So if we set the per-user hard limit to be equal to the tenant's total, then the per-user bucket doesn't limit, the global does. And then the fairness is determined by who gets the global tokens first? That could be random.
So to enforce fairness, we need the per-user limits to be set to the fair share. Then the global bucket will not be the bottleneck if the sum of per-user limits is less than or equal to the tenant's total? Actually, if the sum of per-user limits is less than the tenant's total, then the global bucket will not be exhausted? But then we are not using the tenant's full capacity? That's wasteful.
So we want: sum of per-user limits = tenant total? Then if all users try to use their full per-user limit, the tenant total is exactly used. But if one user is idle, then the other users can't use the idle user's share because their per-user limit is fixed? Then we are not allowing them to use the extra capacity.
So we need the per-user limits to be soft? That is, we want to allow a user to exceed their fair share if the tenant's total is not exceeded and other users are not using their share.
This brings us back to the dynamic fair share.
Given the complexity, I think we should implement:
Option A: Two-level fixed limits (hard limits per user and a global tenant limit). This is simple and provides isolation and quotas. Fairness is achieved by setting the per-user limits appropriately (so that the sum of per-user limits equals the tenant total and each user gets a fair share). But it doesn't allow a user to use more than their fixed limit even if the tenant has capacity and other users are idle.
Option B: Dynamic fair share with a global bucket and per-user counters, and a calculated fair share based on active users.
Let's try to design Option B:
We have:
- Tenant T with global rate limit R (per minute, for example).
- We use a sliding window of W (e.g., 60 seconds) for the tenant and for each user.
We maintain in Redis:
For tenant T:
- A sorted set (or a hyperloglog?) of the requests in the last W seconds? But we want to count the number of requests in the last W seconds. We can use a sliding window with a fixed window (e.g., every minute) but that's not smooth.
Alternatively, we can use a token bucket for the tenant (with rate R and burst B) and then for the user fair share we need to know:
Let U = current usage of tenant T in the last W seconds (we can get from a sliding window counter).
Let u_i = current usage of user i in the last W seconds.
Let N = number of distinct users of tenant T that have at least one request in the last W seconds.
Then the fair share for user i is: (R * w_i) / sum(w_j for j in active users)
But note: R is the rate per W seconds? If R is per minute and W=60, then R is the maximum in 60 seconds.
Then we allow if:
u_i < min( hard_limit_i, fair_share_i ) AND U < R ?
But wait, the global bucket already ensures U < R? Actually, the global bucket is a token bucket that refills at rate R over time. So if we use a token bucket for the tenant, then we don't need to track U separately? But then how do we compute N and the per-user usage for the fair share?
We need to track per-user usage in the same window W.
So we need:
- A global token bucket for the tenant (to enforce R).
- For each user, a sliding window counter for the last W seconds (to compute u_i and to know if they are active).
Then for a request from user i:
Step 1: Check the tenant's global token bucket. If no token, reject.
Step 2: Compute the current fair share for user i:
Let active_users = set of users with at least one request in the last W seconds (we can get by querying all user counters? That's expensive).
Let total_weight = sum of weights for active_users.
Let fair_share_i = (R * weight_i) / total_weight [but note: R is per W seconds?]
Step 3: Check if the user i's current usage in the last W seconds (u_i) is less than min(hard_limit_i, fair_share_i). If not, reject.
Step 4: If passed, then:
- Consume a token from the tenant's global bucket.
- Record the request for user i in the sliding window.
This is complex because:
- We need to maintain a sliding window for each user (which can be done with a sorted set in Redis, but for many users and many requests, it's heavy).
- We need to compute the set of active users and their total weight for every request? That's O(number of active users) per request, which could be high.
We can try to optimize:
Instead of computing the fair share for every request, we can update the fair share periodically (every second?) and cache it? But then if a new user becomes active, we need to update.
Alternatively, we can use a different algorithm:
We can assign each user a weight and then use a weighted fair queuing (WFQ) for the tokens? But in a distributed system, we need a central scheduler? That's not scalable.
Given the complexity, I think for a production system we would use a simpler approach:
We use a token bucket for the tenant (rate R) and then for each user we use a token bucket with rate = min(hard_limit_i, R) and then we also have a "burst" factor? But that doesn't give dynamic fairness.
Alternatively, we can use the "cell-based" rate limiting (like in AWS API Gateway) where we have:
- A global limit for the tenant.
- Per-user limits that are fixed.
And then we rely on the tenant to set the per-user limits to fair shares.
Given the time, I'll design the two-level fixed limit system (Option A) because it's simpler and meets the basic requirements of quotas and isolation. Fairness is achieved by configuration.
Implementation details for Option A:
We'll use Redis to store:
For tenant T:
- Key: `rate_limit:tenant:T:global`
- Value: a token bucket structure. We can use a Redis script to implement a token bucket (with `INCRBY` and `EXPIRE` for fixed window? or use `CL.THROTTLE` if using Redis 7.0?).
For user i of tenant T:
- Key: `rate_limit:tenant:T:user:i`
- Value: a token bucket for the user's hard limit.
We can use the Redis `CL.THROTTLE` command if available, or implement with Lua scripts.
Steps for a request:
1. Check the tenant's global bucket: call `CL.THROTTLE` with the tenant's rate and burst.
2. Check the user's bucket: call `CL.THROTTLE` with the user's rate and burst.
3. If both are allowed (return 0 or 1 for allowed?), then proceed.
But note: `CL.THROTTLE` returns the number of seconds to wait until a token is available. We can check if it's 0.
Alternatively, we can do:
We run two scripts (or one script that does both) that:
- Check the tenant bucket and if allowed, decrement the tenant bucket and then check the user bucket and if allowed, decrement the user bucket and return allowed.
But note: we don't want to decrement the tenant bucket if the user bucket fails? Actually, we do? Because if the user is over their limit, we don't want to count against the tenant? Or do we? The tenant's bucket is for all requests, even if the user is over their limit? That doesn't make sense.
We want:
- If the tenant is over, reject.
- If the user is over, reject.
And we don't want to consume a tenant token if the user is over? Actually, we do? Because the tenant's limit is for all requests, including those from users that are over their limit? But then if the user is over their limit, we are still consuming the tenant's token? That might be acceptable because the tenant's limit is the total, and the user's limit is an additional constraint.
But then if the user is over their limit, we reject and we don't want to count that request against the tenant? Because the request was not served.
So we should:
- First check the tenant: if not allowed, reject without touching the user bucket.
- Then check the user: if not allowed, reject without consuming the tenant token? But then the tenant token was already consumed in the first check? We need to do:
Option 1: Check both without consuming, then if both are okay, consume both.
Option 2: Consume the tenant token only if the user is also okay? But that requires a two-phase commit.
We can do:
Use a Lua script that:
local tenant_key = KEYS[1]
local user_key = KEYS[2]
local tenant_limit = tonumber(ARGV[1])
local tenant_burst = tonumber(ARGV[2])
local user_limit = tonumber(ARGV[3])
local user_burst = tonumber(ARGV[4])
-- Check tenant
local tenant_remaining = redis.call('CL.THROTTLE', tenant_key, tenant_limit, tenant_burst, 1)
if tenant_remaining[1] == 0 then
-- tenant allowed
-- Now check user
local user_remaining = redis.call('CL.THROTTLE', user_key, user_limit, user_burst, 1)
if user_remaining[1] == 0 then
-- both allowed
return 0 -- allowed
else
-- user not allowed, but we already consumed a tenant token? We need to rollback the tenant token?
-- We can't rollback easily. So we should check without consuming first?
end
else
return 1 -- tenant not allowed
end
The problem: `CL.THROTTLE` with the `INCREASE` parameter set to 1 will consume a token. We don't want to consume the tenant token if the user is not allowed.
So we need to:
Step 1: Check the tenant without consuming? `CL.THROTTLE` with `INCREASE` 0? But the command doesn't have a "peek" option.
We can implement our own token bucket with Lua that allows peeking.
Alternatively, we can do:
First, we check the tenant with `INCREASE` 0? But then we have to implement the token bucket ourselves.
Let's implement a simple token bucket in Lua:
We store:
- For each key (tenant or user), we store:
- tokens: current number of tokens (float)
- last_refill: timestamp of last refill
Then the function:
function allow(key, rate, burst, now)
-- Get the current tokens and last_refill
local tokens = redis.call('HGET', key, 'tokens')
local last_refill = redis.call('HGET', key, 'last_refill')
if tokens == false then
tokens = burst
last_refill = now
else
tokens = tonumber(tokens)
last_refill = tonumber(last_refill)
end
-- Refill: tokens = min(burst, tokens + (now - last_refill) * rate)
local delta = now - last_refill
local refill_amount = delta * rate
tokens = math.min(burst, tokens + refill_amount)
last_refill = now
if tokens >= 1 then
tokens = tokens - 1
-- Save
redis.call('HMSET', key, 'tokens', tokens, 'last_refill', last_refill)
return 1 -- allowed
else
-- Save the updated tokens (which might have increased) and last_refill?
redis.call('HMSET', key, 'tokens', tokens, 'last_refill', last_refill)
return 0 -- not allowed
end
end
But note: this is a standard token bucket. However, we want to check without consuming? Then we can have:
function peek(key, rate, burst, now)
-- similar but don't decrement tokens if allowed.
Then our main script:
local tenant_allowed = peek(tenant_key, tenant_rate, tenant_burst, now)
if tenant_allowed == 0 then
return 0 -- tenant not allowed
end
local user_allowed = peek(user_key, user_rate, user_burst, now)
if user_allowed == 0 then
return 0 -- user not allowed
end
-- Now both are allowed, so we consume:
allow(tenant_key, tenant_rate, tenant_burst, now)
allow(user_key, user_rate, user_burst, now)
return 1
But note: between the peek and the allow, the state might change? We are in a Lua script, so it's atomic.
However, we are doing two peeks and then two allows. But the allows will refill again? That's okay because we are using the same `now` for both? We should use the same `now` for both peeks and allows? Actually, we should use the same `now` for the entire operation to be consistent.
Let's adjust:
We get `now` at the beginning and use it throughout.
But note: the token bucket algorithm uses the time since last refill. If we do:
Step1: peek tenant -> gets tokens and last_refill, computes new tokens based on now, but doesn't update last_refill.
Step2: peek user -> same.
Then when we allow, we update the tokens and last_refill for each. But then the next time, the last_refill will be set to `now` (the time of the allow). That means we are not refilling between the peek and the allow? That's acceptable because the time difference is very small.
Alternatively, we can do:
We can combine the two token buckets into one script that updates both if allowed.
However, the above script with two peeks and two allows is not atomic because between the two allows, another request could change the state? But we are in a Lua script, so the entire script runs atomically. But we are doing:
peek tenant -> returns allowed or not.
peek user -> returns allowed or not.
Then if both allowed, we do:
allow tenant
allow user
But what if between the two allows, the state changed? It didn't because we are in the same script and we haven't released the lock. However, note that the `allow` function does a refill based on the current time (which is the same `now` we passed) and then decrements. But the `peek` we did earlier used the same `now` and we got the tokens at that time. Then when we do `allow`, we are refilling again with the same `now`? That would double the refill? Actually, the `allow` function will refill again with the same `now`? But we already computed the tokens in the peek? We are not storing the intermediate tokens.
We need to restructure:
We can compute the new tokens for tenant and user in the peek, then if both are allowed, we set the tokens to the new tokens (after refill) minus 1, and set last_refill to now.
Alternatively, we can write a script that does:
local now = redis.call('TIME')[1] -- current time in seconds (integer)
-- For tenant
local tenant_data = redis.call('HMGET', tenant_key, 'tokens', 'last_refill')
local tenant_tokens = tonumber(tenant_data[1]) or burst
local tenant_last = tonumber(tenant_data[2]) or now
local tenant_refill = (now - tenant_last) * tenant_rate
tenant_tokens = math.min(burst, tenant_tokens + tenant_refill)
local tenant_allowed = 0
if tenant_tokens >= 1 then
tenant_allowed = 1
tenant_tokens = tenant_tokens - 1
end
-- Similarly for user.
if tenant_allowed == 1 and user_allowed == 1 then
redis.call('HMSET', tenant_key, 'tokens', tenant_tokens, 'last_refill', now)
redis.call('HMSET', user_key, 'tokens', user_tokens, 'last_refill', now)
return 1
else
-- We don't update because we didn't consume.
return 0
end
But note: if the tenant is allowed but the user is not, we don't update the tenant? Then the tenant's tokens are not decremented? That's what we want: we only consume the tenant token if the user is also allowed.
However, we did refill the tenant's tokens in our computation, but we didn't save them? Then the next time, we will refill again from the old last_refill? That's a problem.
We need to update the tenant's tokens even if we don't consume? Because we refilled based on the current time. But if we don't update, then the next time we will refill again from the old last_refill, which is wrong.
So we must update the tenant's tokens (and last_refill) even if we don't consume? But then we are updating the state even when we reject? That might be acceptable because we are refilling the tokens (which is idempotent) but we are setting the last_refill to now? That would break the refill because the next refill will be from now, so we lose the time between now and the next request.
Actually, the token bucket algorithm: we should update the last_refill only when we consume? Or every time we check? The standard is to update the last_refill only when we consume? Because if we update the last_refill without consuming, then the next refill will be from that time, and we might not refill enough.
Let's think:
We have a bucket that refills at a constant rate. The state is (tokens, last_refill). When we check, we should update the tokens to the current time (by refilling) but not update last_refill until we consume? Actually, the standard algorithm:
tokens = min(burst, tokens + (now - last_refill) * rate)
if tokens >= 1:
tokens -= 1
last_refill = now -- because we consumed now.
So we update last_refill only on consume.
Therefore, in our script:
We compute the current tokens (by refilling from last_refill to now) and then:
if we are going to consume, we set tokens to current_tokens - 1 and last_refill to now.
if we are not going to consume, we do not update the state? But then the next time we check, we will refill from the old last_refill to the new now, which is correct.
So:
Step 1: for tenant, compute current_tokens (by refilling from last_refill to now) but do not update last_refill.
Step 2: for user, same.
Step 3: if both current_tokens >= 1, then we consume:
set tenant tokens to current_tokens - 1 and last_refill to now.
set user tokens to current_tokens - 1 and last_refill to now.
else, do nothing.
This is correct.
So the script:
local now = redis.call('TIME')[1]
-- Tenant
local tenant_data = redis.call('HMGET', tenant_key, 'tokens', 'last_refill')
local tenant_tokens = tonumber(tenant_data[1])
local tenant_last = tonumber(tenant_data[2])
if tenant_tokens == nil then
tenant_tokens = tenant_burst
tenant_last = now
else
local delta = now - tenant_last
local refill = delta * tenant_rate
tenant_tokens = math.min(tenant_burst, tenant_tokens + refill)
end
-- User
local user_data = redis.call('HMGET', user_key, 'tokens', 'last_refill')
local user_tokens = tonumber(user_data[1])
local user_last = tonumber(user_data[2])
if user_tokens == nil then
user_tokens = user_burst
user_last = now
else
local delta = now - user_last
local refill = delta * user_rate
user_tokens = math.min(user_burst, user_tokens + refill)
end
if tenant_tokens >= 1 and user_tokens >= 1 then
-- consume
tenant_tokens = tenant_tokens - 1
user_tokens = user_tokens - 1
redis.call('HMSET', tenant_key, 'tokens', tenant_tokens, 'last_refill', now)
redis.call('HMSET', user_key, 'tokens', user_tokens, 'last_refill', now)
return 1
else
return 0
end
This script does:
- Refill both buckets to the current time (without updating last_refill).
- Check if both have at least 1 token.
- If yes, consume one from each and set last_refill to now.
- If no, do nothing.
This is atomic.
We assume that the rate and burst are provided as arguments.
We also need to set an expiration on the keys? We can set a TTL when we create the key? But the token bucket will keep growing tokens up to burst, so we don't want to expire the key too soon. We can set a TTL of, say, 2*burst/rate? But that might be long.
Alternatively, we can not set TTL and let the keys accumulate? But then we have to clean up old tenants and users.
We can have a separate process to clean up keys that haven't been used for a while.
But for simplicity, we can set a TTL on the keys when we create them? Actually, we don't create them, we update them. We can set the TTL every time we update? That might be heavy.
Alternatively, we can use Redis key expiration with a long TTL (e.g., 1 day) and then have a background job to delete keys that haven't been updated for a day.
Given the scale, we might have many tenants and users. We need to consider memory.
We can also use a different data structure? But the above is simple.
This design meets:
- Quotas: tenant and user have fixed quotas (the rate and burst for each).
- Isolation: each tenant and user has their own key.
- Fairness: by setting the user's rate and burst to a fair share of the tenant's.
However, it does not allow dynamic adjustment based on active users.
But if we want dynamic fairness, we would need to change the user's rate on the fly? That's complex.
Conclusion:
We'll implement the two-level fixed limit token bucket with the above Lua script.
Steps:
1. We have a configuration for each tenant:
- tenant_rate, tenant_burst.
- For each user under the tenant: user_rate, user_burst.
2. When a request comes, we run the Lua script with:
KEYS[1] = "rate_limit:tenant:" .. tenant_id .. ":global"
KEYS[2] = "rate_limit:tenant:" .. tenant_id .. ":user:" .. user_id
ARGV[1] = tenant_rate
ARGV[2] = tenant_burst
ARGV[3] = user_rate
ARGV[4] = user_burst
3. The script returns 1 if allowed, 0 if not.
We can also extend to have multiple user identifiers (like API key, user id, etc.) but the idea is the same.
For fairness, the tenant's configuration should set the user's rate to a fair share of the tenant's rate. For example, if the tenant has rate 100 and 2 users, set each user's rate to 50. Then if both users are active, they each get 50. If one is idle, the other can only get 50? That's not using the full 100. So we are not allowing the active user to use the idle user's share.
To allow that, we would need to set the user's rate to 100 (the tenant's rate) and then rely on the tenant's global bucket to limit the total? But then one user could use 100 and the other 0? That's not fair.
So we have a trade-off.
If we want to allow users to use extra capacity when others are idle, we need to set the user's rate to the tenant's rate (or higher) and then rely on the global bucket to limit the total. But then if both are active, they might each try to use 100 and the global bucket will allow only 100 in total? Then they will share the 100 arbitrarily (based on who gets the tokens first). That's not fair either.
So the fixed per-user limit is not enough for dynamic fairness.
Given the complexity of dynamic fairness, I think we should stick to fixed per-user limits and let the tenant configure them appropriately.
If the tenant wants to allow users to use extra capacity, they can set the user's rate to the tenant's rate and then use a different algorithm for the global bucket? But then the global bucket will be the bottleneck and the per-user bucket won't limit? Then we are back to just a global bucket.
So maybe we don't need the per-user bucket? But then we can't enforce per-user limits.
The requirement says "quotas" which implies per-user quotas.
So we keep both.
Final design:
We have two levels of rate limiting:
Tenant global: rate R_T, burst B_T.
User: rate R_U, burst B_U.
We enforce both.
The tenant must set R_U such that the sum of R_U for all users is not more than R_T (to avoid wasting capacity) and each R_U is set to the fair share.
If the tenant wants to allow users to exceed their fair share when others are idle, they can set R_U to a higher value (up to R_T) and then the global bucket will limit the total. But then if two users are active, they might each try to use R_T and the global bucket will only allow R_T in total, so they will be limited by the global bucket. But the per-user bucket won't limit because R_U is high. So the per-user bucket becomes irrelevant? Then why have it?
We have it to enforce a maximum per user. So if we set R_U to R_T, then the per-user bucket doesn't limit (unless the user tries to use more than R_T, which the global bucket will also limit). So the per-user bucket is only effective if R_U < R_T.
Therefore, to enforce a fair share, we set R_U = R_T / N (where N is the number of users). Then the per-user bucket will limit each user to R_T/N, and the global bucket will ensure the total doesn't exceed R_T.
But then if one user is idle, the other users cannot use more than R_T/N because their per-user bucket limits them. So we are not using the full R_T.
To allow using the full R_T when some users are idle, we need to adjust R_U dynamically. That's the dynamic fair share.
Given the time, I think we should implement the fixed limits and then if the requirement for dynamic fairness is strong, we can extend later.
So the answer: we build a two-level token bucket with fixed limits for tenant and user.
We'll write the Lua script as above.
We also need to handle the case where the tenant or user doesn't exist? We initialize with burst.
We also need to consider that the rate and burst might be floating point? We use integers for simplicity? We can use fixed-point arithmetic (multiply by 1000 and use integers).
Let's adjust the script for integer arithmetic:
We store tokens as integer (but we do fractional refill?).
We can do:
tokens = tokens + (now - last_refill) * rate
but if rate is, say, 100 per minute, then per second it's 100/60 = 1.666... We can use fixed point: multiply by 1000 and then divide by 1000.
Alternatively, we can use the `CL.THROTTLE` command which handles this.
Since Redis 7.0 has CL.THROTTLE, we can use that if available.
But the problem says "build", so we might not assume Redis 7.0.
We'll implement our own with fixed-point.
Let's use:
rate = requests per minute, but we want per second? Actually, the token bucket is usually in terms of tokens per second.
We can let the rate be in tokens per second, and burst in tokens.
Then in the script:
local delta = now - last_refill -- in seconds
local refill = delta * rate -- this is fractional, so we use fixed point: store rate as integer (e.g., rate * 1000) and then refill = (delta * rate) / 1000
But then tokens are stored as integer? We can store tokens as fixed point (multiplied by 1000). Or we can use floating point in Lua? Redis stores numbers as strings, but we can use floating point in Lua and then store as string? But then we have to convert.
Alternatively, we can do:
We store tokens as integer (the number of tokens, where 1 token = 1 request). Then we do:
refill = math.floor(delta * rate) -- but that loses fractional part.
To avoid fractional, we can set the rate to be an integer (requests per minute) and then use a window of 1 minute? But then we are not smooth.
Actually, the token bucket is smooth: it refills continuously.
We can do:
Let rate be tokens per second (float). We store tokens as float in Lua and then store as string in Redis.
But then we have to do string to float conversion, which is slow.
Alternatively, we can use fixed point with a scaling factor (e.g., 1000). Then:
rate_fixed = rate * 1000 (integer)
tokens_fixed = tokens * 1000 (integer)
Then refill = (delta * rate_fixed) / 1000 -> but we do integer division? We want to keep the fractional part in tokens_fixed.
So:
tokens_fixed = tokens_fixed + delta * rate_fixed
Then when checking if tokens_fixed >= 1000 (because we want to consume 1 token, which is 1000 in fixed point).
And when we consume, we subtract 1000.
Then we store tokens_fixed as integer.
Example:
rate = 1.5 tokens per second -> rate_fixed = 1500
burst = 10 tokens -> burst_fixed = 10000
initial tokens_fixed = burst_fixed = 10000.
after 1 second: tokens_fixed = 10000 + 1 * 1500 = 11500.
then we can consume 1 token (10000 -> 10500? Wait, we subtract 1000? Actually, 1 token = 1000 in fixed point? Then we set:
1 token = 1000 fixed units.
Then:
tokens_fixed = tokens_fixed + delta * rate_fixed (this is in fixed units per second)
And we check if tokens_fixed >= 1000.
Then consume: tokens_fixed = tokens_fixed - 1000.
So we set:
token_value = 1000 (so 1 token = 1000 fixed units)
Then:
rate_fixed = rate * token_value (so if rate=1.5, then rate_fixed=1500)
burst_fixed = burst * token_value
Then the refill is: tokens_fixed = tokens_fixed + delta * rate_fixed
And we check tokens_fixed >= token_value.
This works.
Let's adjust the script for fixed point:
We'll use a scaling factor of 1000.
ARGV[1] = tenant_rate (float) -> we'll convert to fixed: tenant_rate_fixed = tenant_rate * 1000
ARGV[2] = tenant_burst (integer) -> tenant_burst_fixed = tenant_burst * 1000
Similarly for user.
Then in the script:
local token_value = 1000
local tenant_rate_fixed = tonumber(ARGV[1]) * token_value -- but ARGV[1] is string, so we do: tonumber(ARGV[1]) * token_value
local tenant_burst_fixed = tonumber(ARGV[2]) * token_value
Then we store tokens_fixed and last_refill.
When refilling:
tokens_fixed = math.min(tenant_burst_fixed, tokens_fixed + (now - last_refill) * tenant_rate_fixed)
Then check if tokens_fixed >= token_value.
Then consume: tokens_fixed = tokens_fixed - token_value.
Then store tokens_fixed and set last_refill = now.
But note: (now - last_refill) is in seconds (integer or float? Redis TIME returns seconds and microseconds? We get seconds from TIME? Actually, TIME returns [seconds, microseconds]. We can use seconds and ignore microseconds? Or use microseconds for more precision.
We can use:
local time = redis.call('TIME')
local now = time[1] + time[2]/1000000.0 -- now in seconds with microseconds.
But then (now - last_refill) is fractional.
We can store last_refill as a float (seconds with microseconds) and then compute delta as float.
Alternatively, we can use microseconds:
now = time[1] * 1000000 + time[2] -- in microseconds.
last_refill stored in microseconds.
Then delta = now - last_refill (in microseconds)
Then refill = delta * (rate_fixed / 1000000) because rate_fixed is per second? Actually, rate_fixed is per second? We set rate_fixed = rate * 1000, and rate is per second? Then:
refill = delta * (rate_fixed / 1000000) because delta is in microseconds and rate_fixed is per second (so per microsecond it's rate_fixed / 1000000).
But then we are doing:
tokens_fixed = tokens_fixed + delta * rate_fixed / 1000000
This is fractional? We want to keep tokens_fixed as integer? Then we can do:
tokens_fixed = tokens_fixed + math.floor(delta * rate_fixed / 1000000)
But that loses fractional tokens? Actually, we are using fixed point with 1000 scaling, so we want to keep the fractional part? We are storing tokens_fixed as integer (which is the fixed point representation). Then:
tokens_fixed = tokens_fixed + (delta * rate_fixed) // 1000000 -- integer division.
But then we are rounding down? That's acceptable.
Alternatively, we can store tokens_fixed as float and then store as string? But then we have to convert.
Let's do:
We store tokens_fixed as integer (the fixed point representation).
We store last_refill as integer (microseconds).
Then:
local delta = now - last_refill -- in microseconds
local refill = math.floor(delta * rate_fixed / 1000000) -- integer, because we are using fixed point with 1000 scaling, so we are adding integer number of fixed units.
But note: rate_fixed = rate * 1000, so:
refill = math.floor(delta * (rate * 1000) / 1000000) = math.floor(delta * rate / 1000)
That's not correct? Because:
We want to add: (delta seconds) * rate tokens, but in fixed point: (delta_seconds * rate) * 1000 = (delta_microseconds/1000000) * rate * 1000 = delta_microseconds * rate / 1000.
So:
refill = math.floor(delta * rate / 1000) -- but delta is in microseconds.
Example: rate = 1.5 tokens per second, then in 1 second (1000000 microseconds) we should add 1.5 tokens -> 1500 fixed units.
delta = 1000000, rate=1.5 -> refill = math.floor(1000000 * 1.5 / 1000) = math.floor(1500) = 1500. Correct.
But if delta=500000 (0.5 seconds), then refill = math.floor(500000 * 1.5 / 1000) = math.floor(750) = 750. Correct.
So:
refill = math.floor(delta * rate / 1000)
But note: rate is a float, delta is integer. We do: delta * rate / 1000, then floor.
However, we are using rate_fixed = rate * 1000, so:
refill = math.floor(delta * rate_fixed / 1000000) -> same as above.
So we can do:
refill = math.floor(delta * rate_fixed / 1000000)
where rate_fixed is an integer (rate * 1000).
Then tokens_fixed = math.min(burst_fixed, tokens_fixed + refill)
This seems correct.
Let's write the script with microseconds:
local time = redis.call('TIME')
local now = time[1] * 1000000 + time[2] -- now in microseconds
-- For tenant:
local tenant_data = redis.call('HMGET', tenant_key, 'tokens_fixed', 'last_refill')
local tenant_tokens_fixed = tonumber(tenant_data[1])
local tenant_last = tonumber(tenant_data[2])
if tenant_tokens_fixed == nil then
tenant_tokens_fixed = tenant_burst_fixed
tenant_last = now
else
local delta = now - tenant_last
local refill = math.floor(delta * tenant_rate_fixed / 1000000)
tenant_tokens_fixed = math.min(tenant_burst_fixed, tenant_tokens_fixed + refill)
end
-- Similarly for user.
if tenant_tokens_fixed >= token_value and user_tokens_fixed >= token_value then
tenant_tokens_fixed = tenant_tokens_fixed - token_value
user_tokens_fixed = user_tokens_fixed - token_value
redis.call('HMSET', tenant_key, 'tokens_fixed', tenant_tokens_fixed, 'last_refill', now)
redis.call('HMSET', user_key, 'tokens_fixed', user_tokens_fixed, 'last_refill', now)
return 1
else
return 0
end
But note: we are not updating the state if we don't consume? That's correct because we only update last_refill when we consume.
However, we are not updating the tokens_fixed if we don't consume? But we did refill in our local variable? We are not saving that refill? That's correct because we don't want to update the last_refill without consuming. But then the tokens_fixed we computed (with refill) is not saved? So the next time, we will refill from the old last_refill, which is correct.
But what about the tokens_fixed? We computed a new tokens_fixed (with refill) but didn't save it? Then the next time we compute, we will refill from the old last_refill to the new now, which will give the same result? Actually, if we don't update the tokens_fixed, then the next time we will compute:
tokens_fixed = old_tokens_fixed + (now_new - old_last_refill) * rate_fixed / 1000000
But if we had updated the tokens_fixed (without consuming) then we would have:
tokens_fixed = old_tokens_fixed + (now - old_last_refill) * rate_fixed / 1000000 [and then set last_refill to now?]
But we don't update last_refill without consuming? Then the next time, the delta will be from old_last_refill to now_new, which is larger than from old_last_refill to now? So we are double counting the refill? That's why we don't update the tokens_fixed without consuming.
So the above script is correct.
However, we are not updating the tokens_fixed (the refill) when we don't consume? That means the tokens_fixed in the hash is stale? But that's okay because the next time we will refill from the old last_refill to the current now, which will give the correct tokens_fixed.
Example:
Initially: tokens_fixed=10000, last_refill=0.
At time=1 second (1000000 microseconds):
delta = 1000000
refill = floor(1000000 * 1500 / 1000000) = 1500
tokens_fixed = 10000 + 1500 = 11500.
If we don't consume, we don't update. Then at time=2 seconds:
delta = 2000000
refill = floor(2000000 * 1500 / 1000000) = 3000
tokens_fixed = 10000 + 3000 = 13000.
But if we had updated at time=1, then at time=2:
tokens_fixed = 11500, last_refill=1000000.
delta = 1000000
refill = 1500
tokens_fixed = 11500+1500=13000.
Same result.
So it's okay.
We'll use this script.
We also need to set an initial burst? We set the initial tokens_fixed to burst_fixed.
We'll store:
key:
"rate_limit:tenant:<tenant_id>:global" -> hash with fields: tokens_fixed, last_refill
"rate_limit:tenant:<tenant_id>:user:<user_id>" -> hash with fields: tokens_fixed, last_refill
We can also set an expiration on these keys? We can set a TTL when we create them? But we don't create them, we update them. We can set a TTL every time we update? That would be expensive and might cause keys to expire while still in use.
Alternatively, we can set a long TTL (e.g., 1 day) and then have a background job to clean up keys that haven't been updated for more than a day.
We'll do:
When we update the key (in the allow case), we set an EXPIRE for, say, 86400 seconds (1 day) if the key doesn't have an expiration? But then we are setting the expiration every time? That's expensive.
We can set the expiration only when we create the key? But we don't know when the key is created (the first time). We can do:
In the script, when we find that the key doesn't exist (tokens_fixed is nil), we set the key with tokens_fixed and last_refill, and then set an EXPIRE? But then we have to do multiple commands.
We can do:
In the script, after we set the key (in the allow case), we do:
redis.call('EXPIRE', key, 86400)
But then if the key already exists, we don't set the expiration? Then the key might never expire? We want to set the expiration only when we create the key? We can check if the key exists? But we just set it.
Alternatively, we can set the expiration every time we update? That would reset the TTL every request, which might be acceptable if we have a long TTL.
Let's set the TTL to 1 day and set it every time we update? That way, if a key is used every day, it won't expire.
But then if a key is not used for a day, it will expire.
We can do:
In the script, after we update the key (in the allow case), we set the TTL to 86400.
But note: if we do that, then every request resets the TTL? That might be acceptable.
However, if we are not allowing (reject), we don't update the key, so the TTL won't be reset? Then the key might expire if there are no allowed requests for a day? That's acceptable.
But what if there are only rejected requests? Then the key will expire and we lose the state? That's acceptable because if there are no allowed requests, then the rate limiter is not being used? But we might want to keep the state for rejected requests? Actually, we don't update the state on reject, so the key will expire.
We can also set the TTL when we create the key (the first time we set tokens_fixed and last_refill). But then if we only have rejected requests, the key will never be created? So we don't have a key to expire.
So we only set the TTL when we create the key? But then if we have a mix of allowed and rejected, the key will be created on the first allow and then we set TTL. Then if we have only rejected requests, the key won't be created? That's okay.
We can adjust the script:
When we initialize the key (tokens_fixed is nil), we set the key and then set the TTL.
But then we are doing:
if tenant_tokens_fixed == nil then
tenant_tokens_fixed = tenant_burst_fixed
tenant_last = now
redis.call('HMSET', tenant_key, 'tokens_fixed', tenant_tokens_fixed, 'last_refill', now)
redis.call('EXPIRE', tenant_key, 86400)
end
And similarly for user.
Then when we update (on allow), we don't set the TTL again? But then the TTL will be from the creation time? We want to extend the TTL on every allow? Actually, we want the key to live as long as it's being used. So we should reset the TTL on every allow? Or on every access?
We can reset the TTL on every allow? That way, if we have a request every day, the key won't expire.
But then we are doing an EXPIRE on every allow? That might be expensive.
Alternatively, we can set a long TTL (e.g., 30 days) and then have a background job to clean up old keys? That might be better.
Given the scale, we might have millions of keys. We can use a Redis key space notification to clean up? Or just let them expire.
Let's set the TTL to 30 days when we create the key, and then on every allow we reset the TTL to 30 days? That way, active keys are kept.
We can do:
In the allow branch:
redis.call('HMSET', ...)
redis.call('EXPIRE', tenant_key, 2592000) -- 30 days
redis.call('EXPIRE', user_key, 2592000)
But then we are setting the TTL for both keys every allow? That's two EXPIRE commands per request.
We can avoid if we don't care about exact expiration? We can set the TTL only when we create the key? Then if a key is used once and then not for 30 days, it will expire. But if it's used every day, the TTL will be from the creation? So if we create the key and then use it 29 days later, it will expire the next day? That's not good.
So we should reset the TTL on every allow.
Alternatively, we can use a separate process to update the TTL? But that's complex.
Given that the rate limiter is on the critical path, we want to minimize commands. We can skip the TTL setting in the script and have a separate process that runs periodically to delete keys that haven't been updated for, say, 30 days.
How to track last update? We have last_refill in the hash. We can scan keys and check last_refill? That's heavy.
Alternatively, we can set a TTL on the key when we create it and then every time we update (on allow) we reset the TTL? We can do:
In the allow branch, after updating the hash, we do:
redis.call('EXPIRE', tenant_key, 2592000)
But note: we are updating the tenant key and the user key. We have to do two EXPIREs.
We can also set the TTL on the hash fields? No.
Given the overhead, we might skip the TTL and rely on a separate cleanup process that deletes keys that haven't been updated for 30 days (by checking the last_refill field). But that requires scanning all keys? We can use a Redis set to track active keys? That's another data structure.
Alternatively, we can use Redis key expiration by setting a TTL on the key when we create it and then every time we update we reset the TTL? We'll do that.
We'll set the TTL to 30 days (2592000 seconds) on every allow.
So the script becomes:
... [previous code] ...
if tenant_tokens_fixed >= token_value and user_tokens_fixed >= token_value then
tenant_tokens_fixed = tenant_tokens_fixed - token_value
user_tokens_fixed = user_tokens_fixed - token_value
redis.call('HMSET', tenant_key, 'tokens_fixed', tenant_tokens_fixed, 'last_refill', now)
redis.call('HMSET', user_key, 'tokens_fixed', user_tokens_fixed, 'last_refill', now)
redis.call('EXPIRE', tenant_key, 2592000)
redis.call('EXPIRE', user_key, 2592000)
return 1
else
return 0
end
But note: if the key didn't exist, we set it and set the TTL in the initialization part? Actually, in the initialization part we also set the key and then we should set the TTL? But in the initialization part, we are not in the allow branch? We are in the initialization for both tenant and user? We set the key and then we set the TTL? But we haven't decided to allow yet? We are just initializing.
We need to set the TTL when we create the key? We can do:
In the tenant initialization (if tenant_tokens_fixed == nil):
... set the hash ...
redis.call('EXPIRE', tenant_key, 2592000)
Similarly for user.
Then in the allow branch, we reset the TTL again? That's redundant but okay.
Alternatively, we can set the TTL only in the allow branch? But then if we initialize and then don't allow (because user not allowed) then the key is created but without TTL? Then it will never expire? That's bad.
So we set TTL in both places: when we initialize and when we allow.
But note: when we initialize, we are setting the key for the first time? Then we set the TTL. Then when we allow, we update the key and reset the TTL.
However, in the initialization, we are setting the key for tenant and user? But what if the user key exists but the tenant key doesn't? We are handling separately.
We'll do:
For tenant:
if tenant_tokens_fixed == nil then
tenant_tokens_fixed = tenant_burst_fixed
tenant_last = now
redis.call('HMSET', tenant_key, 'tokens_fixed', tenant_tokens_fixed, 'last_refill', now)
redis.call('EXPIRE', tenant_key, 2592000)
end
Similarly for user.
Then in the allow branch, we update and reset TTL.
But note: in the allow branch, we are updating both keys. We reset the TTL for both.
This should work.
However, we are doing a lot of commands. We can try to reduce:
We can set the TTL only once per key per request? We are setting it twice if we initialize and then allow? Actually, if we initialize and then allow in the same request, we set the TTL twice? That's okay.
But what if we initialize and then the user is not allowed? Then we set the TTL for the tenant and user keys (in the initialization) but then we don't allow? That's okay because we set the TTL when we created the key.
But note: in the initialization, we set the TTL for both keys, even if the user is not allowed? That's okay because we created the key.
However, we are creating the user key even if the user is not allowed? That might be a problem because we are creating a key for a user that doesn't exist? But we are given the user_id, so we assume that the user exists? Or we are creating the key on first use? That's acceptable.
We are creating the key for the user on first request? That's okay.
But what if the user is not allowed? We still create the key? Then we have a key for a user that might never be allowed? That's okay because we set a TTL and it will expire.
We can avoid creating the user key if the user is not allowed? But then the next time the user makes a request, we will create it. That's acceptable.
But in the script, we initialize the user key even if the user is not allowed? Actually, we initialize both tenant and user keys before checking? We do:
We get the tenant data and user data. If either is nil, we initialize them (with burst and now). Then we check the tokens.
So if the user is not allowed (because tokens_fixed < token_value) but we initialized the user key, then we have created the user key and set the TTL? That's okay.
We can change to initialize only if we are going to allow? But then we need to check without initializing? Actually, we need to initialize to have a value to check? We can initialize only if the key doesn't exist and then check? But then if the key doesn't exist, we initialize and then check? That's what we do.
So it's fine.
We'll go with this.
Summary:
We have a Lua script that:
1. Gets the current time in microseconds.
2. For tenant key and user key:
- If the key doesn't exist, initialize tokens_fixed to burst_fixed and last_refill to now, and set TTL to 30 days.
- Else, refill the tokens_fixed based on the time elapsed (delta) and the rate_fixed.
3. Check if both tokens_fixed >= token_value (1000).
4. If yes, consume one token from each (subtract token_value), update the hash with new tokens_fixed and last_refill=now, and reset TTL to 30 days for both keys. Return 1.
5. Else, return 0.
This provides:
- Quotas: fixed rate and burst for tenant and user.
- Isolation: separate keys for each tenant and user.
- Fairness: by setting the user's rate to a fair share of the tenant's rate.
However, it does not provide dynamic fairness (adjusting to active users). But that's acceptable given the complexity.
We can extend later by changing the user's rate dynamically? But that would require updating the user's rate in the configuration and then the script would use the new rate? But the script uses the rate passed as argument. So we can change the rate in the configuration and the next request will use the new rate.
But if we want to adjust the user's rate based on the number of active users, we would need to compute that and then set the user's rate in Redis? That would be a separate process.
Given the time, we'll stick to fixed limits.
This is a reasonable design.
Let's write the final Lua script.
We assume:
token_value = 1000
ARGV[1] = tenant_rate (float, requests per second)
ARGV[2] = tenant_burst (integer, number of requests)
ARGV[3] = user_rate (float)
ARGV[4] = user_burst (integer)
KEYS[1] = tenant key
KEYS[2] = user key
Script:
local token_value = 1000
local tenant_rate_fixed = tonumber(ARGV[1]) * token_value
local tenant_burst_fixed = tonumber(ARGV[2]) * token_value
local user_rate_fixed = tonumber(ARGV[3]) * token_value
local user_burst_fixed = tonumber(ARGV[4]) * token_value
local time = redis.call('TIME')
local now = time[1] * 1000000 + time[2] -- microseconds
-- Tenant
local tenant_data = redis.call('HMGET', KEYS[1], 'tokens_fixed', 'last_refill')
local tenant_tokens_fixed = tonumber(tenant_data[1])
local tenant_last = tonumber(tenant_data[2])
if tenant_tokens_fixed == nil then
tenant_tokens_fixed = tenant_burst_fixed
tenant_last = now
redis.call('HMSET', KEYS[1], 'tokens_fixed', tenant_tokens_fixed, 'last_refill', tenant_last)
redis.call('EXPIRE', KEYS[1], 2592000)
else
local delta = now - tenant_last
local refill = math.floor(delta * tenant_rate_fixed / 1000000)
tenant_tokens_fixed = math.min(tenant_burst_fixed, tenant_tokens_fixed + refill)
end
-- User
local user_data = redis.call('HMGET', KEYS[2], 'tokens_fixed', 'last_refill')
local user_tokens_fixed = tonumber(user_data[1])
local user_last = tonumber(user_data[2])
if user_tokens_fixed == nil then
user_tokens_fixed = user_burst_fixed
user_last = now
redis.call('HMSET', KEYS[2], 'tokens_fixed', user_tokens_fixed, 'last_refill', user_last)
redis.call('EXPIRE', KEYS[2], 2592000)
else
local delta = now - user_last
local refill = math.floor(delta * user_rate_fixed / 1000000)
user_tokens_fixed = math.min(user_burst_fixed, user_tokens_fixed + refill)
end
if tenant_tokens_fixed >= token_value and user_tokens_fixed >= token_value then
tenant_tokens_fixed = tenant_tokens_fixed - token_value
user_tokens_fixed = user_tokens_fixed - token_value
redis.call('HMSET', KEYS[1], 'tokens_fixed', tenant_tokens_fixed, 'last_refill', now)
redis.call('HMSET', KEYS[2], 'tokens_fixed', user_tokens_fixed, 'last_refill', now)
redis.call('EXPIRE', KEYS[1], 2592000)
redis.call('EXPIRE', KEYS[2], 2592000)
return 1
else
return 0
end
We'll also consider that the same script can be used for multiple tenants and users.
We'll call this script with the appropriate keys and arguments.
This is a complete design.
Note: We are using a fixed window? Actually, the token bucket is a sliding window? The token bucket refills continuously, so it's a sliding bucket.
This script should be loaded into Redis once and then called with EVAL.
We assume that the rate and burst are set by the tenant administrator.
For fairness, the tenant should set the user_rate such that the sum of user_rates for all users is not more than tenant_rate. And each user_rate should be set to the fair share.
If the tenant wants to allow users to use more than their fair share when others are idle, they can set user_rate to tenant_rate (or higher) and then the tenant global bucket will limit the total. But then the user bucket won't limit until the user uses more than user_rate? But if user_rate is set to tenant_rate, then the user bucket won't limit because the tenant bucket will run out first? Actually, the user bucket might have more tokens (burst) but the rate is the same? Then the user bucket won't be the bottleneck.
So the per-user bucket is only effective if user_rate < tenant_rate.
Therefore, to enforce a fair share, set user_rate = tenant_rate / N (where N is the number of users).
This design is simple and meets the requirements.
We can extend it to have multiple levels (like per-application under user) by adding another level.
But for now, this should be sufficient.
Let me know if there are any questions.
I'll design a comprehensive tenant-aware rate limiter with quotas, fairness, and isolation. Here's a production-ready architecture:
Architecture Overview
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Client App │───▶│ Rate Limiter │───▶│ Backend API │
│ (Tenant A User) │ │ (Multi-tenant)│ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ Redis Cluster │
│ (State Storage) │
└─────────────────┘
Core Components
1. Multi-Level Quota System
class QuotaConfig:
"""Hierarchical quota configuration per tenant"""
def __init__(self):
# Global tenant quotas
self.global_requests_per_second = 1000
self.global_burst_size = 2000
self.global_daily_quota = 1_000_000
# Per-tier/user quotas (fairness)
self.user_tiers = {
'free': {'rps': 10, 'burst': 20, 'daily': 10_000},
'basic': {'rps': 100, 'burst': 200, 'daily': 100_000},
'premium': {'rps': 500, 'burst': 1000, 'daily': 500_000},
'enterprise': {'rps': 5000, 'burst': 10000, 'daily': 10_000_000}
}
# Isolation boundaries
self.isolation_levels = {
'strict': {'max_concurrent_users': 1, 'dedicated_shards': True},
'soft': {'max_concurrent_users': 10, 'dedicated_shards': False}
}
2. Fairness Algorithms
A. Weighted Fair Queuing (WFQ)
class WFQScheduler:
"""Fair distribution among active users within a tenant"""
def __init__(self, tenant_id):
self.tenant_id = tenant_id
self.virtual_times = {} # user_id -> virtual_time
self.last_update = time.time()
def allocate_tokens(self, user_id, weight=1.0):
"""Calculate fair share based on active users"""
now = time.time()
active_users = self.get_active_users(tenant_id=self.tenant_id)
# Calculate fair share: (total_tenant_quota * weight) / sum(weights)
total_weight = sum(active_users.values())
fair_share = (self.tenant_quota * weight) / total_weight
# Update virtual time for WFQ
if user_id not in self.virtual_times:
self.virtual_times[user_id] = 0
# virtual_time += fair_share / weight
self.virtual_times[user_id] += fair_share / weight
return min(fair_share, self.user_quotas[user_id])
B. Hierarchical Token Bucket (HTB)
Tenant (Root)
├── User Group A (Weight: 30%)
│ ├── User A1 (Guaranteed: 10%)
│ └── User A2 (Burstable: 20%)
├── User Group B (Weight: 70%)
│ ├── User B1 (Guaranteed: 20%)
│ └── User B2 (Burstable: 50%)
3. Isolation Strategies
class IsolationManager:
"""Enforce tenant isolation boundaries"""
ISOLATION_MODES = {
'PROCESS': 'separate_processes', # Complete isolation
'THREAD': 'thread_per_tenant', # Thread isolation
'CONNECTION': 'dedicated_connections', # Connection pool isolation
'LOGICAL': 'logical_namespaces' # Namespace isolation (default)
}
def __init__(self, tenant_id, mode='LOGICAL'):
self.tenant_id = tenant_id
self.mode = mode
self.isolation_boundary = self.create_boundary()
def create_boundary(self):
if self.mode == 'PROCESS':
return ProcessIsolation(self.tenant_id)
elif self.mode == 'THREAD':
return ThreadIsolation(self.tenant_id)
else:
return LogicalNamespaceIsolation(self.tenant_id)
def execute(self, func, *args, **kwargs):
"""Execute function within tenant isolation boundary"""
with self.isolation_boundary.context():
return func(*args, **kwargs)
4. Redis Storage Schema
# Tenant-level keys
rate_limit:tenant:{tenant_id}:global:rps
rate_limit:tenant:{tenant_id}:global:burst
rate_limit:tenant:{tenant_id}:daily:used
# User-level keys (with tier weighting)
rate_limit:tenant:{tenant_id}:user:{user_id}:rps
rate_limit:tenant:{tenant_id}:user:{user_id}:burst
rate_limit:tenant:{tenant_id}:user:{user_id}:tier
# WFQ state
rate_limit:tenant:{tenant_id}:wfq:virtual_time:{user_id}
rate_limit:tenant:{tenant_id}:wfq:active_users
# Isolation tracking
rate_limit:tenant:{tenant_id}:isolation:shard
rate_limit:tenant:{tenant_id}:isolation:connections
# Sliding window logs (for fairness calculation)
rate_limit:tenant:{tenant_id}:window:{user_id}:{minute_bucket}
5. Complete Rate Limiter Implementation
import redis
import time
import json
from typing import Dict, Optional
from dataclasses import dataclass
from collections import defaultdict
@dataclass
class RateLimitResult:
allowed: bool
remaining: int
reset_after: float
tenant_remaining: int
fair_share: float
isolation_violation: bool = False
class TenantAwareRateLimiter:
def __init__(
self,
redis_client: redis.Redis,
tenant_quotas: Dict[str, Dict],
fairness_algorithm: str = 'wfq',
isolation_level: str = 'LOGICAL'
):
self.redis = redis_client
self.tenant_quotas = tenant_quotas
self.fairness_alg = fairness_algorithm
self.isolation_mgr = IsolationManager(isolation_level)
def check_limit(
self,
tenant_id: str,
user_id: str,
cost: int = 1,
endpoint: Optional[str] = None
) -> RateLimitResult:
"""Main rate limiting check with fairness and isolation"""
# 1. Check tenant isolation (are we on correct shard?)
if not self._verify_isolation(tenant_id):
return RateLimitResult(
allowed=False,
remaining=0,
reset_after=0,
tenant_remaining=0,
fair_share=0,
isolation_violation=True
)
# 2. Check tenant global quota
tenant_ok, tenant_remaining, tenant_reset = self._check_tenant_quota(
tenant_id, cost
)
if not tenant_ok:
return RateLimitResult(
allowed=False,
remaining=tenant_remaining,
reset_after=tenant_reset,
tenant_remaining=tenant_remaining,
fair_share=0
)
# 3. Calculate fair share for user
fair_share = self._calculate_fair_share(tenant_id, user_id)
# 4. Check user quota with fairness
user_ok, user_remaining, user_reset = self._check_user_quota(
tenant_id, user_id, cost, fair_share
)
# 5. Apply isolation penalties if needed
if not user_ok:
self._apply_isolation_penalty(tenant_id, user_id)
return RateLimitResult(
allowed=user_ok,
remaining=min(tenant_remaining, user_remaining),
reset_after=max(tenant_reset, user_reset),
tenant_remaining=tenant_remaining,
fair_share=fair_share
)
def _calculate_fair_share(self, tenant_id: str, user_id: str) -> float:
"""Calculate dynamic fair share based on active users"""
if self.fairness_alg == 'wfq':
return self._calculate_wfq_share(tenant_id, user_id)
elif self.fairness_alg == 'htb':
return self._calculate_htb_share(tenant_id, user_id)
else:
# Simple equal distribution
active_users = self._get_active_user_count(tenant_id)
if active_users == 0:
return self.tenant_quotas[tenant_id]['global_requests_per_second']
return self.tenant_quotas[tenant_id]['global_requests_per_second'] / active_users
def _calculate_wfq_share(self, tenant_id: str, user_id: str) -> float:
"""Weighted Fair Queuing calculation"""
pipe = self.redis.pipeline()
# Get all active users with their weights
active_users = self._get_active_users_with_weights(tenant_id)
if not active_users:
return self.tenant_quotas[tenant_id]['global_requests_per_second']
# Calculate total weight
total_weight = sum(active_users.values())
# Get user's weight (from tier or default)
user_weight = active_users.get(user_id, 1.0)
# Fair share = (tenant_quota * user_weight) / total_weight
fair_share = (
self.tenant_quotas[tenant_id]['global_requests_per_second'] *
user_weight / total_weight
)
# Apply minimum guarantee (e.g., 10% of fair share)
min_guarantee = fair_share * 0.1
return max(fair_share, min_guarantee)
def _check_tenant_quota(self, tenant_id: str, cost: int) -> tuple:
"""Check tenant global quota using sliding window"""
key = f"rate_limit:tenant:{tenant_id}:global:rps"
now = time.time()
window = 60 # 60 second window
# Lua script for atomic check-and-increment
lua_script = """
local key = KEYS[1]
local now = tonumber(ARGV[1])
local cost = tonumber(ARGV[2])
local window = tonumber(ARGV[3])
local limit = tonumber(ARGV[4])
-- Remove old entries
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
-- Count current requests
local current = redis.call('ZCARD', key)
if current + cost <= limit then
-- Add new request
for i = 1, cost do
redis.call('ZADD', key, now, now .. ':' .. math.random())
end
redis.call('EXPIRE', key, window * 2)
return {1, limit - current - cost, window}
else
-- Get reset time (oldest entry + window)
local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
if oldest[2] then
local reset = tonumber(oldest[2]) + window - now
return {0, 0, math.max(0, reset)}
end
return {0, 0, window}
end
"""
result = self.redis.eval(
lua_script,
1,
key,
now,
cost,
window,
self.tenant_quotas[tenant_id]['global_requests_per_second']
)
allowed = bool(result[0])
remaining = int(result[1])
reset_after = float(result[2])
return allowed, remaining, reset_after
def _check_user_quota(
self,
tenant_id: str,
user_id: str,
cost: int,
fair_share: float
) -> tuple:
"""Check user quota with fairness consideration"""
user_tier = self._get_user_tier(tenant_id, user_id)
user_quota = self.tenant_quotas[tenant_id]['user_tiers'][user_tier]
# Get user's current usage
user_key = f"rate_limit:tenant:{tenant_id}:user:{user_id}:rps"
current_usage = self.redis.get(user_key) or 0
current_usage = int(current_usage)
# Allow if under both hard limit and fair share
hard_limit = user_quota['rps']
effective_limit = min(hard_limit, fair_share)
if current_usage + cost <= effective_limit:
# Increment usage (with expiration for sliding window)
pipe = self.redis.pipeline()
pipe.incrby(user_key, cost)
pipe.expire(user_key, 60) # Reset each minute
results = pipe.execute()
return True, int(effective_limit - (current_usage + cost)), 60
else:
return False, 0, 60
def _verify_isolation(self, tenant_id: str) -> bool:
"""Verify request is on correct isolation shard"""
expected_shard = self._get_tenant_shard(tenant_id)
current_shard = self.isolation_mgr.get_current_shard()
return expected_shard == current_shard
def _apply_isolation_penalty(self, tenant_id: str, user_id: str):
"""Apply penalty for exceeding isolation boundaries"""
penalty_key = f"rate_limit:tenant:{tenant_id}:isolation:penalties:{user_id}"
self.redis.incr(penalty_key)
self.redis.expire(penalty_key, 300) # 5 minute penalty
def _get_active_users_with_weights(self, tenant_id: str) -> Dict[str, float]:
"""Get active users with their tier weights"""
active_key = f"rate_limit:tenant:{tenant_id}:wfq:active_users"
users = self.redis.hgetall(active_key)
# Convert to weights based on tier
weighted_users = {}
for user_id, tier in users.items():
tier_config = self.tenant_quotas[tenant_id]['user_tiers'][tier]
# Weight based on tier (premium = 3x, enterprise = 10x)
weights = {'free': 1.0, 'basic': 2.0, 'premium': 3.0, 'enterprise': 10.0}
weighted_users[user_id] = weights.get(tier, 1.0)
return weighted_users
6. Distributed Coordination for Fairness
class FairnessCoordinator:
"""Coordinate fairness across multiple rate limiter instances"""
def __init__(self, redis_client: redis.Redis):
self.redis = redis_client
def record_user_activity(self, tenant_id: str, user_id: str):
"""Track active users for WFQ calculation"""
key = f"rate_limit:tenant:{tenant_id}:wfq:active_users"
self.redis.hsetnx(key, user_id, self._get_user_tier(tenant_id, user_id))
self.redis.expire(key, 300) # 5 minute activity timeout
def get_fair_share(self, tenant_id: str, user_id: str) -> float:
"""Get fair share from coordinator (consensus across instances)"""
coord_key = f"rate_limit:coordinator:{tenant_id}:fair_share"
# Use Redis Redlock for consensus
lock = self.redis.lock(f"{coord_key}:lock", timeout=5)
with lock:
fair_shares = self.redis.hgetall(coord_key)
if user_id not in fair_shares:
# Recalculate fair share
active_users = self._get_active_users(tenant_id)
total_quota = self._get_tenant_quota(tenant_id)
for uid, weight in active_users.items():
fair_shares[uid] = (total_quota * weight) / sum(active_users.values())
# Store calculated shares
self.redis.hmset(coord_key, fair_shares)
self.redis.expire(coord_key, 60)
return float(fair_shares.get(user_id, 0))
7. Monitoring & Metrics
class RateLimiterMetrics:
"""Expose metrics for monitoring"""
METRICS = {
'tenant_requests_total': 'Counter',
'tenant_allowed_total': 'Counter',
'tenant_denied_total': 'Counter',
'tenant_fairness_violations': 'Counter',
'isolation_violations': 'Counter',
'user_rps_usage': 'Gauge',
'fair_share_calculations': 'Histogram'
}
def record_check(
self,
tenant_id: str,
user_id: str,
result: RateLimitResult
):
"""Record rate limit check for monitoring"""
labels = {'tenant': tenant_id, 'user': user_id}
if result.allowed:
self.metrics.tenant_allowed_total.inc(labels)
else:
self.metrics.tenant_denied_total.inc(labels)
if result.isolation_violation:
self.metrics.isolation_violations.inc(labels)
self.metrics.user_rps_usage.set(
value=result.tenant_remaining,
labels=labels
)
Deployment Configuration
# rate-limiter-config.yaml
tenants:
- id: "tenant_a"
quotas:
global_rps: 1000
global_burst: 2000
daily: 1000000
tiers:
free: {rps: 10, burst: 20}
basic: {rps: 100, burst: 200}
premium: {rps: 500, burst: 1000}
isolation:
level: "soft" # or "strict"
shard: "shard-1"
- id: "tenant_b"
quotas:
global_rps: 5000
global_burst: 10000
daily: 5000000
tiers:
enterprise: {rps: 5000, burst: 10000}
isolation:
level: "strict"
shard: "shard-2"
fairness:
algorithm: "wfq" # wfq, htb, or simple
min_guarantee_percent: 10
staleness_threshold_seconds: 300
redis:
cluster_mode: true
replica_count: 2
shard_count: 4
monitoring:
prometheus_enabled: true
metrics_retention_days: 30
Key Features Implementation
1. Quotas
- Hierarchical: Tenant → Tier → User
- Multiple windows: RPS, burst, daily
- Hard vs soft limits: Hard limits are absolute, soft limits can be exceeded during low usage
2. Fairness
- WFQ algorithm: Active users get weighted fair share
- Dynamic adjustment: Fair share recalculates based on active users
- Minimum guarantees: Every user gets baseline quota
- Burst borrowing: Idle users' capacity can be borrowed (within limits)
3. Isolation
- Physical isolation (strict mode): Separate Redis shards, processes, connections
- Logical isolation (soft mode): Namespace separation in shared infrastructure
- Isolation violations: Tracked and penalized
- Cross-tenant attack prevention: Rigorous tenant_id validation
Scaling Considerations
- Redis Cluster: Shard by tenant_id for isolation
- Local caching: Front-end caches recent decisions (1-2 seconds)
- Circuit breakers: Per-tenant failure detection
- Backpressure: Signal upstream when tenant is over capacity
- Warm-up periods: New tenants get gradual quota ramp-up
Example Usage
# Initialize
redis_client = redis.RedisCluster(...)
rate_limiter = TenantAwareRateLimiter(
redis_client=redis_client,
tenant_quotas=load_quotas(),
fairness_algorithm='wfq',
isolation_level='LOGICAL'
)
# Check request
result = rate_limiter.check_limit(
tenant_id="acme_corp",
user_id="user_123",
cost=1,
endpoint="/api/v1/data"
)
if result.allowed:
process_request()
else:
return {
"error": "rate_limit_exceeded",
"retry_after": result.reset_after,
"tenant_remaining": result.tenant_remaining,
"fair_share": result.fair_share
}
Failure Modes & Handling
- Redis failure: Fallback to local token bucket with conservative limits
- Clock skew: Use Redis TIME for consistent time source
- Hot tenants: Auto-throttle and alert
- Fairness starvation: Minimum guarantee enforcement
- Isolation breach: Immediate quarantine and alerting
This design provides:
- Strong isolation between tenants
- Fair distribution within tenants
- Flexible quotas at multiple levels
- Scalable distributed architecture
- Observable with comprehensive metrics
- Resilient with fallback mechanisms
The system can handle thousands of tenants with millions of users while maintaining strict isolation and fairness guarantees.