Rate Limiting

Why and where to rate limit, the main algorithms (token bucket, leaky bucket, fixed and sliding windows) with code, distributed rate limiting with Redis, and how to communicate limits.

Intermediate 3 min readLesson 12 of 20 Interview Q&A

Rate limiting caps how many requests a client can make in a period. It protects services from abuse and accidental overload (a buggy client in a retry loop), keeps usage fair between tenants, controls costs, and blunts brute-force and scraping attacks.

Where to limit

  • Edge / API gateway — per IP, API key or user, before traffic reaches your services.
  • Per service — protect expensive endpoints (search, login, exports).
  • Outbound — respect third-party limits when calling others.
  • Per key — the limit key can be IP, user ID, API key, tenant, or a combination (user + endpoint).

Algorithms

Token bucket (most common)

A bucket holds up to B tokens and refills at r tokens per second. Each request takes a token; with no tokens left, it's rejected. It allows bursts up to B while enforcing an average rate r.

refill r tokens/sbucketcapacity Brequest takes 1 tokenallow / 429
class TokenBucket {
    private final double capacity, refillPerSec;
    private double tokens;
    private long last = System.nanoTime();

    TokenBucket(double capacity, double refillPerSec) {
        this.capacity = capacity; this.refillPerSec = refillPerSec; this.tokens = capacity;
    }

    synchronized boolean tryAcquire() {
        long now = System.nanoTime();
        tokens = Math.min(capacity, tokens + (now - last) / 1e9 * refillPerSec);  // lazy refill
        last = now;
        if (tokens < 1) return false;
        tokens -= 1;
        return true;
    }
}

The others

AlgorithmHowProsCons
Token bucketTokens refill at rate r up to BAllows bursts; smooth average; tiny stateTwo parameters to tune
Leaky bucketRequests queue and drain at a constant ratePerfectly smooth outputBursts are delayed or dropped; adds latency
Fixed window counterCount per calendar window (per minute)Simplest: one counter with an expiryBoundary burst: 100 at 0:59 + 100 at 1:00 = 200 in two seconds
Sliding window logStore each request's timestamp; count those in the last windowExactMemory per request
Sliding window counterWeighted mix of the current and previous window countsClose to exact, tiny stateApproximate

Sliding window counter estimate:

count≈current+previous×window−elapsedwindow\text{count} \approx \text{current} + \text{previous} \times \frac{\text{window} - \text{elapsed}}{\text{window}}

Distributed rate limiting

With many API servers, limits must be shared. The usual approach is Redis with atomic operations:

lua
-- Fixed-window limiter as a Redis Lua script (atomic)
local current = redis.call("INCR", KEYS[1])
if current == 1 then
  redis.call("EXPIRE", KEYS[1], ARGV[1])      -- window length in seconds
end
if current > tonumber(ARGV[2]) then            -- limit
  return 0
end
return 1

Token buckets can be implemented the same way (store tokens and last refill time; update in a Lua script). Considerations:

  • Redis adds a network round trip per request; keep it close (same zone), or batch with local limiters that sync periodically (approximate, but cheap).
  • Decide what happens when Redis is down: fail open (allow — favours availability) or fail closed (deny — favours protection).
  • Gateways and proxies often have this built in: Envoy, Kong, nginx limit_req, Cloudflare and AWS API Gateway.

Communicating limits

HTTP
HTTP/1.1 429 Too Many Requests
Retry-After: 30
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 30

Clients should honour Retry-After and back off exponentially with jitter, so throttled clients don't all retry in sync.

Rate limiting enforces per-client fairness. Load shedding protects the service as a whole: when overloaded (queue too long, latency too high), reject or deprioritise low-priority traffic early so important traffic still succeeds. Both belong in a robust system (Reliability patterns).

Key takeaways
  • Rate limiting protects against abuse and overload and enforces fairness.
  • Token bucket: bursts up to B, average rate r — the usual default.
  • Fixed windows are simple but allow boundary bursts; sliding windows fix that.
  • Distributed limits use Redis with atomic scripts; decide on fail-open or fail-closed.
  • Return 429 with Retry-After; clients back off with jitter.
Interview questions
QDesign a rate limiter for an API with 10 million users.hard

Limit at the API gateway by API key or user, using a token bucket per key stored in a Redis cluster (sharded by key) and updated atomically with a Lua script. Configure limits per plan and per endpoint. Add a small local in-memory limiter to absorb extreme bursts cheaply. Return 429 with Retry-After and rate-limit headers, and decide fail-open behaviour if Redis is unavailable. Monitor rejections per key to spot abuse.