We are going to design a multi-tenant throttling system that layers:
Organization quotas (static limits per tenant)
Feature gates (enable/disable features per tenant, might also have rate limits)
Abuse heuristics (dynamic adjustments based on suspicious activity)
We'll break down the system into components:
Tenant Context: Every request must be associated with a tenant (organization). We assume we have a way to extract tenant ID (e.g., from JWT, API key, etc.)
Quota Manager: Manages static quotas for each tenant. Quotas can be set per time window (e.g., 1000 requests per minute). We can use a token bucket or fixed window counter.
Feature Gate Manager: Determines if a tenant has access to a feature and may also assign a quota for that feature.
Abuse Detector: Monitors for abuse patterns (e.g., sudden spikes, repeated errors, etc.) and can impose stricter limits or block the tenant temporarily.
Throttling Decision Engine: Combines the above to decide whether to allow a request, and if so, with what limits (or if it should be blocked).
Storage: We need to store:
Tenant quotas (static)
Feature gate configurations (which features are enabled and their quotas)
Abuse state (current abuse level, corrections, etc.)
Metrics and Logging: To monitor and adjust the system.
Let's design the flow for a request:
Step 1: Identify tenant and the feature (or API endpoint) being accessed.
Step 2: Check feature gate:
If the feature is disabled for the tenant, reject immediately.
If the feature has a specific quota, use that quota for this feature. Otherwise, use the organization-wide quota.
Step 3: Check organization quota (if no feature-specific quota, or in addition to it? We need to define layering).
We have two approaches:
a) Feature-specific quotas are independent and do not count against organization quota? Then we have two separate buckets.
b) Feature-specific quotas are a subset of organization quota? Then we need to track both.
Let's assume we want to support both. So we can have:
Global organization quota (for all requests)
Feature-specific quotas that are in addition to the global? Or instead of?
However, note: the requirement says "layering". We can think of it as:
Layer 1: Feature gate (is the feature enabled?)
Layer 2: Feature-specific quota (if set, then check that)
Layer 3: Organization-wide quota (if no feature-specific set, or in addition?)
But note: if we have both feature-specific and organization-wide, we might double count. We want to avoid that.
Let's clarify:
Option A: Hierarchical - feature-specific quotas are part of the organization quota. So if an organization has 1000 total and a feature has 500, then that feature can use up to 500 but the total organization usage cannot exceed 1000.
Option B: Independent - feature-specific quotas are separate. Then the organization might have 1000 for all, and the feature has 500 in addition? That would allow 1500 for that feature? Not likely.
I think the common pattern is:
The organization has a total quota (e.g., 1000 requests per minute).
Some features might have their own quotas (which are part of the total). So if you use 500 on feature A, you have 500 left for other features.
But sometimes, a feature might have a minimum guarantee? Or separate? We need to design for flexibility.
Let's define:
Organization quota: a set of tokens that are shared across all features (unless a feature has its own separate bucket?).
We can have:
For a given tenant and feature:
1. If the feature has a dedicated quota, then we use that bucket and ignore the organization bucket for that request.
2. If the feature does not have a dedicated quota, then we use the organization bucket.
But note: what if a tenant uses multiple features? Some with dedicated, some without? Then the organization bucket is only used for those without dedicated.
Alternatively, we can have:
Always check organization bucket (if set) and then feature bucket (if set). Both must pass? That would be two separate limits.
Then for a request to Feature A:
- We check Feature A bucket (max 500/min) and also the organization bucket (max 1000/min). So if Feature A uses 600, but organization only used 200, then the request is rejected because of Feature A limit? But what if we want Feature A to be limited by its own and not by the organization? Then we don't check organization for Feature A.
So we can have:
For a request to feature F for tenant T:
1. If feature F is disabled -> reject.
2. If feature F has a quota, then check that quota. If exceeded, reject.
3. If feature F does not have a quota, then check the organization quota. If exceeded, reject.
But what if we want to enforce both? Then we need to check both.
Let's think of use cases:
Some features are premium and have their own quota (separate from the rest). So we don't want the premium feature to eat into the general quota.
Some features are part of the general quota.
So we can have:
Each feature configuration:
- enabled: boolean
- quota: optional (if set, then this feature uses its own bucket, else uses the organization bucket)
And the organization has a global bucket (which is used by all features that don't have their own).
But note: if a feature has its own bucket, then the organization bucket is not used for that feature. So the organization bucket is only for non-premium features.
This seems reasonable.
Step 4: Abuse heuristics:
We can have an abuse score for the tenant (or for the tenant+feature). The abuse score can be increased by:
- High error rates (4xx, 5xx) from the tenant's requests.
- Sudden spikes in traffic (compared to baseline).
- Patterns that look like scraping, brute force, etc.
The abuse score can lead to:
- Temporary blocks (if score too high)
- Reduced quotas (e.g., if abuse score is high, we might lower the effective quota for the tenant)
How to integrate?
We can have:
After passing the quota checks, we check the abuse state:
code
If the tenant is currently blocked due to abuse -> reject.
Otherwise, we might adjust the allowed rate for the tenant (for the current request) based on abuse. For example, if abuse score is 50%, then we only allow 50% of the quota? But note: the quota check already passed. So we are now in the realm of dynamic adjustment.
Alternatively, we can incorporate the abuse adjustment into the quota buckets? That is, we can have:
code
effective_quota = base_quota * (1 - abuse_score)
But note: abuse_score might be per feature? Then we adjust the feature bucket accordingly.
However, adjusting the bucket on the fly might be complex because we have to update the bucket's capacity? Or we can adjust the token refill rate? Or we can do:
When checking the bucket, we check:
code
current_tokens = bucket.tokens
allowed_tokens = base_capacity * (1 - abuse_score) [if abuse_score is 0.5, then allowed_tokens is half]
But note: the bucket might have already accumulated tokens. We don't want to take away tokens that are already there?
Alternatively, we can have:
The abuse detector sets a multiplier for the tenant (or for the feature) that is used when checking the quota:
code
if (current_tokens >= 1) and (random() < multiplier) then allow, else reject.
But that would be probabilistic and might not be acceptable.
Another idea: we can have a separate "abuse bucket" that limits the rate of requests when abuse is detected? But then we are adding another layer.
Let's think of simplicity:
We can have:
After passing the feature and organization quotas, we check:
code
if abuse_score > threshold:
reject (or require CAPTCHA, etc.)
But note: the abuse score might be dynamic and we might want to gradually reduce the allowed rate.
And then we use that effective rate limit for the bucket (for the feature or organization) by adjusting the bucket's capacity or refill rate.
However, note that the bucket might have already been filled. So we need to adjust the bucket's state.
Alternatively, we can have two buckets:
code
- Normal bucket (with base quota)
- Abuse bucket (with reduced quota)
And then we decide which bucket to use based on abuse score.
But then we have to manage two sets of buckets per tenant? That's complex.
Let's simplify:
We'll have one bucket per (tenant, feature) or (tenant, organization) as per the configuration.
The bucket's capacity (max tokens) and refill rate are fixed by the quota.
Then, when we check the bucket, we do:
code
tokens_needed = 1
if abuse_score > 0:
tokens_needed = 1 / (1 - abuse_score) [so if abuse_score=0.5, then we require 2 tokens for one request]
But note: the bucket might not have that many tokens. So we are effectively reducing the rate by a factor of (1-abuse_score).
However, this might lead to tokens being consumed faster when abuse is high, and then the bucket runs out quickly.
Alternatively, we can adjust the refill rate? But the refill rate is fixed.
Another idea: we can have the abuse detector set a multiplier on the bucket's consumption:
code
When we take a token, we take `ceil(1/(1-abuse_score))` tokens? That might be too aggressive.
Given the complexity, maybe we do:
code
We have a bucket with base quota.
We also have an abuse score that, when above a threshold, triggers a separate bucket with a much lower quota? Or we can set a flag that says "under abuse" and then use a different bucket (with a lower capacity) for that tenant.
But then we have to manage state: when the abuse score goes down, we switch back.
Let's break down:
We can have:
For each (tenant, feature) or (tenant, organization) we have:
code
- normal_bucket: with base quota
- abuse_bucket: with lower quota (maybe 10% of base) or even zero (block)
Then, we have an abuse state for the tenant (or tenant+feature) that can be:
code
- NORMAL: use normal_bucket
- ABUSE: use abuse_bucket
The abuse state is set by the abuse detector when the abuse score exceeds a threshold, and cleared when it goes below another threshold (hysteresis).
This way, we don't change the bucket parameters on the fly, we just switch which bucket to use.
But note: the abuse_bucket might be shared across all features? Or per feature? We can have:
code
abuse_bucket per (tenant, feature) and per (tenant, organization) as well.
However, that doubles the number of buckets? We can share the abuse bucket for the organization across all features? But then if one feature is being abused, we might want to limit only that feature? So per feature abuse bucket makes sense.
But then we have:
code
For each tenant and for each feature that has a dedicated quota, we have two buckets (normal and abuse) and for the organization we have two buckets (normal and abuse) for the non-dedicated features.
This is getting complex.
Let's try to simplify:
We can have:
code
For each tenant:
- organization_normal_bucket
- organization_abuse_bucket
For each feature that has a dedicated quota for the tenant:
- feature_normal_bucket
- feature_abuse_bucket
Then, for a request:
code
if feature is enabled:
if feature has dedicated quota:
bucket = (abuse_state for tenant+feature is ABUSE) ? feature_abuse_bucket : feature_normal_bucket
if bucket.take(1): allow, else reject
else:
bucket = (abuse_state for tenant is ABUSE) ? organization_abuse_bucket : organization_normal_bucket
if bucket.take(1): allow, else reject
How do we set the abuse state?
code
We have an abuse detector that monitors the tenant (or tenant+feature) and sets the abuse state.
The abuse state can be stored per tenant and per feature (if feature is being abused independently).
But note: the abuse detector might detect abuse on a specific feature, so we set the abuse state for that tenant+feature. Or it might be general, so we set for the tenant.
We can have:
code
abuse_state: map<tenant_id, AbuseState> // for organization-wide
abuse_state_feature: map<tenant_id, map<feature_name, AbuseState>>
Then, when checking:
code
if feature has dedicated quota:
if tenant has abuse_state_feature for this feature and it's ABUSE, then use abuse bucket for feature.
else use normal bucket for feature.
else:
if tenant has abuse_state and it's ABUSE, then use abuse bucket for organization.
else use normal bucket for organization.
The abuse buckets would have a fixed (lower) quota, e.g., 10% of the normal bucket? Or we can set it to a fixed low number (like 10 per minute) regardless of the normal bucket.
We can configure the abuse bucket per feature and per organization? That might be too much.
Alternatively, we can have:
code
The abuse bucket for a tenant (or tenant+feature) is set to a fixed low value (like 10 requests per minute) when abuse is detected, and when abuse clears, we go back to the normal bucket.
But note: the normal bucket might have accumulated tokens while under abuse? Then when we switch back, we have a full bucket? That might be okay.
However, we might want to reset the buckets when switching to abuse? Or not? We can leave the normal bucket as is (so it keeps accumulating) and the abuse bucket is independent.
But then when we switch back, we have a full normal bucket? That might be acceptable.
Alternatively, we can have the abuse bucket be a separate bucket with a fixed low capacity and refill rate, and the normal bucket continues to fill (but not used) during abuse.
This seems workable.
Summary of buckets:
For tenant T:
organization_normal_bucket: tokens, capacity, refill_rate (from organization quota)
organization_abuse_bucket: fixed, say capacity=10, refill_rate=10 per minute? (or we can set it to a percentage of the normal? but then we have to store the normal bucket's quota to compute that? We can set the abuse bucket at the time of abuse detection? But we want it fixed? Let's set it to a fixed low value for all, unless configured otherwise.)
For feature F (if dedicated quota for tenant T):
feature_normal_bucket: tokens, capacity, refill_rate (from feature quota)
feature_abuse_bucket: fixed, say capacity=10, refill_rate=10 per minute.
But note: the abuse bucket for a feature might be set only when that feature is being abused? We can have:
code
When abuse is detected for (tenant, feature), we set the abuse state for that (tenant, feature) and start using the feature_abuse_bucket (which we might have to create if not exists?).
We can pre-create the abuse buckets? Or create on the fly.
Let's pre-create:
code
For each tenant, we create:
organization_normal_bucket, organization_abuse_bucket.
For each feature that the tenant has a dedicated quota, we create:
feature_normal_bucket, feature_abuse_bucket.
The abuse bucket's capacity and refill rate can be set by configuration (global) or per feature? We can have:
Then, when creating the abuse bucket for a feature, we look up the config.
Alternatively, we can have the abuse bucket be a fixed low value for all, and if we need per-feature, we can extend.
Given the complexity, let's start with:
code
- The abuse bucket for any tenant or tenant+feature is fixed to 10 requests per minute (capacity=10, refill_rate=10 per minute).
We can adjust this later.
Step 5: Putting it all together:
Request processing:
function handle_request(tenant_id, feature, ...):
1. Check feature gate: if feature is disabled for tenant -> reject (403).
code
2. Determine which bucket to use:
if feature has dedicated quota for tenant:
if abuse_state[tenant_id][feature] == ABUSE:
bucket = get_abuse_bucket(tenant_id, feature) # might create if not exists
else:
bucket = get_normal_bucket(tenant_id, feature)
else:
if abuse_state[tenant_id] == ABUSE:
bucket = get_abuse_bucket(tenant_id, None) # for organization
else:
bucket = get_normal_bucket(tenant_id, None)
3. Try to take a token from the bucket (with possible wait? but we are throttling, so we don't wait, we just reject if not available).
4. If token taken -> allow, else reject (429).
Step 6: Abuse detection:
code
We need a separate process that:
- Collects metrics per tenant and per feature (request count, error rate, etc.)
- Computes an abuse score (or just a binary state) for each tenant and for each feature.
How often? Maybe every minute?
We can have:
abuse_state[tenant_id] = NORMAL or ABUSE
abuse_state[tenant_id][feature] = NORMAL or ABUSE
The abuse detector runs periodically (e.g., every minute) and updates the abuse states.
The abuse state can have hysteresis:
if current_score > high_threshold -> set to ABUSE
if current_score < low_threshold -> set to NORMAL
The score can be computed from:
- Request rate (compared to baseline)
- Error rate (4xx, 5xx)
- Possibly other signals (like same user making many requests, etc.)
We can also have a decay: if the tenant stops abusive behavior, the score goes down.
Step 7: Storage:
code
We need to store:
- Tenant feature configurations (enabled, quota for feature, etc.)
- Organization quota (for non-dedicated features)
- Abuse states (and maybe abuse scores for the detector)
Also, the bucket states (tokens, last refill) must be stored and updated atomically.
We can use a distributed storage like Redis for the buckets (token bucket algorithm) and for the abuse states.
For the feature gate and quota configuration, we can use a database (like PostgreSQL) and cache in memory (or in Redis) for fast access.
Step 8: Scalability:
code
We might have many tenants and features. The buckets are per (tenant, feature) or (tenant, organization). We can shard by tenant_id.
Step 9: Monitoring and Alerts:
code
We need to monitor:
- Rejection rates (due to quota, abuse, feature disabled)
- Abuse state changes
- Bucket utilizations
Step 10: Implementation details:
code
We'll need:
- A way to extract tenant_id and feature from the request.
- A configuration service that provides:
* Whether a feature is enabled for a tenant.
* The quota for a feature (if dedicated) and for the organization.
- A token bucket implementation that is distributed (we can use Redis with atomic operations).
- An abuse detector service that runs periodically and updates abuse states in Redis.
- A throttling middleware that uses the above.
def handle_request(self, request):
tenant_id = extract_tenant(request)
feature = extract_feature(request)
# 1. Check feature gate
if not self.config_service.is_feature_enabled(tenant_id, feature):
return reject(403, "Feature disabled")
# 2. Get the bucket
bucket = self._get_bucket(tenant_id, feature)
# 3. Try to consume a token
if bucket.try_consume():
return proceed()
else:
return reject(429, "Rate limit exceeded")
def _get_bucket(self, tenant_id, feature):
# Determine if feature has dedicated quota
feature_quota = self.config_service.get_feature_quota(tenant_id, feature)
org_quota = self.config_service.get_org_quota(tenant_id)
# Check abuse state
abuse_state = self._get_abuse_state(tenant_id, feature)
if feature_quota is not None:
# This feature has dedicated quota
if abuse_state == ABUSE:
return self._get_abuse_bucket_for_feature(tenant_id, feature)
else:
return self._get_normal_bucket_for_feature(tenant_id, feature, feature_quota)
else:
# Use organization quota
if abuse_state == ABUSE:
return self._get_abuse_bucket_for_org(tenant_id)
else:
return self._get_normal_bucket_for_org(tenant_id, org_quota)
def _get_normal_bucket_for_feature(self, tenant_id, feature, quota):
# We need to get or create a token bucket for (tenant_id, feature) with the given quota.
# The bucket state is stored in Redis. We can use a key like: f"bucket:feature:{tenant_id}:{feature}"
# The quota is the capacity and refill rate (if we are using token bucket with refill rate).
# We assume quota has: capacity, refill_rate (per minute).
# We'll use a distributed token bucket that refills at a constant rate.
pass
def _get_abuse_bucket_for_feature(self, tenant_id, feature):
# Fixed abuse bucket for this feature (if not exists, create with fixed low capacity and refill rate)
pass
Similarly for organization.
The token bucket implementation:
code
We can use a Redis script that does:
current_time = now()
last_refill = redis.get(last_refill_key) or current_time
tokens = redis.get(tokens_key) or capacity
# Refill tokens based on time passed
elapsed = current_time - last_refill
new_tokens = min(capacity, tokens + elapsed * refill_rate_per_second)
if new_tokens >= 1:
# consume one token
redis.set(tokens_key, new_tokens - 1)
redis.set(last_refill_key, current_time)
return True
else:
redis.set(tokens_key, new_tokens)
redis.set(last_refill_key, current_time)
return False
But note: we are doing multiple gets and sets. We need to do it atomically. We can use a Lua script.
Alternatively, we can use a fixed window counter? But token bucket is smoother.
We'll use a token bucket with refill.
The abuse state:
code
We store in Redis:
key: abuse_state:{tenant_id} -> value: "NORMAL" or "ABUSE"
key: abuse_state:{tenant_id}:{feature} -> value: "NORMAL" or "ABUSE"
The abuse detector:
code
It runs periodically (say every minute) and for each tenant (and for each feature that has dedicated quota) it:
- Collects metrics for the last minute (requests, errors, etc.)
- Computes a score (0 to 1)
- If score > high_threshold (e.g., 0.8) and current state is NORMAL -> set to ABUSE.
- If score < low_threshold (e.g., 0.2) and current state is ABUSE -> set to NORMAL.
The metrics can be stored in a time series database or we can aggregate in Redis.
We can have:
For each tenant and feature (or tenant for organization), we have:
request_count_last_minute
error_count_last_minute
Then:
error_rate = error_count / request_count (if request_count > 0, else 0)
Also, we can compare request_count to a baseline (average of last 10 minutes?).
score = (error_rate * 0.5) + (spike_factor * 0.5)
Where spike_factor = (current_request_count - baseline) / baseline (capped at 1)
This is a simple example.
Step 11: Configuration:
code
We need a way to configure:
- Organization quotas (for each tenant, or a default)
- Feature gates and feature-specific quotas (for each tenant, or a default)
We can have a table:
tenant_quotas:
tenant_id, quota_type (org or feature), feature_name (null for org), capacity, refill_rate_per_minute
tenant_features:
tenant_id, feature_name, enabled
Then, when we look up:
For feature F for tenant T:
Check tenant_features: if exists and enabled=false -> reject.
Check tenant_quotas:
First, look for (tenant_id, 'feature', feature_name) -> if found, use that as feature_quota.
Then, look for (tenant_id, 'org', null) -> use as org_quota.
If no feature_quota and no org_quota? Then we can have a global default?
Step 12: Extension points:
code
- We might want to have different abuse buckets for different abuse levels? (e.g., if abuse score is 0.5, then use a bucket with 50% of the normal? But we are switching buckets, so we can have multiple abuse buckets? That's too complex.)
- We might want to have a graduated response: first warning, then reduce quota, then block.
We can do:
Abuse state can be:
NORMAL, WARNING, RESTRICTED, BLOCKED
And then we have different buckets for each? Or we can have:
NORMAL: normal bucket
WARNING: normal bucket but with a lower capacity? Or use abuse bucket with 50%?
RESTRICTED: abuse bucket with 10%
BLOCKED: bucket with 0 capacity.
But then we need 4 buckets per (tenant, feature) and per organization? That's a lot.
Alternatively, we can adjust the abuse bucket's capacity dynamically? But then we have to change the bucket's capacity on the fly? That's also complex.
Given the complexity, let's stick to two states: NORMAL and ABUSE (with a fixed low abuse bucket). We can extend later.
Step 13: Performance:
code
Step 14: Implementation plan:
code
Step 15: Abuse detector:
code
Step 16: Revised architecture:
code
We have:
1. Throttling middleware:
- Checks feature gate, quota, abuse state, and bucket.
- Emits events (allowed, throttled) to a message queue (e.g., Kafka).
2. Backend service:
- Processes allowed requests.
- Emits events (backend response) to the same message queue.
3. Metrics service:
- Consumes events and aggregates per (tenant, feature) and (tenant, org) in memory (or in Redis) for the last N minutes.
4. Abuse detector:
- Periodically (every minute) queries the metrics service for the last minute's aggregates for each tenant and feature.
- Computes abuse scores and updates abuse states in Redis.
5. Throttling middleware reads abuse states from Redis (with 2-second cache).
This way, the throttling middleware is fast (only reads from Redis and config cache) and the heavy metric aggregation is done elsewhere.
Step 17: Implementation steps:
code
Step 18: Future improvements:
code
- We might want to have different thresholds per tenant (based on their plan). We can have:
abuse_thresholds: {
tenant_id: {high: 0.9, low: 0.1},
default: {high: 0.8, low: 0.2}
}
- We might want to have different abuse buckets per tier.
- We might want to have a way to manually override the abuse state for a tenant.
This is a high-level design. We'll need to adjust as we implement.
- A way to run the metrics service and abuse detector as separate processes.
Given the complexity, we'll start with a simple implementation and then scale.
Let's write the token bucket Lua script as a string:
code
token_bucket_script = """
local tokens_key = KEYS[1]
local last_refill_key = KEYS[2]
local capacity = tonumber(ARGV[1])
local refill_rate_per_sec = tonumber(ARGV[2]) / 60
local now = tonumber(redis.call('TIME')[1])
local last_refill = tonumber(redis.call('GET', last_refill_key)) or now
local tokens = tonumber(redis.call('GET', tokens_key)) or capacity
local elapsed = now - last_refill
local refill_amount = elapsed * refill_rate_per_sec
local new_tokens = math.min(capacity, tokens + refill_amount)
if new_tokens >= 1 then
redis.call('SET', tokens_key, new_tokens - 1)
redis.call('SET', last_refill_key, now)
return 1
else
redis.call('SET', tokens_key, new_tokens)
redis.call('SET', last_refill_key, now)
return 0
end
"""
We'll load this script once and use its SHA.
Then, the token bucket class:
code
class TokenBucket:
def __init__(self, redis, key_prefix, capacity, refill_rate_per_minute):
self.redis = redis
self.key_tokens = f"{key_prefix}:tokens"
self.key_last_refill = f"{key_prefix}:last_refill"
self.capacity = capacity
self.refill_rate_per_minute = refill_rate_per_minute
self.script_sha = None # we'll load the script
def try_consume(self):
# Load the script if not loaded
if self.script_sha is None:
self.script_sha = self.redis.script_load(token_bucket_script)
# Run the script
result = self.redis.evalsha(
self.script_sha,
2, # number of keys
self.key_tokens,
self.key_last_refill,
self.capacity,
self.refill_rate_per_minute
# note: we don't pass now, because the script uses Redis TIME
)
return result == 1
But note: the script uses Redis TIME, so we don't need to pass now.
However, we are using the same script for all buckets. That's fine.
Now, the throttling middleware:
code
Note: The abuse bucket for org and feature are fixed. We can make them configurable later.
Step 19: Abuse detector:
code
We need to get the metrics from the metrics service.
The abuse detector runs every minute (say at 5 seconds after the minute).
For each active (tenant, feature) and (tenant, org):
current_metrics = metrics_service.get_metrics(tenant_id, feature, org_flag, last_n_minutes=1) # for the last minute
baseline_metrics = metrics_service.get_metrics(tenant_id, feature, org_flag, last_n_minutes=10) # for the last 10 minutes (including the current? we want the previous 10? We want the baseline without the current minute? So we can get last 10 minutes excluding the current? Then we have 9 minutes? We can do:
current_metrics for minute M-1 (the minute that just ended)
baseline_metrics for minutes M-10 to M-2 (9 minutes)
Then:
total_current = current_metrics.allowed + current_metrics.throttled
total_baseline = average of (baseline_metrics[i].allowed + baseline_metrics[i].throttled) for i in the 9 minutes
spike_factor = (total_current - total_baseline) / total_baseline if total_baseline>0 else 0
error_rate = current_metrics.backend_errors / current_metrics.allowed if current_metrics.allowed>0 else 0
score = spike_factor * 0.5 + error_rate * 0.5
Then:
current_abuse_state = get_abuse_state(tenant_id, feature) # from Redis
if score > 0.8 and current_abuse_state == 'NORMAL':
set_abuse_state(tenant_id, feature, 'ABUSE')
elif score < 0.2 and current_abuse_state == 'ABUSE':
set_abuse_state(tenant_id, feature, 'NORMAL')
We do the same for the organization (org_flag=True).
Step 20: Metrics service:
code
We need to store per (tenant, feature) and (tenant, org) for each minute.
We can have:
In Redis:
key: metrics:tenant:{tenant_id}:feature:{feature}:minute:{minute_ts} -> hash with fields: allowed, throttled, backend_errors
key: metrics:tenant:{tenant_id}:org:minute:{minute_ts} -> same.
We also need to know which (tenant, feature) are active? We can have a set:
key: active_tenants_features
members: "tenant_id:feature" and "tenant_id:org"
Then, when we get an event, we:
- Extract tenant_id, feature, event_type.
- Determine the minute_ts (floor to minute) from the event timestamp.
- Build the key.
- Increment the appropriate field in the hash (using HINCRBY).
- Add the (tenant_id, feature) to the active set (if not already there).
Then, when the abuse detector runs, it:
- Gets the current minute (say, 2024-01-01-12:34) and then the minute_ts for the last minute (12:33) and the previous 10 minutes.
- For each (tenant, feature) in the active set (and for the org) we:
Get the hash for the last minute (12:33) and for the previous 9 minutes (12:24 to 12:32) and compute the baseline.
- Then compute the score and update abuse state.
- Then we can remove the old minute keys (older than 10 minutes) from the active set? Or we can keep the active set for all time? We can remove the keys from the active set if they haven't been updated in 10 minutes? But we are only reading the last 10 minutes, so if a (tenant, feature) hasn't had activity in 10 minutes, we can skip.
So we can:
active_tenants_features: set of "tenant_id:feature" and "tenant_id:org"
When we process an event, we add to the set.
Then, when the abuse detector runs, we iterate over the set, but for each we check if there is data for the last 10 minutes? If not, we skip? Or we remove from the set if there's no data for the last 10 minutes? We can do:
For each member in the set:
Check if there is any data for the last 10 minutes (by trying to get one of the keys). If not, remove from the set.
This way, the active set only contains (tenant, feature) that had activity in the last 10 minutes.
This is a comprehensive design.
Given the complexity, we might start with a simpler version:
code
- Without feature-specific quotas? Only organization quota.
- Without abuse buckets, just block when abuse score is high? But we want to layer.
But the requirement says multi-tenant throttling with layering.
We'll go with the full design and implement step by step.
Let's write the code for the key components.
We assume:
code
- We have a Redis client.
- We have a config service (that we can implement with a simple in-memory cache and a database).
- We have a message queue (like Kafka) for events.
We'll write:
code
token_bucket.lua (the script)
token_bucket.py (the class)
throttling_middleware.py
metrics_service.py
abuse_detector.py
This is a large system. We might need to adjust.
Given the time, we'll outline the code structure and leave the implementation details for later.
We'll also need to handle:
code
- Sharding: if we have many tenants, we might want to shard the Redis keys? But Redis can handle many keys.
- Performance: we are doing 1-2 Redis calls per request? That might be acceptable if Redis is fast.
- Memory: the abuse cache in the middleware is per instance. We can have multiple instances of the middleware, so the cache is local.
This design should work.
Let me know if you have any questions or need more details on a specific part.
I'll design a comprehensive multi-tenant throttling system with layered guardrails. This is a sophisticated architecture that balances protection, flexibility, and tenant experience.
Phase 1: Deploy with all guardrails disabled but monitoring active
Phase 2: Enable feature gates only (no quota enforcement)
Phase 3: Enable organization quotas with 10x headroom
Phase 4: Enable abuse heuristics in observe-only mode
Phase 5: Gradual ramp-down of headroom while monitoring impact
Phase 6: Full enforcement with real-time adjustments
12. Testing Strategy
Unit tests for each heuristic and bucket algorithm
Integration tests with simulated tenant traffic patterns
Audit trail - complete history of all quota changes and abuse actions
Graceful degradation - system continues working during partial failures
Fairness - prevents noisy neighbors while protecting legitimate traffic
The key innovation is the layered approach where static quotas provide baseline protection, feature gates enable/disable functionality, and abuse heuristics add dynamic, behavior-based adjustments - all while maintaining tenant isolation and providing clear feedback.
We are doing multiple Redis calls per request? We can batch:
- Get feature enabled and quota in one go? (from the config service, which might be cached in memory)
- Get abuse state (one or two Redis calls: one for tenant, one for feature)
- Get bucket (one Redis call via Lua script that does the token consumption and refill)
So total: 1 Lua script for bucket, and 1-2 Redis gets for abuse state and config? We can cache the config and abuse state in memory (with TTL) to reduce Redis calls.
But note: we must be careful with caching because:
- Feature gate changes should be reflected quickly? We can have a short TTL (e.g., 30 seconds) for config cache.
- Abuse state changes should be reflected quickly? We can have a very short TTL (e.g., 5 seconds) for abuse state cache.
Alternatively, we can have the abuse detector update Redis and the middleware read from Redis every time? That would be 1-2 extra Redis calls per request.
We can do:
The middleware does:
abuse_state = redis.get(abuse_key) # with a TTL? The abuse detector sets the key and we don't set TTL? Then we have to rely on the abuse detector to clear? But if the abuse detector fails to clear, we might be stuck in ABUSE.
We can have the abuse state keys set with an expiration? Then if the abuse detector doesn't update, it will expire and go back to NORMAL? But we don't want that because we want to keep the abuse state until the abuse detector clears it.
So we can have:
The abuse detector sets the abuse state key with no expiration (or a long one) and when it clears, it deletes the key.
Then, in the middleware, we check:
if redis.get(abuse_key) == "ABUSE": then use abuse bucket.
But then we have to do a Redis call for every request? That might be expensive.
We can cache the abuse state in the middleware (in memory) and refresh it every, say, 5 seconds? Then we have:
abuse_state_cache = {}
last_updated = 0
def get_abuse_state(tenant_id, feature):
now = time.time()
if now - last_updated > 5:
# refresh from Redis
# We can get all abuse states for this tenant? Or just the ones we need?
# We can preload all abuse states for the tenant? But we don't know which features are used?
# Alternatively, we can have a separate cache per (tenant, feature) with TTL? But then we might have many.
Given the complexity, let's do:
For each request, we do:
abuse_state = self.redis.get(abuse_key) # where abuse_key is built from tenant_id and feature (or just tenant_id for org)
We can have the abuse_key for feature: f"abuse:{tenant_id}:{feature}"
For org: f"abuse:{tenant_id}:org"
We do one Redis call for the feature abuse state, and if the feature doesn't have dedicated quota, we do another for org? But we can do:
if feature has dedicated quota:
abuse_key = f"abuse:{tenant_id}:{feature}"
else:
abuse_key = f"abuse:{tenant_id}:org"
So only one Redis call for abuse state.
Then we do one Lua script for the bucket.
And we have the config (which we can cache in memory with a TTL of 30 seconds).
So per request:
- Check config cache (in memory) for feature gate and feature quota/org quota.
- One Redis call for abuse state.
- One Lua script for bucket.
That's 1 Redis call and 1 Lua script (which is also a Redis call). So 2 Redis calls per request.
If we can cache the abuse state in memory with a TTL of 5 seconds, then we can reduce to 1 Redis call (the Lua script) for requests that hit the cache.
But note: the abuse state might change more frequently? We can set the abuse state cache TTL to 2 seconds.
Let's do:
abuse_state_cache = {} # key: (tenant_id, feature) -> (state, expiry)
def get_abuse_state(tenant_id, feature):
key = (tenant_id, feature)
now = time.time()
if key in abuse_state_cache:
state, expiry = abuse_state_cache[key]
if now < expiry:
return state
# else, fetch from Redis
redis_key = f"abuse:{tenant_id}:{feature}"
state = self.redis.get(redis_key)
if state is None:
state = "NORMAL"
# cache for 2 seconds
abuse_state_cache[key] = (state, now+2)
return state
But note: if the abuse detector sets the state to ABUSE, we want it to take effect quickly. 2 seconds is acceptable.
However, if the abuse detector clears the state, we want that to take effect quickly too.
So 2 seconds TTL is acceptable.
We'll have:
- A configuration service (with caching) that provides:
* is_feature_enabled(tenant_id, feature) -> bool
* get_feature_quota(tenant_id, feature) -> Quota (capacity, refill_rate_per_minute) or None
* get_org_quota(tenant_id) -> Quota
- A Redis client.
- A token bucket implementation using a Lua script.
- An abuse state cache (in memory) with TTL 2 seconds.
- The middleware:
def middleware(request):
tenant_id = extract_tenant(request)
feature = extract_feature(request)
# 1. Check feature enabled
if not config_service.is_feature_enabled(tenant_id, feature):
return reject(403)
# 2. Get feature_quota and org_quota
feature_quota = config_service.get_feature_quota(tenant_id, feature)
org_quota = config_service.get_org_quota(tenant_id)
# 3. Determine which bucket to use
if feature_quota is not None:
# dedicated feature quota
abuse_state = get_abuse_state(tenant_id, feature)
if abuse_state == "ABUSE":
bucket = get_abuse_bucket_for_feature(tenant_id, feature)
else:
bucket = get_normal_bucket_for_feature(tenant_id, feature, feature_quota)
else:
# use org quota
abuse_state = get_abuse_state(tenant_id, "org") # or use the same function with a special key?
if abuse_state == "ABUSE":
bucket = get_abuse_bucket_for_org(tenant_id)
else:
bucket = get_normal_bucket_for_org(tenant_id, org_quota)
# 4. Try to consume
if bucket.try_consume():
return proceed()
else:
return reject(429)
The bucket.get_abuse_bucket_for_feature and get_normal_bucket_for_feature will return a TokenBucket instance that is configured with the appropriate capacity and refill rate, and uses a Redis key that is specific to that bucket.
The TokenBucket instance will have:
key: string (Redis key for tokens)
last_refill_key: string (Redis key for last refill timestamp)
capacity: int
refill_rate: int (per minute? but in the script we use per second)
The try_consume() method runs the Lua script.
The Lua script:
local tokens_key = KEYS[1]
local last_refill_key = KEYS[2]
local capacity = tonumber(ARGV[1])
local refill_rate_per_sec = tonumber(ARGV[2]) / 60 -- convert from per minute to per second
local now = tonumber(ARGV[3]) -- current time in seconds (from the client, but we can use Redis time? better to use Redis time to avoid clock skew)
-- We can use Redis time:
-- local now = redis.call('TIME')[1]
But note: the TIME command returns an array with two values: seconds and microseconds. We want seconds.
Let's do:
local time = redis.call('TIME')
local now = tonumber(time[1])
Then:
local last_refill = tonumber(redis.call('GET', last_refill_key)) or now
local tokens = tonumber(redis.call('GET', tokens_key)) or capacity
local elapsed = now - last_refill
local refill_amount = elapsed * refill_rate_per_sec
local new_tokens = math.min(capacity, tokens + refill_amount)
if new_tokens >= 1 then
redis.call('SET', tokens_key, new_tokens - 1)
redis.call('SET', last_refill_key, now)
return 1
else
redis.call('SET', tokens_key, new_tokens)
redis.call('SET', last_refill_key, now)
return 0
end
But note: we are doing multiple calls. We can use a transaction? But we are already in a Lua script, so it's atomic.
However, we are doing two SETs and two GETs. We can use:
local current = redis.call('GET', tokens_key)
... etc.
But we are already in a Lua script, so it's atomic.
We can also use:
We can store the tokens and last_refill in a hash? Then we can update both in one call? But we are updating two keys.
Alternatively, we can store the bucket state in one key as a hash? Then we can use HGET and HSET? But then we have to update two fields in one hash? We can do:
key: bucket:{tenant}:{feature}:{type} (type: 'normal' or 'abuse')
fields: tokens, last_refill
Then in Lua:
local data = redis.call('HGETALL', key)
-- parse
-- update
-- HMSET
But that might be more efficient? Not necessarily.
We'll stick to two keys for simplicity.
We'll have a separate process that runs every minute.
For each tenant and for each feature that has dedicated quota, and for the organization (for non-dedicated features) we:
- Get the request count in the last minute (from a time series, or we can have a Redis counter that we reset every minute? We can have:
key: requests:tenant:{tenant_id}:feature:{feature}:minute:{current_minute}
and similarly for errors.
We can use a Redis sorted set with timestamps? Or we can have a counter that we increment and then reset? But we need to count by minute.
Alternatively, we can have a fixed window counter per minute? We can do:
We have a key for each minute (using the minute timestamp) and we increment it for each request.
Then, for the last minute, we sum over the last 60 seconds? That would be 60 keys? Too many.
Instead, we can use:
We maintain:
- A rolling window of requests (using a sorted set with timestamps). We add each request with a timestamp, and then remove old ones (older than 1 minute). Then the count is the size of the set.
But that can be heavy.
Alternatively, we can use:
We have a token bucket that we use for throttling, and we can also use the bucket's current tokens to estimate the rate? Not really.
Given the complexity, let's assume we have a separate metrics collector that aggregates:
- total_requests (for the last minute) for each (tenant, feature) and for (tenant, org)
We can have:
We use a Redis counter that we increment for each request, and we also set a key that expires in 60 seconds? Then every minute we read the current value and reset? But then we lose the per-minute granularity? We can have:
key: requests:tenant:{tenant_id}:feature:{feature}:current
We increment this key for every request, and we set an expiration of 60 seconds? Then after 60 seconds it will be deleted. But then we need to read it and reset it at the same time? We can do:
current = redis.incr(key)
if current == 1:
# set expiration to 60 seconds
redis.expire(key, 60)
Then, when the abuse detector runs, it reads the key and then deletes it? But then we might miss requests that happen while we are reading? We can use a Lua script to read and delete atomically? Or we can have two keys: one for current minute and one for previous?
This is getting complex.
Alternatively, we can use a time series database like Prometheus and query the last minute? But that might be heavy for many tenants.
Given the constraints, let's assume we have a separate service that aggregates metrics (like collected by the throttling middleware) and exposes an API for the abuse detector.
The middleware, when it allows a request, also sends a metric:
tenant_id, feature, allowed
and when it rejects:
tenant_id, feature, rejected (and reason: quota, abuse, feature disabled)
We can have a background worker that processes these metrics and updates the abuse scores.
Then the abuse detector can query this metrics service (which has in-memory aggregates) for the last minute.
This way, we don't burden the Redis with metrics.
So:
The middleware sends events to a message queue (or a metrics service) with:
{tenant_id, feature, allowed: true/false, reason: ...}
The metrics service aggregates:
per (tenant, feature) and per (tenant, org) the request count and error count (if rejected with 4xx/5xx? but note: the middleware might reject with 429, which is not an error from the backend).
We want to detect abuse from the traffic pattern, so we care about the requests that we allowed? And also the ones that we rejected? If we reject a lot, that might be because the tenant is trying to abuse? So we should count the rejected ones as well? But note: the throttling is doing its job, so a high rejection rate might indicate abuse? But also might indicate that the tenant's quota is too low.
We want to detect:
-Sudden spike in traffic (allowed requests) -> might be abuse.
-High error rate from the backend (when the request is allowed and then the backend returns 5xx) -> might be abuse? Or just backend issues.
So we need two sets of metrics:
1. Throttling metrics: allowed and rejected by throttling.
2. Backend metrics: errors from the backend (for allowed requests).
The abuse detector should consider:
For a tenant (or tenant+feature):
total_requests = allowed_requests + rejected_by_throttling?
But note: the rejected_by_throttling are not reaching the backend, so we don't have backend errors for them.
We can have:
allowed_requests: these are the ones that passed throttling and went to the backend.
backend_errors: from the backend (for allowed requests).
Then:
request_rate = allowed_requests (per minute)
error_rate = backend_errors / allowed_requests (if allowed_requests>0)
spike: compare request_rate to baseline (average of last 10 minutes of allowed_requests)
The abuse detector uses these metrics.
So we need to:
- The middleware sends two events:
1. When a request is allowed:
event: {type: 'allowed', tenant_id, feature, timestamp}
2. When a request is rejected by throttling:
event: {type: 'throttled', tenant_id, feature, reason, timestamp}
- The backend (when it processes an allowed request) sends:
event: {type: 'backend', tenant_id, feature, status_code, timestamp}
Then the metrics service aggregates:
For each (tenant, feature) and for (tenant, org):
allowed_count_last_minute
throttled_count_last_minute
backend_error_count_last_minute (for 5xx? or 4xx? We might consider 4xx as client errors, which might be abuse? e.g., 404 might be scraping? But we can define)
Then the abuse detector queries the metrics service for the last minute.
This is a more robust design.
a) Set up Redis for:
- Buckets (token bucket state)
- Abuse states (keys: abuse:tenant:{tenant_id} and abuse:tenant:{tenant_id}:feature:{feature})
b) Implement the token bucket Lua script.
c) Implement the config service (with caching) that reads from a database (or config files) and provides:
- is_feature_enabled(tenant_id, feature)
- get_feature_quota(tenant_id, feature) -> returns capacity and refill_rate_per_minute (or None)
- get_org_quota(tenant_id) -> returns capacity and refill_rate_per_minute
d) Implement the throttling middleware:
- Extract tenant_id and feature.
- Check feature enabled.
- Get feature_quota and org_quota from config service.
- Get abuse state from Redis (with 2-second in-memory cache).
- Determine which bucket to use (normal or abuse) and which bucket key (feature or org).
- Run the token bucket Lua script to try to consume.
- If allowed, emit 'allowed' event to message queue. Else, emit 'throttled' event (with reason) and reject.
e) Implement the metrics service:
- Subscribe to the message queue.
- Maintain in-memory aggregates (or in Redis) for each (tenant, feature) and (tenant, org) for:
allowed_count, throttled_count, backend_error_count
for the current minute and previous minutes? We only need last minute for the abuse detector? But we also need baseline (last 10 minutes). So we need to keep at least 10 minutes.
- We can store:
For each (tenant, feature) and (tenant, org):
window: an array of 10 buckets (each for a minute) for allowed_count, throttled_count, backend_error_count.
Then, for the current minute, we update the current bucket.
Every minute, we shift the window (remove the oldest, add the current as the newest?).
But note: we are getting events in real-time. We can have:
We bucket by minute (using the event timestamp). We can have:
key: metrics:tenant:{tenant_id}:feature:{feature}:minute:{minute_ts}
and store the counts for that minute.
Then, when the abuse detector runs, it sums over the last 10 minutes for baseline, and takes the last minute for current.
- Alternatively, we can use a sliding window? But we are aggregating per minute, so we can just store 10 minutes of history.
- The metrics service can expose an API:
get_metrics(tenant_id, feature, org_flag, last_n_minutes=10)
that returns:
{
"current_minute": {allowed: X, throttled: Y, backend_errors: Z},
"baseline": {allowed: avg, ...}
}
f) Implement the abuse detector:
- Every minute, for each tenant and for each feature that has dedicated quota, and for the organization:
Call the metrics service to get:
current = metrics for the last minute (which is the minute that just ended? We need to align the minutes. We can run the abuse detector at the end of the minute? Or we can use the current partial minute? Better to use complete minutes.
So we run the abuse detector at, say, 5 seconds after the minute? Then we have the complete minute.
Then compute:
total_requests = current.allowed + current.throttled (or maybe only allowed? because throttled are rejected by us and might not be abuse? but a sudden spike in throttled might indicate abuse too? But if we are throttling, then we are already protecting. So we might not care about throttled for abuse? But if a tenant is sending a lot of requests that are being throttled, that might be abuse? They are trying to overwhelm us? So we should consider throttled as well? But note: if we are already throttling, then the abuse detector might not be needed? However, the abuse detector might set the abuse state to ABUSE which then uses the abuse bucket (which is even lower). So we want to detect abuse even if the tenant is being throttled.
So we consider total_requests = allowed + throttled.
baseline = average of the last 10 minutes of total_requests.
spike_factor = (current.total_requests - baseline) / baseline (if baseline>0, else 0)
error_rate = current.backend_errors / current.allowed (if allowed>0, else 0)
score = spike_factor * 0.5 + error_rate * 0.5
Then:
if score > high_threshold (0.8) and current state is NORMAL -> set to ABUSE.
if score < low_threshold (0.2) and current state is ABUSE -> set to NORMAL.
Then update Redis abuse state.
g) We also need to consider:
- The abuse detector should run for the organization (for non-dedicated features) and for each feature that has dedicated quota.
How to iterate over all tenants and features?
We can have a list of active tenants? Or we can store the metrics for every (tenant, feature) that had activity? Then the abuse detector only checks those that had activity in the last 10 minutes?
We can have the metrics service expose:
get_active_tenants_and_features(last_n_minutes=10)
that returns:
[
{tenant_id: t1, feature: f1, org: false},
{tenant_id: t1, feature: null, org: true}, // for org
...
]
Then the abuse detector iterates over these.
class ThrottlingMiddleware:
def __init__(self, config_service, redis_client, metrics_queue):
self.config_service = config_service
self.redis = redis_client
self.metrics_queue = metrics_queue
self.abuse_cache = {} # (tenant_id, feature) -> (state, expiry)
self.abuse_cache_ttl = 2
def handle(self, request):
tenant_id = self._extract_tenant(request)
feature = self._extract_feature(request)
# 1. Check feature enabled
if not self.config_service.is_feature_enabled(tenant_id, feature):
self._emit_metric(tenant_id, feature, 'throttled', 'feature_disabled')
return self._reject(403, "Feature disabled")
# 2. Get quotas
feature_quota = self.config_service.get_feature_quota(tenant_id, feature)
org_quota = self.config_service.get_org_quota(tenant_id)
# 3. Determine bucket
if feature_quota is not None:
abuse_state = self._get_abuse_state(tenant_id, feature)
if abuse_state == 'ABUSE':
bucket = self._get_abuse_bucket_for_feature(tenant_id, feature)
else:
bucket = self._get_normal_bucket_for_feature(tenant_id, feature, feature_quota)
else:
abuse_state = self._get_abuse_state(tenant_id, 'org')
if abuse_state == 'ABUSE':
bucket = self._get_abuse_bucket_for_org(tenant_id)
else:
bucket = self._get_normal_bucket_for_org(tenant_id, org_quota)
# 4. Try to consume
if bucket.try_consume():
self._emit_metric(tenant_id, feature, 'allowed', None)
return self._proceed(request)
else:
self._emit_metric(tenant_id, feature, 'throttled', 'quota_exceeded')
return self._reject(429, "Rate limit exceeded")
def _get_abuse_state(self, tenant_id, feature):
key = (tenant_id, feature)
now = time.time()
if key in self.abuse_cache:
state, expiry = self.abuse_cache[key]
if now < expiry:
return state
# Fetch from Redis
redis_key = f"abuse:{tenant_id}:{feature}"
state = self.redis.get(redis_key)
if state is None:
state = 'NORMAL'
self.abuse_cache[key] = (state, now + self.abuse_cache_ttl)
return state
def _get_normal_bucket_for_feature(self, tenant_id, feature, quota):
# quota is an object with capacity and refill_rate_per_minute
key_prefix = f"bucket:feature:{tenant_id}:{feature}:normal"
return TokenBucket(self.redis, key_prefix, quota.capacity, quota.refill_rate_per_minute)
def _get_abuse_bucket_for_feature(self, tenant_id, feature):
# Fixed abuse bucket: capacity=10, refill_rate_per_minute=10
key_prefix = f"bucket:feature:{tenant_id}:{feature}:abuse"
return TokenBucket(self.redis, key_prefix, 10, 10)
Similarly for org.
def _emit_metric(self, tenant_id, feature, event_type, reason):
# Send to message queue
msg = {
'tenant_id': tenant_id,
'feature': feature,
'event_type': event_type,
'reason': reason,
'timestamp': time.time()
}
self.metrics_queue.send(json.dumps(msg))