{}DSA Atlas

Rate Limiting & Quotas

Why and where to rate limit, the five classic algorithms (fixed window, sliding log, sliding window counter, token bucket, leaky bucket/GCRA) with code, distributed rate limiting with Redis and Lua, response headers, client behaviour, quotas and fairness.

Intermediate → Advanced5 interview questions

Why rate limit?

  1. Protect availability — stop one client (buggy loop, scraper, attacker) from starving everyone.
  2. Fairness — share capacity across tenants.
  3. Security — slow brute force, credential stuffing, enumeration, OTP guessing.
  4. Cost control — expensive downstreams (LLM calls, SMS, third-party APIs).
  5. Monetisation — plans with different quotas.

Where to limit

Client SDKself-throttle CDN / WAFper IP, bots API gatewayper key / tenant Serviceper action DownstreamDB pools, 3rd-party coarse limits at the edge, precise per-tenant limits at the gateway, business limits in services
Rate limiting is layered, not a single box.

The algorithms

Token bucket (capacity 5, refill 1/s) +1 token / second request takes a token; empty → 429 bursts up to 5, sustained 1 req/s Fixed window boundary burst window 1 (limit 100)window 2 (limit 100) 100 + 100 in ~1 s sliding windows / token buckets fix this
Token bucket allows controlled bursts; fixed windows allow accidental double bursts at the boundary.
AlgorithmMemory per keyAccuracyBurstsNotes
Fixed window counterO(1)boundary spikes up to 2×uncontrolledINCR + EXPIRE; simplest
Sliding window logO(requests in window)exactnone beyond limitsorted set of timestamps
Sliding window counterO(1)~exact (assumes even spread)smoothedCloudflare's approach
Token bucketO(1)exactcontrolled (capacity)most popular
Leaky bucket / GCRAO(1)exactnone (smooth output)GCRA = token bucket expressed as a "theoretical arrival time"

Token bucket (in-process)

import time, threading

class TokenBucket:
    def __init__(self, rate: float, capacity: int):
        self.rate, self.capacity = rate, capacity
        self.tokens = float(capacity)
        self.updated = time.monotonic()
        self.lock = threading.Lock()

    def allow(self, cost: float = 1.0) -> bool:
        with self.lock:
            now = time.monotonic()
            self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
            self.updated = now
            if self.tokens >= cost:
                self.tokens -= cost
                return True
            return False

limiter = TokenBucket(rate=10, capacity=20)   # 10 req/s sustained, bursts of 20
class TokenBucket {
  private tokens: number;
  private updated = performance.now();
  constructor(private rate: number, private capacity: number) { this.tokens = capacity; }

  allow(cost = 1): boolean {
    const now = performance.now();
    this.tokens = Math.min(this.capacity, this.tokens + ((now - this.updated) / 1000) * this.rate);
    this.updated = now;
    if (this.tokens < cost) return false;
    this.tokens -= cost;
    return true;
  }
}

Sliding window counter

Text
estimate = count(current window) + count(previous window) × (1 − elapsed_fraction_of_current_window)

limit 100/min, at 12:01:15 (25% into the window):
previous window (12:00) = 80, current (12:01) = 30
estimate = 30 + 80 × 0.75 = 90 → allowed (< 100)

Sliding window log

Python
# Redis sorted set: one member per request
def allow(r, key, limit, window_s, now_ms, req_id):
    pipe = r.pipeline()
    pipe.zremrangebyscore(key, 0, now_ms - window_s * 1000)   # drop old entries
    pipe.zadd(key, {req_id: now_ms})
    pipe.zcard(key)
    pipe.pexpire(key, window_s * 1000)
    _, _, count, _ = pipe.execute()
    return count <= limit        # (a rejected request still counted — fine for abuse limits)

Distributed token bucket in Redis (atomic Lua)

-- KEYS[1] = bucket key; ARGV = rate (tokens/s), capacity, cost
local rate, capacity, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local t = redis.call('TIME')                                -- server clock: no app clock skew
local now = tonumber(t[1]) + tonumber(t[2]) / 1e6
local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) * rate)
local allowed = 0
if tokens >= cost then tokens = tokens - cost; allowed = 1 end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) * 2)
return {allowed, tokens}
import redis
r = redis.Redis()
bucket = r.register_script(open("token_bucket.lua").read())

def check(api_key: str, endpoint_class: str) -> bool:
    allowed, remaining = bucket(keys=[f"rl:{api_key}:{endpoint_class}"], args=[10, 20, 1])
    return allowed == 1
clients LB gateway 1 gateway 2 gateway 3 Redis Clusteratomic Lua per key all gateways share one counter per key; Lua makes read-modify-write atomic
A shared store makes limits global across many stateless servers.

Responses and client behaviour

HTTP
HTTP/1.1 429 Too Many Requests
Retry-After: 12
RateLimit-Policy: "default";q=100;w=60
RateLimit: "default";r=0;t=12
Content-Type: application/problem+json

{"type":"https://api.example.com/errors/rate-limited","title":"Too many requests","status":429,
 "detail":"Limit of 100 requests per 60 s for key sk_live_51Hc… exceeded."}

Well-behaved clients: honour Retry-After, back off exponentially with jitter, spread scheduled jobs (no cron at :00 for everyone), and cap concurrency.

Choosing keys and limits

KeyUse
API key / OAuth clientpublic APIs, plans
User IDper-user fairness
Tenantnoisy-neighbour protection
IP / subnet / ASNunauthenticated endpoints, bots (beware NAT/CGNAT sharing IPs)
Endpoint class / costexpensive operations get stricter limits or higher token cost
Compositetenant + endpoint, user + action

Cost-based limiting: charge more tokens for expensive operations (search, exports, LLM tokens) instead of counting requests equally — GitHub's GraphQL API and LLM APIs (tokens per minute) do this.

Operational concerns

  • Failure mode when the limiter store is down: fail open (most APIs) or closed (auth/SMS).
  • Latency: keep the check sub-millisecond; local caches for hot keys; pipeline/batch.
  • Observability: metrics of allowed/denied per key; alert on sudden spikes; dashboards for customers.
  • Exemptions and overrides: internal traffic, enterprise plans, temporary increases.
  • Test with load tests, including boundary bursts and clock skew.

See the rate limiter case study for a full system design answer.

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.