Design a rate limiter: algorithms and design

A rate limiter decides, for every request, whether a client has used up its share. If yes, the request is rejected, usually with HTTP 429 Too Many Requests. It protects the service from one noisy client, keeps usage fair between customers, stops abuse such as password guessing, and keeps the bill under control when each call costs money. This lesson designs a limiter for a public API: the algorithms, the shared state, and what happens when the limiter itself fails.

Background note: four words that get mixed up

  • Rate limiting: a rule per client, such as "600 requests per minute for this API key". Excess requests are rejected.
  • Throttling: slowing a client down instead of rejecting, for example by delaying its requests. Many people use it as another word for rate limiting.
  • Quota: a long-period allowance, such as 1 million calls a month on a paid plan. It is about billing and plans, and is counted, not checked in microseconds.
  • Load shedding: the service drops work because it is overloaded as a whole, whoever sent it (see the resilience lesson). A rate limiter looks at one client. Shedding looks at the service.

1. Requirements and Scope

Functional requirements:

  • Limit requests by a key: API key, user ID, IP address, or a mix with the route.
  • Support different rules: a free plan and a paid plan, a strict rule for login, a cost of more than one for expensive calls.
  • Allow short bursts, but hold the long-term average.
  • Tell the client what happened: rejected, and when to retry.
  • Change rules without a deploy.

Non-functional requirements:

  • Fast: the check adds under 2 ms to each request, because it runs on every request.
  • Highly available: if the limiter breaks, the API must not go down with it.
  • Accurate enough: a client may slip a few requests over the limit. It must not get double.
  • Works across many servers: 100 gateway servers must enforce one limit, not 100 limits.

Out of scope: large DDoS floods, which are stopped at the edge (see the DDoS lesson), and billing.

2. Estimation

  • Traffic: 1 billion API requests a day. 1,000,000,000 ÷ 86,400 ≈ 11,600 per second on average, and about 4 times that at peak: 46,400 per second. Every request needs one limiter check.
  • Latency: a round trip to Redis in the same zone takes about 0.5 ms. One Redis call per request fits the 2 ms budget. Two or three calls would not.
  • Redis load: a Lua script is heavier than a plain command, so assume 50,000 checks per second per node. Peak 46,400 × 1.5 for zone loss ≈ 69,600, so 2 nodes by load. We run 3 shards, one per zone, each with a replica in another zone.
  • Memory: 5 million active API keys × about 100 bytes per bucket = 500 MB. Tiny. Idle keys expire.

The takeaway: size and speed are easy. The hard parts are atomicity (no lost updates), the extra latency on every request, and what happens when the limiter is down.

3. What the Client Sees

A rejected request returns 429 with a Retry-After header in seconds, and a short body saying which limit was hit. Many APIs also send headers on every response with the limit and what is left (commonly X-RateLimit-Limit and X-RateLimit-Remaining; an IETF draft standardizes RateLimit-* names). Good clients use these to slow down before they are rejected. A rejection with no Retry-After makes clients retry at once, which makes things worse.

4. High-Level Design

flowchart LR
  C["Clients"] --> LB["Load balancer"]
  LB --> G["API gateway: rate limit check"]
  G -->|allowed| S["Backend services"]
  G -.->|over limit| R["429 + Retry-After"]
  G --> RD[("Redis: buckets, 3 shards")]
  RS["Rules service"] -.->|"limits, refreshed every few seconds"| G
  G -.-> M["Metrics: allowed, rejected, errors"]
  • Where it runs: in the API gateway (see the gateway lesson), before authentication-heavy or expensive work. Rejecting early is cheap. A limiter inside each service also works but repeats the logic everywhere.
  • Where the counts live: a shared store, Redis, because every gateway server must see the same numbers. Local memory alone gives 100 limits for 100 servers.
  • Where the rules live: a rules service or config store. Gateways keep a local copy and refresh it every few seconds, so a rules outage does not block traffic.

5. The Algorithms

All of them answer one question: "have there been too many requests recently?" They differ in memory, accuracy, and how they treat bursts. We use a limit of 100 requests per minute as the example.

5.1 Fixed Window Counter

Count requests in each clock minute. At the start of the next minute the count resets. It is one counter per key, which is the cheapest. The flaw is the edge: a client sends 100 requests at 12:00:59 and 100 more at 12:01:00. That is 200 requests in two seconds, double the limit, and every one of them was allowed.

5.2 Sliding Window Log

Store the timestamp of every request. On a new request, drop timestamps older than a minute and count the rest. It is exact, but it stores up to 100 timestamps per key. For a limit of 10,000 per minute that is far too much memory.

5.3 Sliding Window Counter

