Bound the request rate each caller (API key, tenant, IP or user) can impose on a shared system. Short bursts are allowed, sustained rates are capped, and rejected callers are told exactly when to come back. One noisy client then cannot degrade service for everyone else.
Rate limiting caps how much work one caller can make you do in a period of time. It sounds like a single counter. In practice you have to answer three separate questions. Which algorithm decides allow or deny? Where in the request path does each limit live? What do you tell the caller when you say no? This guide follows one invented incident at Ledgerline, a public accounting API. A per-pod fixed-window counter let one runaway integration flatten the database for every tenant. You will rebuild its limits with a shared token bucket at the gateway and a sliding window on an expensive endpoint, and design 429 responses that well-behaved clients can act on. The same structure works when an interviewer says "design a rate limiter" or "protect this API from abusive clients".
The problem
A situation where the obvious design starts to hurt.
Ledgerline serves a REST API to 3,200 tenants and their partner integrations. Peak traffic is about 14,000 requests per second, spread across 40 stateless gateway pods in front of an invoices service and a reports service. Both services share a Postgres cluster with a 400-connection pool.
The only protection was an in-memory fixed-window counter in each gateway pod: 1,200 requests per minute per API key. It had two flaws. First, every pod counted on its own, and the load balancer spread one key's traffic over all 40 pods, so the real limit was about 48,000 requests per minute per key. Second, a fixed window resets at the minute boundary. A client could send 1,200 requests at 12:00:59 and another 1,200 at 12:01:00, which is twice the intended rate within two seconds.
Then a partner's bookkeeping sync tool hit a bug. It retried a failing invoice call in a tight loop and sent roughly 9,000 requests per second from a single API key for 22 minutes. Almost none of it was rejected. The Postgres pool saturated, and p99 latency for every tenant went from 140 ms to 9 seconds. Separately, one tenant's script triggered 60 report exports in a minute. Each export is a 30-second analytical query, and the reports replica pinned at 100% CPU.
The postmortem found three gaps. The limit was not shared across pods. The algorithm allowed boundary bursts. And every endpoint got the same budget, so a cheap GET and a 30-second export cost the same. It also noted that the few 429s that did fire had no Retry-After header. The sync tool could not have backed off correctly even if it had tried.
The solution
What the pattern proposes.
Split the protection into layers, and match each layer's algorithm to what it protects.
At the edge (CDN or WAF), enforce a coarse per-IP limit of 300 requests per second, plus stricter limits on unauthenticated routes such as login and token exchange. This layer has no idea who the tenant is. Its job is to stop floods before they cost you a TLS handshake at the gateway.
At the API gateway, enforce the main per-API-key quota with a token bucket stored in Redis. Each key has a bucket with a capacity, for example 100 tokens on the Standard plan, and a refill rate, for example 20 tokens per second. A request takes one token. If the bucket is empty, the request is rejected. The sustained rate is capped at 20 requests per second (1,200 per minute), and an integration that wakes up and fires 100 calls at once is still allowed through. All 40 pods share the bucket. A single Lua script reads, refills and decrements it atomically, and it uses Redis server time, so pods with skewed clocks cannot disagree about how many tokens exist.
Inside the reports service, enforce a sliding window: 20 exports per tenant in any rolling 60 minutes. Exports are rare and expensive, so the exact sliding log (a sorted set of timestamps, at most 20 entries per tenant) is cheap and has no boundary burst. A token bucket would also work here, but a rolling count is easier to explain to customers in the docs.
Every rejection returns 429 Too Many Requests with these parts:
- A Retry-After header computed from the actual refill time, not a constant. - RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers (an IETF draft that many APIs follow) on every response, so clients can slow down before they hit zero. - A problem+json body naming which limit was hit.
Keep 429 separate from 503. A 429 means the caller exceeded its quota. A 503 means Ledgerline itself is overloaded and is shedding load.
An everyday analogy
The same idea, outside software.
Think of a self-service car wash that sells tokens through a machine that drips one new token into your tray every three seconds, up to a tray of ten. If you have been away for a while, you can run ten quick washes back to back. After that, you get one wash every three seconds no matter how hard you push the button. Everyone drawing from the same tray gets the same budget, however many wash bays they spread across.
The sliding window is the deep-clean bay next door. It has a sign that says no more than 20 deep cleans per customer in any rolling hour. The attendant keeps the times of your last 20 visits and tells you exactly when the oldest one ages out.
Structure
The pieces and how they relate.
Participants
- Edge / WAF
- Applies coarse per-IP limits before authentication. It cheaply drops floods and credential-stuffing on login routes. It cannot see tenants, so it must stay generous enough that a whole office behind one NAT address is not blocked.
- API gateway
- Authenticates the API key, looks up the plan's capacity and refill rate, asks Redis to take tokens, and either forwards the request or answers 429. It adds RateLimit-* headers to every response. It is the single place where per-key quota is enforced.
- Redis limiter
- Holds one small hash per API key (tokens, last refill timestamp) and runs the token bucket as an atomic Lua script using server time. Keys expire once a bucket would be full again, so idle tenants cost no memory.
- Plan limits store
- Source of truth for capacity and refill per plan and per-key overrides, for example a partner granted 500 tokens at 100 per second. Gateways cache it for 60 seconds so limit changes propagate within a minute without a lookup per request.
- Reports service
- Enforces the endpoint-specific sliding window on exports, because only it knows that an export is a 30-second query. It records accepted exports in a Redis sorted set per tenant and rejects the 21st inside any rolling hour.
- API client
- Is expected to read RateLimit-Remaining, honour Retry-After, and add jitter to retries. The 429 contract only works if documented SDKs actually do this.
Pseudocode
The solution to the scenario, language-neutral.
// Token bucket (gateway, per API key). Runs atomically inside Redis.
function take(key, capacity, refillPerSec, cost):
now = redisServerTimeMs()
(tokens, ts) = HMGET key tokens ts
if missing: tokens = capacity; ts = now
tokens = min(capacity, tokens + (now - ts) * refillPerSec / 1000)
if tokens >= cost:
tokens = tokens - cost
allowed = true; retryMs = 0
else:
allowed = false
retryMs = ceil((cost - tokens) * 1000 / refillPerSec)
HSET key tokens tokens ts now
PEXPIRE key ceil(capacity * 1000 / refillPerSec) + 1000
return (allowed, floor(tokens), retryMs)
// Sliding log (reports service, per tenant). Exact, fine for small limits.
function allowExport(tenant, limit = 20, windowMs = 3600000):
key = "exports:" + tenant
now = redisServerTimeMs()
ZREMRANGEBYSCORE key 0 (now - windowMs)
if ZCARD key >= limit:
oldest = ZRANGE key 0 0 WITHSCORES
return deny(retryMs = oldest.score + windowMs - now)
ZADD key now uniqueId() // only accepted requests are recorded
PEXPIRE key windowMs
return allow()
// Sliding window counter (cheaper variant for high limits).
// Two fixed buckets weighted by overlap with the rolling window.
estimate = previousWindowCount * (1 - elapsedInCurrent / windowMs) + currentWindowCount
allow if estimate < limit
// Gateway request handling
function handle(request):
key = authenticate(request)
limit = planLimits.cached(key)
decision = take("rl:" + key, limit.capacity, limit.refillPerSec, costOf(request.route))
if decision.degraded: metrics.increment("ratelimit.fail_open")
if not decision.allowed:
return 429 with
Retry-After: max(1, ceil(decision.retryMs / 1000))
RateLimit-Limit, RateLimit-Remaining: 0, RateLimit-Reset
body: { title: "Too Many Requests", limit: "api-key", retry_after_ms }
response = forward(request)
add RateLimit-* headers to response
return responseThe code
The same solution in TypeScript, Python and PHP.
import Redis from "ioredis";
// Atomic token bucket. Uses Redis server time so 40 gateway pods never disagree about "now".
// Requires Redis 7 (effects replication by default, so TIME before writes is allowed).
const TAKE_LUA = `
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local state = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(state[1])
local ts = tonumber(state[2])
if tokens == nil or ts == nil then
tokens = capacity
ts = now
end
tokens = math.min(capacity, tokens + math.max(0, now - ts) * refill / 1000)
local allowed = 0
local retry_ms = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry_ms = math.ceil((cost - tokens) * 1000 / refill)
end
redis.call('HSET', key, 'tokens', tostring(tokens), 'ts', now)
redis.call('PEXPIRE', key, math.ceil(capacity * 1000 / refill) + 1000)
return {allowed, tostring(tokens), retry_ms}
`;
export interface Limit {
capacity: number; // max burst, e.g. 100
refillPerSec: number; // sustained rate, e.g. 20
}
export interface Decision {
allowed: boolean;
limit: number;
remaining: number;
retryAfterMs: number;
degraded: boolean; // true when Redis was unreachable and we failed open
}
type TakeFn = (key: string, capacity: number, refill: number, cost: number) => Promise<[number, string, number]>;
export class TokenBucketLimiter {
private readonly takeTokens: TakeFn;
// Construct the client with a tight timeout, e.g. new Redis({ commandTimeout: 50 }).
constructor(redis: Redis) {
// defineCommand sends EVALSHA and falls back to EVAL on NOSCRIPT.
redis.defineCommand("takeTokens", { numberOfKeys: 1, lua: TAKE_LUA });
const withCommand = redis as unknown as { takeTokens: TakeFn };
this.takeTokens = withCommand.takeTokens.bind(redis);
}
async take(apiKey: string, limit: Limit, cost = 1): Promise<Decision> {
if (cost > limit.capacity) {
throw new RangeError("cost exceeds bucket capacity; request could never succeed");
}
try {
const [allowed, tokens, retryMs] = await this.takeTokens(
`rl:${apiKey}`,
limit.capacity,
limit.refillPerSec,
cost,
);
return {
allowed: allowed === 1,
limit: limit.capacity,
remaining: Math.floor(Number(tokens)),
retryAfterMs: retryMs,
degraded: false,
};
} catch {
// Fail open: a limiter outage must not become an API outage. The caller emits a metric.
return { allowed: true, limit: limit.capacity, remaining: limit.capacity, retryAfterMs: 0, degraded: true };
}
}
}
export function limitHeaders(d: Decision, limit: Limit): Record<string, string> {
const secondsUntilFull = Math.ceil((limit.capacity - d.remaining) / limit.refillPerSec);
return {
"RateLimit-Limit": String(limit.capacity),
"RateLimit-Remaining": String(d.remaining),
"RateLimit-Reset": String(secondsUntilFull),
};
}
export function tooManyRequests(d: Decision, limit: Limit) {
const retryAfterSec = Math.max(1, Math.ceil(d.retryAfterMs / 1000));
return {
status: 429,
headers: {
...limitHeaders(d, limit),
"Retry-After": String(retryAfterSec),
"Content-Type": "application/problem+json",
},
body: {
title: "Too Many Requests",
status: 429,
detail: `API key limit is ${limit.refillPerSec} requests/s with bursts of ${limit.capacity}.`,
limit: "api-key",
retry_after_ms: d.retryAfterMs,
},
};
}import math
from dataclasses import dataclass
import redis
# Atomic token bucket. Uses Redis server time so 40 gateway pods never disagree about "now".
# Requires Redis 7 (effects replication by default, so TIME before writes is allowed).
TAKE_LUA = """
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local state = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(state[1])
local ts = tonumber(state[2])
if tokens == nil or ts == nil then
tokens = capacity
ts = now
end
tokens = math.min(capacity, tokens + math.max(0, now - ts) * refill / 1000)
local allowed = 0
local retry_ms = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry_ms = math.ceil((cost - tokens) * 1000 / refill)
end
redis.call('HSET', key, 'tokens', tostring(tokens), 'ts', now)
redis.call('PEXPIRE', key, math.ceil(capacity * 1000 / refill) + 1000)
return {allowed, tostring(tokens), retry_ms}
"""
@dataclass(frozen=True)
class Limit:
capacity: int # max burst, e.g. 100
refill_per_sec: float # sustained rate, e.g. 20
@dataclass(frozen=True)
class Decision:
allowed: bool
limit: int
remaining: int
retry_after_ms: int
degraded: bool # True when Redis was unreachable and we failed open
class TokenBucketLimiter:
# Build the client with tight timeouts, e.g.
# redis.Redis(host=..., socket_timeout=0.05, socket_connect_timeout=0.05)
def __init__(self, client: redis.Redis) -> None:
# register_script sends EVALSHA and reloads the script on NOSCRIPT.
self._take = client.register_script(TAKE_LUA)
def take(self, api_key: str, limit: Limit, cost: int = 1) -> Decision:
if cost > limit.capacity:
raise ValueError("cost exceeds bucket capacity; request could never succeed")
try:
allowed, tokens, retry_ms = self._take(
keys=[f"rl:{api_key}"],
args=[limit.capacity, limit.refill_per_sec, cost],
)
except redis.RedisError:
# Fail open: a limiter outage must not become an API outage. The caller emits a metric.
return Decision(True, limit.capacity, limit.capacity, 0, True)
return Decision(
allowed=allowed == 1,
limit=limit.capacity,
remaining=int(float(tokens)),
retry_after_ms=int(retry_ms),
degraded=False,
)
def limit_headers(d: Decision, limit: Limit) -> dict[str, str]:
seconds_until_full = math.ceil((limit.capacity - d.remaining) / limit.refill_per_sec)
return {
"RateLimit-Limit": str(limit.capacity),
"RateLimit-Remaining": str(d.remaining),
"RateLimit-Reset": str(seconds_until_full),
}
def too_many_requests(d: Decision, limit: Limit) -> tuple[int, dict[str, str], dict]:
retry_after_sec = max(1, math.ceil(d.retry_after_ms / 1000))
headers = {
**limit_headers(d, limit),
"Retry-After": str(retry_after_sec),
"Content-Type": "application/problem+json",
}
body = {
"title": "Too Many Requests",
"status": 429,
"detail": f"API key limit is {limit.refill_per_sec:g} requests/s with bursts of {limit.capacity}.",
"limit": "api-key",
"retry_after_ms": d.retry_after_ms,
}
return 429, headers, body<?php
declare(strict_types=1);
final class Limit
{
public function __construct(
public readonly int $capacity, // max burst, e.g. 100
public readonly float $refillPerSec // sustained rate, e.g. 20
) {}
}
final class Decision
{
public function __construct(
public readonly bool $allowed,
public readonly int $limit,
public readonly int $remaining,
public readonly int $retryAfterMs,
public readonly bool $degraded // true when Redis was unreachable and we failed open
) {}
}
final class TokenBucketLimiter
{
// Atomic token bucket. Uses Redis server time so 40 gateway pods never disagree about "now".
// Requires Redis 7 (effects replication by default, so TIME before writes is allowed).
private const LUA = <<<'LUA'
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
local state = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(state[1])
local ts = tonumber(state[2])
if tokens == nil or ts == nil then
tokens = capacity
ts = now
end
tokens = math.min(capacity, tokens + math.max(0, now - ts) * refill / 1000)
local allowed = 0
local retry_ms = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
retry_ms = math.ceil((cost - tokens) * 1000 / refill)
end
redis.call('HSET', key, 'tokens', tostring(tokens), 'ts', now)
redis.call('PEXPIRE', key, math.ceil(capacity * 1000 / refill) + 1000)
return {allowed, tostring(tokens), retry_ms}
LUA;
private readonly string $sha;
// Connect with tight timeouts, e.g. $redis->connect($host, 6379, 0.05)
// and $redis->setOption(Redis::OPT_READ_TIMEOUT, 0.05).
public function __construct(private readonly \Redis $redis)
{
$this->sha = sha1(self::LUA);
}
public function take(string $apiKey, Limit $limit, int $cost = 1): Decision
{
if ($cost > $limit->capacity) {
throw new \InvalidArgumentException('cost exceeds bucket capacity; request could never succeed');
}
$args = ["rl:{$apiKey}", (string) $limit->capacity, (string) $limit->refillPerSec, (string) $cost];
try {
$result = $this->redis->evalSha($this->sha, $args, 1);
if ($result === false) {
// NOSCRIPT after a Redis restart: load the script with EVAL once.
$this->redis->clearLastError();
$result = $this->redis->eval(self::LUA, $args, 1);
}
if (!is_array($result)) {
throw new \RedisException((string) $this->redis->getLastError());
}
} catch (\RedisException) {
// Fail open: a limiter outage must not become an API outage. The caller emits a metric.
return new Decision(true, $limit->capacity, $limit->capacity, 0, true);
}
[$allowed, $tokens, $retryMs] = $result;
return new Decision(
(int) $allowed === 1,
$limit->capacity,
(int) floor((float) $tokens),
(int) $retryMs,
false
);
}
}
/** @return array<string, string> */
function limitHeaders(Decision $d, Limit $limit): array
{
$secondsUntilFull = (int) ceil(($limit->capacity - $d->remaining) / $limit->refillPerSec);
return [
'RateLimit-Limit' => (string) $limit->capacity,
'RateLimit-Remaining' => (string) $d->remaining,
'RateLimit-Reset' => (string) $secondsUntilFull,
];
}
/** @return array{0: int, 1: array<string, string>, 2: array<string, mixed>} */
function tooManyRequests(Decision $d, Limit $limit): array
{
$retryAfterSec = max(1, (int) ceil($d->retryAfterMs / 1000));
$headers = limitHeaders($d, $limit) + [
'Retry-After' => (string) $retryAfterSec,
'Content-Type' => 'application/problem+json',
];
$body = [
'title' => 'Too Many Requests',
'status' => 429,
'detail' => sprintf(
'API key limit is %s requests/s with bursts of %d.',
rtrim(rtrim(number_format($limit->refillPerSec, 2, '.', ''), '0'), '.'),
$limit->capacity
),
'limit' => 'api-key',
'retry_after_ms' => $d->retryAfterMs,
];
return [429, $headers, $body];
}When to use it
Situations where it pays off.
A multi-tenant API where one tenant's bug or script can consume a shared resource such as a database pool, a replica's CPU or a third-party quota.
Per-key limits turn a global outage into a local one. At Ledgerline, a 20 req/s bucket would have rejected about 99.8% of the sync tool's 9,000 req/s loop, and other tenants' p99 latency would have stayed where it was.
Traffic that is naturally bursty but has a meaningful sustained ceiling, such as integrations that sync on a schedule or mobile apps that fetch several resources on launch.
A token bucket separates burst size (capacity) from sustained rate (refill), so you can allow a 100-request startup burst without allowing 100 requests every second.
Expensive endpoints whose cost is far above an average request, such as exports, bulk imports or search across years of data.
A separate, smaller limit per endpoint, enforced in the service that knows the cost, stops one rare-but-heavy operation from hiding inside a generous general quota.
You sell plans with documented quotas, or you call an upstream provider that enforces its own quota on you.
Explicit limits with RateLimit headers make the contract visible. Outbound, the same bucket keeps you under the provider's limit instead of discovering it through their 429s.
How to implement it
Steps to introduce it in existing code.
Pick the identity you limit on at each layer: client IP at the edge (unauthenticated), API key or tenant at the gateway, tenant plus endpoint in the service. Write each down with its number and the resource it protects.
Size the gateway bucket from what the backend can absorb. If Postgres handles about 25,000 queries per second and a typical call does 2 queries, no single key should be able to take more than a small fraction of that. Then pick capacity from the real burst pattern of good clients.
Store bucket state in a shared store (Redis) and update it in one atomic script using server time. A read-then-write from the gateway lets two pods both spend the last token.
Give expensive routes a cost greater than 1 or their own limiter. Reject costs larger than the capacity at configuration time, because such a request could never succeed.
Decide the outage behaviour explicitly. Give the Redis call a tight timeout (about 50 ms). If it times out, fail open with a metric and a coarse per-pod in-memory cap as a backstop.
Return 429 with Retry-After computed from the bucket's refill time, RateLimit-* headers on every response, and a problem+json body. Document that clients must honour Retry-After with jitter, and make your own SDKs do it.
Dashboard 429s by key and route, alert on fail-open events, and review the top rejected keys weekly. A key that is constantly limited is either a bug to report to the partner or a customer who needs a bigger plan.
Pros and cons
What you gain and what you pay.
Pros
- Isolates tenants: a runaway client exhausts its own bucket, not the shared database pool.
- Token buckets allow realistic bursts while still enforcing a hard sustained rate, with two numbers that are easy to reason about.
- A shared Redis bucket makes the documented limit the real limit, regardless of how many gateway pods you run.
- Good 429s with Retry-After turn rejections into scheduled retries instead of retry storms.
- Layered limits put each check where it is cheapest and best informed: IP at the edge, quota at the gateway, cost in the service.
Cons
- Adds a network round trip to Redis on every request and makes Redis part of the hot path, with an availability decision you must make.
- Limits are a guess about capacity. Set them too low and you reject paying customers, too high and they protect nothing. They need monitoring and revision.
- Per-key limits do not protect against many keys spiking at once. You still need load shedding (503) and backpressure for aggregate overload.
- Exact sliding logs cost memory proportional to the limit, so they do not scale to limits of thousands per window per key.
Trade-offs
Decisions you'll have to make, each with its price.
Shared Redis bucket vs per-pod in-memory buckets
You gainShared state makes the documented limit exact across all 40 pods and survives autoscaling. Per-pod buckets cost no network hop.
You payOne extra round trip per request (sub-millisecond in the same zone) and a dependency on Redis. Per-pod buckets must divide the limit by pod count and drift whenever the pod count or load balancing changes.
Fail open vs fail closed when Redis is unreachable
You gainFailing open keeps the API up during a limiter outage. Failing closed guarantees no tenant can flood Postgres.
You payFailing open removes protection exactly when something is already wrong, so keep a coarse per-pod cap as a backstop. Failing closed turns a Redis blip into a full outage for 3,200 tenants.
Bucket capacity 100 vs 500 at the same 20 tokens/s refill
You gainA larger capacity tolerates bigger sync bursts from legitimate integrations without 429s.
You payA larger burst lands on Postgres all at once. 500 instantaneous requests from each of a few keys can briefly saturate the 400-connection pool even though sustained rates are fine.
Exact sliding log vs sliding window counter for exports
You gainThe log is exact and gives a precise Retry-After from the oldest timestamp. The counter needs only two integers per tenant.
You payThe log stores one sorted-set entry per accepted request, which is fine at 20 per hour and wasteful at 10,000 per hour. The counter can admit slightly more or fewer than the limit near window boundaries.
Limiting at the edge vs at the gateway
You gainEdge limits drop floods before they cost TLS and authentication work. Gateway limits know the tenant and plan.
You payEdge limits keyed on IP misfire behind corporate NAT and mobile carrier gateways, so they must stay coarse. Gateway limits are reached only after connection and auth costs are paid.
How it fails
What goes wrong in production and how to prevent it.
Redis primary fails over and the limiter returns errors for 10 to 20 seconds.
What to doSet a 50 ms command timeout and fail open with a degraded flag. Alert on the fail-open rate. Keep a per-pod in-memory cap of the plan rate divided by the pod count as a backstop, so a runaway key is still roughly bounded while Redis recovers.
Clients ignore Retry-After and retry immediately, so rejected traffic stays at 9,000 req/s.
What to doRejections are cheap (one Redis script, no backend work), but still escalate: after a key is rejected continuously for 5 minutes, push a temporary block for that key to the edge and notify the partner. Make the official SDKs honour Retry-After with full jitter.
Many tenants retry at the same moment after a shared Retry-After and create synchronized spikes.
What to doCompute Retry-After per key from that bucket's actual refill time rather than a constant. Document that clients should add random jitter of up to the Retry-After value.
Pods with skewed clocks compute different refill amounts, letting a key overspend or wrongly rejecting it.
What to doTake time from Redis TIME inside the Lua script so every decision uses one clock, and never pass the gateway's local time as an argument.
A plan upgrade is not reflected, and a customer who just paid for 100 req/s keeps hitting 20 req/s.
What to doCache plan limits for 60 seconds at most, invalidate the cache on plan-change events, and make RateLimit-Limit visible so support can confirm what the gateway is enforcing.
Per-key limits all pass, but 3,000 keys spike together and Postgres still saturates.
What to doRate limiting is not overload protection. Add a concurrency bulkhead on the database pool and shed excess with 503 plus Retry-After when queue wait exceeds about 200 ms, separate from per-key 429s.
In a system design interview
When to bring it up and how to explain it.
Bring it up when the design has a public or multi-tenant API, when the interviewer asks how you stop one client from hurting others, or when a downstream (database, third-party API) has a hard capacity you must stay under. Say it early in the API layer discussion, not as an afterthought.
What you could say
I'd put limits at three layers. At the edge, a coarse per-IP limit around 300 requests per second, mainly to stop floods and protect login. At the gateway, the real quota: a token bucket per API key in Redis, say capacity 100 and refill 20 per second. That allows startup bursts and caps the sustained rate at 1,200 a minute. The bucket is updated in one Lua script using Redis server time, so all gateway pods share one exact limit, and a rejection doesn't consume tokens. Expensive operations get their own limit in the service that owns them, for example a sliding window of 20 exports per tenant per rolling hour. On rejection I return 429 with a Retry-After computed from the refill time, RateLimit headers on every response so clients can slow down early, and a problem body that says which limit was hit. I'd keep 429 for the client's quota and 503 for our own overload. If Redis is down, I fail open with a tight timeout, a metric and a per-pod fallback cap, because a limiter outage shouldn't become an API outage.
Likely follow-ups
Why not just use a fixed window counter per minute?
Boundary bursts. A client can spend the full minute's quota at the end of one window and again at the start of the next, so it gets double the rate within seconds. A token bucket or sliding window counter removes that with similar cost.
How does this scale if Redis becomes the bottleneck?
Each key's state is independent, so shard by key with Redis Cluster. The script touches one key, so it stays atomic on one shard. At 14,000 requests per second it is one small script per request, well within a modest cluster. Only past that would I consider local token leasing, where a pod takes a batch of 10 tokens at a time and accepts slight overspend.
How would you limit your own calls to a third-party API that allows 50 requests per second?
Same token bucket, keyed on the provider, with refill set a bit under their limit, around 45. Callers wait or queue for a token instead of getting a 429. I'd treat the provider's own 429s as a signal to back off using their Retry-After, not as errors for the circuit breaker.
What should the client do when it receives a 429?
Stop sending on that key until Retry-After passes, add random jitter so it doesn't sync with other clients, and use RateLimit-Remaining to pace itself before it hits zero. Retries of non-idempotent writes should carry an idempotency key, so a retry after an ambiguous failure can't double-apply.
Relations with other guides
Patterns it's often confused or combined with.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Rate limiting is only half the conversation. Clients must answer a 429 by waiting for Retry-After plus jitter, or rejected requests come straight back and keep the limiter busy.
- Backpressure: Let Slow Consumers Slow Down Fast Producers
Rate limiting caps each caller by a fixed quota. Backpressure reacts to the system's actual load. Ledgerline uses limits for fairness and 503-based shedding for aggregate overload.
- Bulkhead: Isolate Resources So One Failure Stays Contained
A bulkhead caps concurrency per resource, so even admitted traffic cannot take all 400 database connections. It complements rate limits, which cap arrival rate per caller.
- Queue-Based Load Leveling: Absorbing a Refund Burst
Accepted exports go onto a queue so their 30-second queries run at a steady pace. The sliding window limits how many enter, and the queue smooths when they run.
- Circuit breaker: fail fast when a dependency is down
When calling an upstream that rate limits you, count its 429s separately from failures. They mean slow down, not that the dependency is broken, so they should not trip the breaker.
- Proxy Pattern: Control Access with a Stand-In Object
The gateway acts as a protection proxy in front of the services: same interface to the client, with access control and quota checks added before forwarding.
Common questions
Short answers to the usual doubts.
Token bucket or sliding window: which should I default to?
Use a token bucket for general per-client quotas. It needs constant memory per key (two numbers), allows controlled bursts, and gives a precise retry time. Use a sliding window when the limit is naturally phrased as N per rolling period, the numbers are small (an exact log of 20 timestamps is cheap), or you must guarantee no more than N events in any window, for example to match a contract with an upstream provider.
What is wrong with a fixed window counter?
It resets at boundaries. A client allowed 1,200 per minute can send 1,200 at 12:00:59 and 1,200 more at 12:01:00, which is double the rate in two seconds. The sliding window counter fixes most of this by weighting the previous window's count by how much of it still overlaps the rolling window, at the cost of being an estimate rather than exact.
Should rejected requests consume tokens or window slots?
No. In the token bucket, a rejection leaves the tokens untouched. In the sliding log, only accepted requests are added. If rejections counted, a client that keeps retrying would never see its window drain and would stay locked out long after it slowed down.
How do I rate limit when one request is much more expensive than another?
Give routes a cost in tokens (a bulk import might cost 10) or put a separate limiter in the service that owns the expensive operation. At Ledgerline the reports service owns the export limit because only it knows an export is a 30-second query, and the gateway should not need that knowledge.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- APIs and HTTPTake the test
- Rate limiter (sliding window)Solve the exercise
- Massive traffic spikes: live votingSolve the exercise