SDE & MLE Prep

Rate Limiting Algorithms

AlgorithmIdeaPros / cons
Token bucketbucket refills at rate r up to capacity b; each request takes a tokenallows bursts up to b; tiny state (tokens, last_refill) — most common
Leaky bucketqueue drains at fixed ratesmooth output; bursts get queued/dropped
Fixed window countercount per minute windowsimple; 2× burst at window edges
Sliding window logstore timestamps, count last 60 sexact; memory heavy
Sliding window counterweighted current + previous windowgood approximation, cheap
def allow(key, rate, capacity, now):
    tokens, last = store.get(key, (capacity, now))
    tokens = min(capacity, tokens + (now - last) * rate)   # refill
    if tokens < 1:
        return False
    store[key] = (tokens - 1, now)
    return True

Distributed: keep counters in Redis with an atomic Lua script (or INCR + EXPIRE); return HTTP 429 with Retry-After.