The first check protects the provider and your overall budget. This request passes because total traffic is within the cap.
Step 2 of 4
Per-IP limit
A sliding window per IP address slows scripted abuse before it costs anything. This client is within its window.
Step 3 of 4
Per-user limit
A token bucket per user keeps heavy users from starving others. Counters live in a shared store such as Redis once there is more than one server.
Step 4 of 4
Cost budget
The request's estimated cost, from its prompt size and model, would push this user past their per-minute budget. It is rejected with a 429 and a Retry-After header.
A request count alone misses expensive calls; limit on estimated cost as well.
Problem
Without rate limits, a single user or abuser can blow through your cost budget or DDoS the provider.
Pattern
Apply per-user, per-IP and global rate limits using a token bucket or sliding window, with a cost-based limit (not just request count).
Implementation
rate_limit.py
~219 tokens
import time
from collections import defaultdict
# Token bucket: cost-budgeted
class CostLimiter:
def __init__(self, per_minute_usd=1.0):
self.budget = defaultdict(float)
self.window_start = defaultdict(float)
def check(self, user_id, cost_usd):
now = time.time()
if now - self.window_start[user_id] > 60:
self.budget[user_id] = 0
self.window_start[user_id] = now
if self.budget[user_id] + cost_usd > per_minute_usd:
return False
self.budget[user_id] += cost_usd
return True
limiter = CostLimiter(per_minute_usd=2.0)
def call_with_limit(user_id, messages):
est_cost = estimate_cost(messages, model)
if not limiter.check(user_id, est_cost):
raise RateLimitError("Cost budget exceeded")
return call_llm(messages)