What Rate Limiting Is Actually For
Rate limiting is the only thing between your database and a client running a while (true) loop. It bounds four distinct risks, and it is worth keeping them apart because the remedy for each is different:
- Abuse. A single authenticated customer can exhaust connection pool capacity and degrade every other tenant. In a multi-tenant system this is the failure that turns one customer's bad script into everyone's outage.
- Cost. Third-party APIs meter per call. An unbounded retry loop against a paid API is a line item that grows without a human approving it — Stripe documents this explicitly, warning that a single badly written integration can generate a bill large enough to bankrupt a small business.
- Fairness. One integrator's batch import should not occupy the worker pool that serves interactive traffic.
- Denial of service. Limits are a cheap, honest layer of defence that sits in front of anything expensive to scale.
Rate limiting is not an authorisation mechanism and it is not authentication. It is a resource governor. When you conflate the two, you end up with a limit set far too high to protect anything, because it was really being used for access control.
Choosing the Key: Who Gets a Bucket?
The algorithm matters far less than the key. Get the key wrong and the best implementation on earth still fails.
| Identity source | Good for | Watch out for |
|---|---|---|
| API key | Server-to-server, easy to reason about | One key shared by a whole customer org |
| OAuth client id | Per-integration quotas in a public API | Rotating refresh tokens creating new keys |
| User id | Fair-share for end-user apps | Login-as-many-users bypasses the limit |
| IP address | Anonymous and unauthenticated traffic | Carrier NAT lumps thousands of real users together |
| Tenant id | Internal APIs and background jobs | One noisy tenant starves its own workers |
The honest answer is a tiered scheme: a generous per-key limit, a per-account limit above it, and a much smaller per-IP limit for unauthenticated requests. Two limits of different scope catch different mistakes, and the pair of them is genuinely harder to game than either alone.
Fixed Window
Count requests in discrete intervals aligned to a boundary. A window identifier is derived from the current time, and a counter lives under that identifier until the window expires. It is the cheapest thing to build and, in a single-process app, entirely adequate.
typescriptexport function fixedWindow( now: number, limit: number, windowMs: number, ): { allowed: boolean; remaining: number; resetAt: number } { // Floor to the window boundary so every client agrees on when it resets. const windowStart = Math.floor(now / windowMs) * windowMs; const resetAt = windowStart + windowMs; const windowKey = "rl:fw:" + Math.floor(windowStart / windowMs); const used = counters.increment(windowKey, 1); counters.expireAt(windowKey, resetAt); return { allowed: used <= limit, remaining: Math.max(0, limit - used), resetAt, }; }
The known defect is the boundary burst: a client limited to 1,000 requests per hour can send 1,000 at 10:59:59 and another 1,000 at 11:00:00 — 2,000 requests in two seconds, twice the intended instantaneous ceiling.
The second defect is synchronised resets. Because the window comes from wall-clock time, every client's bucket resets at the same instant, and at the top of a minute you get a thundering herd whether or not anyone was actually rate limited.
Sliding Window
Keep a log of individual request timestamps and count only those inside the last N milliseconds. This eliminates the boundary burst, because there is no boundary.
lua-- KEYS[1] = sorted set of request timestamps -- ARGV[1] = now (ms) ARGV[2] = window (ms) ARGV[3] = limit ARGV[4] = req id redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', tonumber(ARGV[1]) - tonumber(ARGV[2])) local count = redis.call('ZCARD', KEYS[1]) if count >= tonumber(ARGV[3]) then local oldest = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES') local retry = math.ceil(tonumber(ARGV[2]) - (tonumber(ARGV[1]) - tonumber(oldest[2]))) return { 0, count, retry } end redis.call('ZADD', KEYS[1], tonumber(ARGV[1]), ARGV[4]) redis.call('PEXPIRE', KEYS[1], tonumber(ARGV[2])) return { 1, tonumber(ARGV[3]) - count - 1, 0 }
The cost is one sorted-set entry per request, plus a ZREMRANGEBYSCORE on every call. At 10,000 requests per second per key that is meaningful Redis work and memory churn for something a counter could do. Sliding window is a good default for interactive APIs at human traffic rates, and the wrong choice for a high-volume ingestion endpoint.
Token Bucket
Tokens accumulate at a steady rate up to a capacity ceiling, and each request spends one. This is the algorithm most public APIs should use, because it does the one thing clients actually need: it permits short bursts at full throughput while enforcing a hard long-run average.
lua-- KEYS[1] = bucket hash -- ARGV[1] now(ms) ARGV[2] capacity ARGV[3] refill/sec ARGV[4] cost ARGV[5] ttl(ms) local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts') local tokens = tonumber(state[1]) local ts = tonumber(state[2]) if tokens == nil then tokens = tonumber(ARGV[2]) ts = tonumber(ARGV[1]) end local elapsed = math.max(0, tonumber(ARGV[1]) - ts) tokens = math.min(tonumber(ARGV[2]), tokens + (elapsed / 1000) * tonumber(ARGV[3])) local allowed = 0 local retryAfter = 0 if tokens >= tonumber(ARGV[4]) then allowed = 1 tokens = tokens - tonumber(ARGV[4]) else retryAfter = math.ceil(((tonumber(ARGV[4]) - tokens) / tonumber(ARGV[3])) * 1000) end redis.call('HSET', KEYS[1], 'tokens', tostring(tokens), 'ts', ARGV[1]) redis.call('PEXPIRE', KEYS[1], tonumber(ARGV[5])) return { allowed, tostring(tokens), retryAfter }
Note the math.min clamp. Without it, a client that is quiet for a week accumulates a bucket of 604,800 tokens and then fires a week of traffic in one burst — the exact opposite of what you were trying to prevent. Capacity is your burst allowance; pick it deliberately. A capacity of 20 with a refill of 5/sec means "sustained 5 rps, bursts up to 20".
Leaky Bucket
Leaky bucket is the odd one out: it does not reject, it queues. Incoming work enters a buffer drained at a strictly constant rate, which is the right model when your downstream is something rate-limited in turn — a partner API, a print device, an SMS gateway. Combined with a bounded queue it becomes real backpressure. Alone with an unbounded queue it is a memory-exhaustion attack with extra steps.
Headers: RateLimit-* and Retry-After
When you reject a request, RFC 6585 section 4 specifies the response: 429 Too Many Requests. That status was added in 2012 precisely because servers had no standard way to say "you are throttled, not broken".
The Retry-After field is defined in RFC 9110 and documented for browsers on MDN. The semantics matter and are commonly got wrong:
- If the value is an integer, it is a number of seconds to wait.
- If the value is an HTTP-date, it is an absolute time at which the client may retry.
- The field may appear on a 429 and also on any 3xx redirect or 503 response, where it tells an intermediary how long to wait before following the redirect or retrying the origin.
Sending a bare Unix timestamp — which many implementations do by copying the X-RateLimit-Reset idea — is a bug. Clients will parse it as "wait until 1970 plus that number of seconds" and retry immediately, forever.
The newer RateLimit header family from the IETF HTTPAPI working group supersedes the older X-RateLimit-* convention:
httpHTTP/1.1 429 Too Many Requests Content-Type: application/problem+json RateLimit: limit=100, remaining=0, reset=17 RateLimit-Policy: 100;w=60 Retry-After: 17
RateLimit-Policy tells the client the policy (limit=100;w=60 is 100 requests per 60 seconds), while RateLimit reports the current state. reset is the number of seconds until the counter resets, not a timestamp — which is precisely the ambiguity that made X-RateLimit-Reset so badly implemented in the wild.
typescriptres.setHeader("RateLimit", "limit=" + limit + ", remaining=" + remaining + ", reset=" + resetSeconds); res.setHeader("RateLimit-Policy", limit + ";w=" + windowSeconds); res.setHeader("Retry-After", String(retryAfterSeconds));
Distributed Limits Need a Shared Store
The moment you run more than one application instance, an in-process counter is wrong. Two instances behind a load balancer each allow 100 requests, so your effective limit is 200, and it drifts with autoscaling. The store has to be shared, and the read-modify-write has to be atomic — the classic implementation is GET then SET, which under concurrency loses increments and lets clients exceed the limit exactly when everyone is hammering.
Redis is the usual answer: INCR plus EXPIRE for fixed window, and Lua scripts (as above) for everything more interesting, because a script runs atomically inside Redis. Two engineering rules that matter more than the choice:
- Fail open or fail closed, deliberately. If Redis is unreachable, does every API call succeed? Fail-open preserves availability and risks cost; fail-closed preserves your budget and turns a Redis blip into a total outage. Pick per endpoint. Payment webhooks: fail closed. Browsing for a logged-in user: fail open, with a local fallback limiter.
- Never let the limiter become the bottleneck. It sits in front of everything, so it needs its own timeout (single-digit milliseconds), its own connection pool, and an alert on p99. A rate limiter that adds 40ms to every request has reduced throughput more than any limit would have.
typescriptimport { Redis } from "ioredis"; const redis = new Redis(process.env.REDIS_URL!, { maxRetriesPerRequest: 1, enableOfflineQueue: false, // fail fast rather than queueing behind a dead node commandTimeout: 5, // milliseconds — this is on the hot path }); export async function tokenBucket(key: string, cost = 1) { const raw = (await redis.eval(TOKEN_BUCKET_LUA, 1, key, Date.now(), CAPACITY, REFILL_PER_SEC, cost, TTL_MS)) as [number, string, number]; return { allowed: raw[0] === 1, remaining: Math.floor(Number(raw[1])), retryAfterMs: raw[2] }; }
The 429 Cascade
The failure mode that catches teams out is not a limit being too tight. It is a limit being enforced correctly while the client ignores Retry-After and retries instantly. What follows is a self-amplifying loop:
- A brief spike — a partner retries, a deploy doubles traffic — pushes one tenant past its limit.
- That client receives 429s and retries immediately, with zero delay.
- Each retry consumes capacity on your edge, your application and Redis. The rejected requests are as expensive as accepted ones.
- Your own latency rises, so more requests time out, so more clients retry.
- Other tenants, who were within their limits, now receive 429s too. The limit that was protecting them has become the mechanism that hurts them.
Traffic graphs in this state have a distinctive shape: request volume rising while success rate falls, with p99 climbing. If your dashboard shows "429s up" but total RPS also up, you are in a retry storm, not a load problem.
Two defences, both client-side, both mandatory:
typescriptfunction backoffDelay(attempt: number, retryAfterSeconds: number): number { // Always honour a server-provided Retry-After — it beats local maths. if (retryAfterSeconds > 0) return retryAfterSeconds * 1000; const ceiling = Math.min(60_000, 500 * Math.pow(2, attempt)); // Full jitter: uniform in [0, ceiling]. Uniform backoff synchronises // every client onto the same retry instant and re-creates the herd. return Math.floor(Math.random() * ceiling); } async function callWithRetry(fn: () => Promise<Response>) { for (let attempt = 0; attempt <= 5; attempt++) { const res = await fn(); if (res.status !== 429 && res.status < 500) return res; if (attempt === 5) return res; const retryAfter = Number(res.headers.get("Retry-After") ?? 0); const delay = backoffDelay(attempt, Number.isFinite(retryAfter) ? retryAfter : 0); await new Promise((r) => setTimeout(r, delay)); } }
The ceiling clamp matters as much as the jitter. Unbounded exponential backoff can produce a five-minute wait after six failures, which looks to the user like the integration is broken. Cap it, and count consecutive 429s separately from 5xx so a genuinely broken dependency does not silently consume your entire retry budget.
On the server side, the complementary move is to return 429 early — at the edge, from a local filter — so a throttled request never reaches the database at all. Rejections are the cheapest possible outcome; letting them travel four hops first makes them the second most expensive thing you do.
Sensible Defaults
Starting points, to be tuned against real traffic rather than vibes:
| Tier | Algorithm | Sustained | Burst | Scope |
|---|---|---|---|---|
| Public anonymous | Fixed window | 60/min | — | IP |
| Authenticated user | Token bucket | 10/s | 40 | User id |
| Partner API key | Token bucket | 100/s | 200 | API key |
| Enterprise account | Token bucket | 1,000/s | 2,000 | Account id |
| Expensive read (report, export) | Token bucket | 2/min | 5 | User id |
| Webhook ingest | Leaky bucket, queue 10k | 500/s | queue | Tenant id |
The last two rows are the ones people forget. Not every call should have the same rate: a report endpoint that runs a 4-second query needs a budget an order of magnitude below a status ping, or one heavy consumer will hold your connection pool hostage.
If you want the surrounding API design rather than just the limiter, how to structure a REST API covers versioning, pagination and error shapes that a rate limiter has to fit inside. Running limits across several services or a whole tenant estate is an infrastructure problem — our cloud and DevOps practice covers where the store lives and how it fails. For the tenant-aware keying above, the multi-tenant architecture guide goes into how you get a trustworthy tenant identity in the first place.