Keep two fixed-window counters, the current minute and the previous one, and weigh the previous one by how much of it still overlaps the sliding window. Example: the previous minute had 80 requests, the current minute has 30, and we are 25% into the current minute. Estimate = 80 × 0.75 + 30 = 90, which is under 100, so the request is allowed. It assumes the previous minute's requests were evenly spread, so it is an approximation, but a very close one, and it needs only two numbers per key.

5.4 Token Bucket

Each key has a bucket that holds up to b tokens (the burst size). Tokens are added at r per second (the long-term rate). Each request takes one token. No token means reject. The bucket is stored as two numbers, the token count and the time of the last refill, and it is refilled lazily when a request arrives: tokens = min(b, tokens + elapsed × r). No timers run in the background.

With b = 10 and r = 2 per second, a client can send 10 requests at once, then 2 per second after that. A quiet client builds up credit, up to the bucket size, and uses it for a burst. This is how real clients behave, which is why token bucket is the usual default.

5.5 Leaky Bucket

Requests enter a queue that drains at a fixed rate, like water leaking from a bucket. If the queue is full, new requests are rejected. It smooths bursty traffic into a steady stream, so it fits a downstream that cannot take bursts. Used only as a counter, it behaves like a token bucket.

5.6 Comparison

Algorithm Memory per key Accuracy Bursts
Fixed window 1 counter Poor at window edges (up to 2x) Allowed, in an uncontrolled way
Sliding window log One timestamp per request Exact No extra bursts
Sliding window counter 2 counters Very close No extra bursts
Token bucket 2 numbers Exact for its rule Controlled by bucket size
Leaky bucket Queue or 2 numbers Exact Smoothed out

Which one to pick: token bucket for most APIs, because it is cheap, allows sensible bursts and is easy to explain. Sliding window counter when the rule is a strict "N per minute" with no bursts. In an interview, name two or three, say the trade-off, and pick one.

6. Enforcing It Across Many Servers

The naive version reads the count, checks it, and writes it back. With many servers this races: two servers both read 99, both allow, and the client gets 101. The read, the decision and the write must be one atomic step. In Redis that means a Lua script, which runs as a single unit with nothing in between (see the Redis lesson). The script below is a token bucket. It uses Redis's own clock (TIME), so servers with slightly different clocks cannot disagree, and it takes a cost so an expensive call can use more than one token.

-- KEYS[1] = bucket key; ARGV = capacity, refill per second, cost
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local d = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(d[1]) or capacity
local ts = tonumber(d[2]) or now
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate)
local allowed, wait_ms = 0, 0
if tokens >= cost then
  tokens = tokens - cost
  allowed = 1
else
  wait_ms = math.ceil((cost - tokens) / rate * 1000)
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
return {allowed, wait_ms}

The PEXPIRE is safe: after capacity / rate seconds with no requests the bucket would be full anyway, so deleting it changes nothing and frees memory. The gateway calls the script from a Spring interceptor:

@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate redis;
    private final DefaultRedisScript<List<Long>> script;   // the Lua script above
    private final RuleCache rules;                          // limits copied from the rules service

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        Rule rule = rules.forRequest(req);                  // plan, burst, perSecond, cost
        String key = "rl:" + rule.plan() + ":" + req.getHeader("X-Api-Key");
        try {
            List<Long> r = redis.execute(script, List.of(key),
                    String.valueOf(rule.burst()), String.valueOf(rule.perSecond()), String.valueOf(rule.cost()));
            if (r.get(0) == 1L) return true;
            res.setStatus(429);
            res.setHeader("Retry-After", String.valueOf((r.get(1) + 999) / 1000));
            return false;
        } catch (DataAccessException e) {
            return true;                                    // limiter down: fail open (see section 9)
        }
    }
}

7. Worked Example: A Photo-Resize API with Free and Pro Plans

Developers call POST /resize to shrink images. POST /resize/batch handles many images and costs 10 tokens. Two plans:

  • Free: bucket of 20, refill 1 per second (60 per minute on average).
  • Pro: bucket of 100, refill 10 per second (600 per minute on average).
  1. A free customer's app wakes up and sends 25 resize calls at once. The first 20 take the 20 tokens. The next 5 get 429 with Retry-After: 1.
  2. After 3 seconds the bucket has 3 tokens again, so 3 more calls pass. A steady 1 call per second is always fine.
  3. A free customer calls /resize/batch, cost 10. A full bucket pays 10 and has 10 left. A second batch right away passes too. A third needs 10 tokens and the bucket has 0, so it gets 429 with Retry-After: 10.
  4. The Pro customer has 10 times the refill and 5 times the burst, with the same code. Only the numbers in the rules service change.

