SteelReed

Search

Search posts, questions…

7. System Design

Rate limiting: five algorithms, a token bucket on Redis, and designing a distributed limiter

Fixed window, sliding log, sliding window counter, leaky bucket and token bucket compared on one example; why token bucket is the usual pick; a token bucket in Redis Lua, fetching tokens in batches, and what to decide when Redis is slow or down.

18 Nov 20269 min readSenior

–

1. The problem

A limit of 10 requests/minute per API key, implemented as a per-minute counter. A client sends 10 requests at 00:59 and 10 at 01:00: 20 requests get through in 2 seconds. The fix reads the token count from Redis, computes in Java and writes it back: two instances both read "1 left" and both let a request through.

2. Key idea

Rate limiting caps how many requests a subject (API key, user id, IP) can send in a period. Nginx limit_req blocks coarsely by IP; the gateway limits by plan; the service limits expensive operations (OTPs). Reject with 429 and Retry-After.

A token bucket is like a ticket machine: it issues tickets steadily (rate), the box holds at most capacity; visitors with a ticket go straight in, without one they wait outside. It stores just two numbers: tokens left and the last refill time; each request tops up based on elapsed time.

Fixed window Sliding log Sliding counter Leaky bucket Token bucket
Memory / key 1 number N timestamps 2 numbers a queue 2 numbers
Boundary burst ×2 gets through none small none yes, up to capacity
Requests wait no no no yes no

The sliding window counter estimates this_minute + last_minute × remaining fraction of last minute: at second 18, last minute 8, this minute 3, the estimate is 3 + 8 × 0.7 = 8.6 < 10 → allowed.

2.1 Which algorithm?

Algorithm Use when Don't use when
Token bucket the default: little memory, O(1), bounded bursts the backend only tolerates a perfectly even rate
Leaky bucket (a queue drained evenly) calling third-party APIs with hard quotas requests can't be made to wait
Sliding window counter you need exactly "N requests per clock minute" even short bursts break the backend

Window-based algorithms only cap the total: 10 requests can still arrive in the first 100 ms.

3. On Redis

LUA
-- KEYS[1] = rl:{apiKey}   ARGV: rate (tokens/s), capacity, requested
local rate, cap, req = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3])
local t = redis.call('TIME')                                  -- Redis's clock, not the caller's
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local s = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(s[1]) or cap
local ts = tonumber(s[2]) or now
tokens = math.min(cap, tokens + (now - ts) / 1000 * rate)     -- refill
local allowed = tokens >= req
if allowed then tokens = tokens - req end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 1000) + 1000)
return { allowed and 1 or 0, tostring(tokens) }
-- Java: redis.execute(script, List.of("rl:" + apiKey), "1", "60", "1")

Lua runs atomically because Redis executes commands one at a time. Java libraries: Bucket4j has a Redis backend; Guava and Resilience4j work within one JVM only.

Fewer round trips, load estimates and when Redis dies
  • Batch fetching: an instance calls the script with requested = 20, keeps 20 tokens in memory and serves 20 requests without Redis. The global limit drifts slightly, so keep batches small relative to capacity.
  • Two tiers: a local limit / N limiter (in-memory Bucket4j) blocks coarsely, Redis enforces plans precisely.
  • Estimates: ~100 bytes/key, 10 million keys ≈ 1 GB. 200K requests/s means 200K script calls, beyond one node (~50–80K commands/s): Redis Cluster, keyed by API key so slots spread evenly.
  • Redis down: fail-open (allow) when the limit is about fairness; fail-closed (block) when it protects something expensive or dangerous (SMS OTPs, money transfers). Combine a 5–10 ms Redis timeout, a circuit breaker and a local fallback limiter.
  • Multi-region: one Redis per region with per-region quotas; global sync per request is too slow.
  • RateLimit-Limit and RateLimit-Remaining headers help clients self-throttle; clients retry with exponential backoff + jitter and respect Retry-After.

4. Working with AI

Delegate to AI: the Lua script, gateway filters, tests with many instances hitting one key.

Check yourself:

  • Read, compute and write happen in one Lua script, not GET then SET from Java.
  • now comes from Redis TIME, not each machine's clock.
  • Fail-open or fail-closed is decided per endpoint type, with a short Redis timeout.
  • Rejections return 429 with Retry-After.

5. Exercises

Exercise 1: Design rate limits for a multi-plan API

Free 60 requests/minute, Pro 1,000/minute, Enterprise 10,000/minute with bursts of 2,000. 5 million API keys, peak 150K requests/s through 30 gateways. Choose the algorithm, parameters, storage and how to handle a slow Redis.

Solution to Exercise 1
  • Token bucket for every plan. Free: rate = 1/s, capacity = 60. Pro: rate ≈ 16.7/s, capacity = 1,000. Enterprise: rate ≈ 167/s, capacity = 2,000.
  • Storage: Redis Cluster, key rl:{apiKey}; 5M × ~100 B ≈ 500 MB. 150K commands/s → 3–4 masters, each with a replica.
  • Less load: Enterprise fetches tokens in batches of 50 per instance; Free/Pro call the script per request.
  • Slow Redis: 10 ms timeout, a circuit breaker opening at > 50% errors over 10 s, falling back to local Bucket4j at limit / 30. Fail-open for reads, fail-closed for sending SMS.

Exercise 2: Review a limiter that "stops bursts"

AI wrote a sliding window log on a ZSET limiting 600 requests/minute, noting "stops bursts, safe for a search API that handles only 20 requests/second". True? What about memory with 1 million keys?

Solution to Exercise 2
  • False: the window only caps 600 over 60 seconds; all 600 can still arrive within 1 second, 30x what the search API handles. Add a 20 requests/second limit (a token bucket with small capacity) or use a leaky bucket.
  • Memory: a sliding log stores up to 600 timestamps per key; 1 million active keys means up to 600 million ZSET members, tens of GB. A token bucket is 2 numbers per key, ~100 MB.

Summary

  • Fixed window lets ×2 through at the boundary; the sliding counter estimates with two counters.
  • Token bucket is the default: 2 numbers per key, bursts up to capacity.
  • Leaky bucket when the backend needs a perfectly even rate.
  • Distributed: a Lua script on Redis, with now from Redis TIME.
  • Decide fail-open or fail-closed for each endpoint in advance.

Back to: Part 1: Multi-level cache and large-scale counters.

Practice interview questions on this topic

All Caching & Redis questions →

Loading comments…
Next on the roadmapMicroservices: when to split, finding service boundaries, and carving up a monolith step by step