Scalability2 min read

Rate Limiter

How services protect themselves from bursts and abuse — token bucket, sliding windows, and where to enforce limits.

A rate limiter caps how many requests a client can make in a period of time. It keeps one noisy client from starving everyone else, protects expensive downstream systems, and turns overload into a clear, retryable error instead of a slow outage.

Why you need one

  • Fairness — one tenant’s batch job should not slow down every other tenant.

  • Cost control — paid APIs and databases have real limits and real bills.

  • Abuse prevention — login brute-forcing and scraping become much harder.

  • Predictable overload — rejecting early is cheaper than timing out late.

Common algorithms

Token bucket

Each client has a bucket that refills at a steady rate (say 10 tokens per second) up to a capacity (say 20). Each request spends one token; an empty bucket means the request is rejected. The capacity allows short bursts while the refill rate enforces the long-run average. This is the most popular choice.

Fixed window counter

Count requests per client per minute (user:42:2026-10-22T10:15). Simple and cheap, but a client can send double the limit across a window boundary — 100 requests at 10:15:59 and 100 more at 10:16:00.

Sliding window

Smooths the boundary problem by weighting the previous window’s count by how much of it still overlaps the last 60 seconds. It costs two counters per client and gives a much more accurate limit.

A token bucket in Redis

In a fleet of servers the counters must be shared, so they usually live in Redis. Doing the read-refill-spend step in one Lua script keeps it atomic:

-- KEYS[1] = bucket key, ARGV = capacity, refill_per_sec, now_ms
local capacity = tonumber(ARGV[1])
local rate     = tonumber(ARGV[2])
local now      = tonumber(ARGV[3])
local bucket   = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens   = tonumber(bucket[1]) or capacity
local ts       = tonumber(bucket[2]) or now
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)
local allowed = tokens >= 1
if allowed then tokens = tokens - 1 end
redis.call("HSET", KEYS[1], "tokens", tokens, "ts", now)
redis.call("PEXPIRE", KEYS[1], math.ceil(capacity / rate * 1000))
return allowed and 1 or 0

Where to enforce it

  • API gateway / edge — coarse per-IP or per-key limits before traffic reaches your services.

  • Service level — per-user or per-tenant limits that need business context.

  • Client side — well-behaved SDKs throttle themselves and respect Retry-After.

Responding to limited clients

Return HTTP 429 Too Many Requests with a Retry-After header, and expose RateLimit-Limit / RateLimit-Remaining so clients can slow down before they hit the wall.

Interview tip: state the limit key (user, API key, IP), the algorithm, where counters live, and what happens when the counter store itself is down — fail open or fail closed?