Engineer a backend rate limiter layering IP, tenant, and feature quotas with metrics.
- User
Engineer a backend rate limiter layering IP, tenant, and feature quotas with metrics.
Assistant
Engineer a backend rate limiter layering IP, tenant, and feature quotas with metrics.
The user wants me to engineer a backend rate limiter. This is a system design/implementation task. The requirements are:
Core Logic Design:
RateLimiter interface and an in-memory version for the example.Implementation Details:
RateLimitStrategy: The core logic (e.g., Token Bucket).Store: Where state lives (In-memory dict vs Redis).Middleware/Dependency: The layer that intercepts requests.Config: Defining the limits (e.g., {"ip": 100, "tenant": 50, "feature": 10}).Metrics: prometheus_client is standard, but I'll use a simple counter/logic wrapper to keep dependencies low while demonstrating the concept.Refining the Code:
RateLimiter Class: Needs is_allowed(key) method.LayeredLimiter Class: This is the orchestrator. It takes the request, extracts IP, Tenant ID, and Feature Name. It checks limits in order.requests_total, rate_limited_total, allowed_total. Labels should include layer (ip, tenant, feature) and tenant_id.Drafting the Code (Mental or Scratchpad):
IP Limit: key = f"ip:{ip}", limit = 1000.
Tenant Limit: key = f"tenant:{tenant_id}", limit = get_tenant_limit(tenant_id) (e.g., 100).
Feature Limit: key = f"feature:{tenant_id}:{feature}", limit = 10.
Algorithm: Let's use a simple fixed window counter for brevity in code, but mention sliding window.
Security/Metrics Note:
X-RateLimit-Limit, X-RateLimit-Remaining) are good practice.Final Polish: I will provide a complete, runnable Python script using FastAPI. It will simulate a Redis-like store in memory for portability but explain how to swap it.
Steps:
RateLimitStore (abstract) and InMemoryStore (implementation).LayeredRateLimiter logic.429 Too Many Requests.prometheus_client to expose real-time metrics for allowed vs. rejected requests per layer.You will need fastapi, uvicorn, and prometheus-client to run this example.
pip install fastapi uvicorn prometheus-client
Run the server:
python -m uvicorn main:app --reload
Normal Traffic: Access http://127.0.0.1:8000/. It should succeed.
Hit IP Limit (Layer 1):
If you send > 100 requests in 60 seconds from the same IP, you will get:
ip Rate limit exceeded.
Hit Feature Limit (Layer 3):
The /expensive-feature has a limit of 10 req/min defined in the logic.
Refresh http://127.0.0.1:8000/expensive-feature 11 times quickly. You will see:
feature Rate limit exceeded.
Note that the root endpoint might still work (up to 100 times) because the feature limit is specific to the path key.
Check Metrics:
Visit http://127.0.0.1:8000/metrics. You will see counters like:
rate_limiter_feature_total{status="allowed"} 10.0
rate_limiter_feature_total{status="rejected"} 1.0
RateLimiter so different tenants have different limits (e.g., Free vs. Pro).X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers. The middleware should calculate these and attach them to the response object.import time
import threading
from collections import defaultdict
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import PlainTextResponse
from prometheus_client import Counter, generate_latest, CONTENT_TYPE_LATEST
# --- 1. Metrics Configuration ---
# We track rejections and accepts per layer to understand where pressure exists.
RATE_LIMIT_METRICS = {
"ip": Counter('rate_limiter_ip_total', 'IP layer rate limit hits', ['status']),
"tenant": Counter('rate_limiter_tenant_total', 'Tenant layer rate limit hits', ['status']),
"feature": Counter('rate_limiter_feature_total', 'Feature layer rate limit hits', ['status'])
}
# --- 2. Storage Engine (Thread-Safe In-Memory Mock) ---
# In production, replace this with Redis + Lua scripts for atomicity across multiple backend instances.
class RateLimitStore:
def __init__(self):
self.lock = threading.Lock()
# Structure: { key: [timestamp1, timestamp2, ...] }
self.store = defaultdict(list)
def cleanup(self, key, window_size):
"""Remove timestamps older than the window."""
cutoff = time.time() - window_size
self.store[key] = [t for t in self.store[key] if t > cutoff]
def count_and_add(self, key, window_size):
"""
Checks count, adds current timestamp if under limit.
Returns (current_count, allowed_bool)
"""
now = time.time()
with self.lock:
self.cleanup(key, window_size)
current_count = len(self.store[key])
return current_count
def increment(self, key, window_size):
"""Atomically add a timestamp."""
now = time.time()
with self.lock:
self.cleanup(key, window_size)
self.store[key].append(now)
return len(self.store[key])
store = RateLimitStore()
# --- 3. The Rate Limiting Logic ---
class RateLimiter:
def __init__(self, store):
self.store = store
def _check_layer(self, layer_name: str, key: str, limit: int, window_seconds: int):
"""
Generic sliding window check.
"""
# 1. Check current count
current_count = self.store.count_and_add(key, window_seconds)
# 2. Decision
if current_count >= limit:
RATE_LIMIT_METRICS[layer_name].labels(status='rejected').inc()
return False, f"{layer_name.capitalize()} rate limit exceeded."
# 3. Increment (In a real distributed system, this increment happens
# atomically after the check or via Lua script)
self.store.increment(key, window_seconds)
RATE_LIMIT_METRICS[layer_name].labels(status='allowed').inc()
return True, "OK"
def process_request(self, ip: str, tenant_id: str, feature: str):
"""
Layered Checks:
1. IP (Global DoS protection)
2. Tenant (Subscription limits)
3. Feature (Resource specific limits)
"""
now = time.time()
# Layer 1: IP Address
# Example: 100 requests per minute per IP
allowed, msg = self._check_layer("ip", f"ip:{ip}", limit=100, window_seconds=60)
if not allowed:
return 429, msg
# Layer 2: Tenant
# Example: Tenant subscription allows 500 requests per minute
allowed, msg = self._check_layer("tenant", f"tenant:{tenant_id}", limit=500, window_seconds=60)
if not allowed:
return 429, msg
# Layer 3: Feature
# Example: Specific expensive feature (e.g., AI generation) limited to 10 per minute
allowed, msg = self._check_layer("feature", f"feature:{tenant_id}:{feature}", limit=10, window_seconds=60)
if not allowed:
return 429, msg
return 200, "Request Processed"
# --- 4. FastAPI Integration ---
app = FastAPI()
limiter = RateLimiter(store)
# Mock Data Extraction
def get_request_context(request: Request):
# In real life, extract from Headers, JWT, or API Gateway context
ip = request.client.host
# Hardcoded for demo: Tenant ID comes from header 'X-Tenant-ID'
tenant_id = request.headers.get("X-Tenant-ID", "public-access")
# Feature is derived from path (simplified)
feature = request.url.path
return ip, tenant_id, feature
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
# Skip metrics endpoint to avoid recursion
if request.url.path == "/metrics":
return await call_next(request)
ip, tenant_id, feature = get_request_context(request)
status_code, message = limiter.process_request(ip, tenant_id, feature)
if status_code == 429:
# Return Rate Limit Error
return PlainTextResponse(content=message, status_code=429, headers={
"Retry-After": "60"
})
response = await call_next(request)
return response
# --- 5. Routes & Metrics Endpoint ---
@app.get("/")
async def root():
return {"status": "ok", "message": "Request passed the rate limiter."}
@app.get("/expensive-feature")
async def expensive_feature():
# This endpoint has a specific feature limit defined in process_request
return {"data": "This is an expensive resource."}
@app.get("/metrics")
async def metrics():
"""Prometheus scraping endpoint"""
return PlainTextResponse(generate_latest(), media_type=CONTENT_TYPE_LATEST)
# To run: uvicorn filename:app --reload