Plans are just data. Adding a "Business" plan is a new row in the rules service, not a deploy.

8. Hot Keys and Many Regions

  • Hot key: one bucket lives on one Redis shard. A huge customer sending 20,000 requests per second hits one node. That still fits inside the 50,000 per second a node can do, but not much more. For bigger customers, let each gateway server take a lease of tokens, for example 100 at a time, from the central bucket and spend them locally. The central call happens once per 100 requests. The cost is accuracy: servers may hold unused tokens, so the limit can be off by up to the total of the leases.
  • Multiple regions: a single global Redis adds 50 to 150 ms across oceans, so it is out. Common choices: a separate limit per region (split the global limit by expected share, for example 60% and 40%), or regional counters that sync with each other every second or so. Both allow a small overshoot. Say that out loud in an interview, then say why it is acceptable.

9. When the Limiter Fails

The limiter sits on the path of every request, so it must not become the thing that takes the API down.

  • Short timeout: give the Redis call 5 to 10 ms. A slow limiter is worse than no limiter. Add a circuit breaker so that, after repeated failures, the gateway skips the call for a few seconds instead of waiting on each request (see the resilience lesson).
  • Fail open (allow all requests while the limiter is down) is the right default for a general API. A few minutes without limits is better than a full outage. This is what the interceptor above does.
  • Fail closed (reject) is right for endpoints where abuse is expensive or dangerous: login, password reset, sending SMS codes. A guessing attack during the outage is the risk.
  • Local fallback: a middle path. While Redis is down, each gateway server enforces the limit divided by the number of servers, in memory. It is rough but still stops the worst abuse.
  • State loss: if a Redis node fails over and loses recent writes, buckets come back fuller than they were. Clients get a short burst of extra requests. That is acceptable.

10. Choosing the Key, and Fairness

Key Good for Watch out for
API key or user ID Plans and fair use for logged-in clients One user can create many accounts
IP address Anonymous traffic and login pages Many real users share one IP (offices, mobile carriers); an attacker can use thousands of IPs
Key + route Different limits for cheap and expensive calls More keys to store
  • Layer the limits. A per-IP limit before login, a per-account limit after it, and a limit per route. A request must pass all of them, so check the cheapest and most likely to reject first.
  • Login is special. Limit attempts per account and per IP together, so one attacker cannot try one password on each of a million accounts, and a victim is not locked out by someone else's guesses (see the authentication lesson).
  • Key explosion. If the key is built from something an attacker controls, such as a random header, they can create millions of buckets and fill Redis. Always set a TTL and cap the key shape.
  • Roll out in shadow mode. Log what would have been rejected before enforcing a new rule. This finds rules that would break real customers.

11. Common Pitfalls

  • Read, then write, with no atomicity. Two servers both see room and both allow. Use one atomic script.
  • Using each server's clock. Clocks differ by milliseconds to seconds. Use the store's clock.
  • No TTL on keys. Memory grows forever, especially with IP-based keys.
  • Fail closed by default. A Redis blip becomes a full outage of the API.
  • Checking late. Parsing large bodies or running database queries before the check lets abusive traffic still use your resources.
  • One limit for every endpoint. A search call and a health check do not cost the same. Use a cost per route.
  • No Retry-After. Rejected clients retry immediately and add to the load.

12. Interview Questions

  1. Which algorithm would you use, and why? Token bucket for most APIs: two numbers per key, controlled bursts, easy to explain. Sliding window counter when the rule is a strict count per period. Fixed window is the simplest but allows double the limit at window edges.
  2. How do you enforce one limit across many servers? Keep the counts in a shared store such as Redis and make the check atomic with a Lua script. Local counters alone give each server its own limit.
  3. What if Redis goes down? Use a short timeout and a circuit breaker. Fail open for a general API, fail closed for login and other abuse-prone endpoints, or fall back to a rough local limit per server.
  4. How do you rate limit by IP when many users share one IP? Prefer the API key or user ID once the client is known. For anonymous traffic, use a higher IP limit, add a second signal such as a device token, and expect some unfairness. Group IPv6 addresses by prefix, since one user can have a whole range.
  5. How is rate limiting different from load shedding? Rate limiting applies a per-client rule to keep usage fair. Load shedding drops work when the whole service is overloaded, whoever sent it. A good system has both.
  6. How do you handle one huge customer on a single hot key? Give each gateway server a lease of tokens from the central bucket and spend them locally. Central calls drop by the lease size, and the limit becomes slightly less exact.
  7. How do you roll out or change a limit safely? Keep rules as data in a rules service, run the new rule in shadow mode first to see who would be rejected, then enforce it gradually and watch the rejection rate and customer support tickets.