Designing a Rate Limiter
Difficulty: Beginner-Intermediate · Prerequisites: Caching and Message Queues
TL;DR
A rate limiter blocks users who send too many requests. It protects your servers from being overwhelmed.
flowchart LR
CLIENT["Client"]
EDGE["Edge<br/>IP blocking"]
GW["API Gateway<br/>per-user limits"]
RL["Rate Limiter<br/>checks Redis"]
REDIS[("Redis<br/>counters")]
API["Your API"]
CLIENT -->|"1. Incoming request"| EDGE
EDGE -->|"2. IP check pass"| GW
GW -->|"3. Read cache"| RL
RL -->|"4. INCR rate counter"| REDIS
GW -->|"5. Allowed"| API
GW -->|"6. Rejected 429"| CLIENT
In 3 sentences: Every request passes through a rate limiter before reaching your API. The limiter checks a counter in Redis - if under the limit, allow and increment; if over, reject with HTTP 429. Multiple layers (edge + gateway + service) protect different things.
Understanding the Problem
What is a rate limiter? When you use an API - say Twitter or Stripe - you can only make a certain number of requests per minute. Go over the limit and you get a “429 Too Many Requests” error. That’s a rate limiter.
Why do we need it?
- Protect servers - one angry client sending 1M requests shouldn’t crash the service for everyone
- Fair usage - free-tier users get 100 calls/min, paid users get 10000
- Cost control - downstream services (databases, third-party APIs) have their own limits
- Security - stop brute-force login attempts, credential stuffing, and distributed denial-of-service (DDoS) attacks
💡 A DDoS attack is many machines flooding you at once purely to exhaust your capacity. Credential stuffing is replaying stolen username/password pairs at scale - both are “too many requests” problems, which is why a rate limiter is a security control and not only a fairness one.
Real examples:
- GitHub API: 5000 requests/hour per authenticated user
- Stripe API: 100 requests/sec per account
- Twitter API: 300 tweets/3 hours per user
Naive First Cut
The simplest possible rate limiter:
flowchart LR
CLIENT["Client"]
API["API Server<br/>HashMap counter"]
DB[("Your DB")]
CLIENT --> API
API --> DB
Keep a HashMap<userId, requestCount> inside the API server. On each request: if count < limit → allow, else → reject.
Why this breaks:
- ❌ Multiple servers - you have 10 API pods. Each has its own counter. Client hits different pods and effectively gets 10× the limit.
- ❌ Server restart - counters vanish. Everyone gets a fresh quota after every deploy.
- ❌ Memory - 10 million unique users = 10 million map entries = out-of-memory (OOM) risk.
💡 OOM is what happens when a process asks for more memory than it is allowed and the operating system kills it. A counter that is never cleaned up grows with every new user who shows up, so the map is a slow leak with a hard ending. - ❌ Window boundaries - client sends 100 requests at 11:59:59, another 100 at 12:00:01. Both windows allow it, but 200 requests arrive in 2 seconds.
Prior Art We’re Drawing From
- Stripe Rate Limiting - Uses token bucket with Redis Lua scripts. Publishes rate limit headers (X-RateLimit-Limit, Remaining, Reset) as the API industry standard. (Stripe Engineering blog)
- Cloudflare Rate Limiting - Processes 45M+ HTTP requests/sec. Uses sliding window counters at the edge for IP-level limits, with per-customer limits at the application layer. (Cloudflare blog)
- Kong Gateway - Open-source API gateway with pluggable rate limiting (local, Redis-backed, or cluster-wide). Shows the three-tier pattern: edge → gateway → service. (Kong rate limiting plugin)
- Google Cloud Armor - Demonstrates adaptive rate limiting that adjusts thresholds based on request patterns rather than fixed rules. (Google Cloud docs)
Functional Requirements
Core
- Limit requests per client - enforce a max number of requests per time window (e.g., 100 requests/minute per user)
- Return clear feedback - rejected requests get HTTP 429 with headers showing limit, remaining quota, and reset time
- Support multiple granularities - limit by user ID, API key, IP address, or endpoint
Below the Line
- Adaptive limits (auto-adjust based on system load)
- Per-endpoint weighting (expensive operations cost more tokens)
- Allowlists/blocklists
- Rate limit dashboard for API consumers
Scale Estimation (Back-of-Envelope)
- Users: Millions of API clients (both internal services and external developers)
- Write QPS: 1M rate-limit checks/sec (every API request triggers a counter check)
💡 QPS means queries per second. The number to sit with is that the limiter’s own QPS equals the entire API’s QPS - every request pays for the check, including the overwhelming majority that are nowhere near their limit. - Read QPS: Same as write - each check is a read-modify-write on the counter
- Storage: ~10GB counter storage in Redis (key per client per window, short time to live, or TTL)
💡 A TTL is an expiry clock Redis enforces itself. It is what keeps storage flat rather than growing forever: a counter for last minute’s window deletes itself instead of needing a cleanup job. - Bandwidth: Sub-ms latency per check - rate limiter must not become the bottleneck
Core Entities
- Rule - defines a limit: identifier type (user/IP/key), max requests, time window, algorithm
- Counter - tracks current usage for a specific client + window combination
- Window - the time boundary (fixed 1-min, sliding, or token bucket refill rate)
- Decision - the result of a rate check: ALLOW or REJECT, with remaining quota
Technology Choices
| Tier | Purpose | Primary Pick | Alternatives | Why Primary Wins Here |
|---|---|---|---|---|
| Counter Store | Rate limit counters per client per window | Redis | Memcached, DynamoDB, Hazelcast | Atomic INCR + TTL in one round-trip; sub-ms latency won’t bottleneck the request path |
| Rule Store | Rate limit rules and quotas | Postgres | MySQL, DynamoDB, etcd | Low-write config data; relational queries for admin dashboards |
| Edge Layer | IP-level blocking before app servers | Cloudflare WAF | AWS WAF, Kong, Envoy rate-limit filter | Drops abusive traffic before it hits your infra |
| Scripting | Atomic check-and-increment logic | Redis Lua scripts | Redis Functions, application-level locks | Lua executes atomically on Redis — no race conditions between read and increment |
| Sync Layer | Cross-node counter aggregation for distributed limiting | Redis Cluster | Envoy global rate limiting, Consul | Shared counters across all API servers without local-only drift |
Why Redis over application-level counters? With 10+ API servers, each tracking its own counter means the real limit is N × configured limit. A shared Redis counter gives a global view. Lua scripts make the check-increment-expire atomic, eliminating time-of-check-to-time-of-use (TOCTOU) races.
💡 A TOCTOU race is the gap between reading a value and acting on it: two requests both read “99 used” and both decide they are allowed, so 101 get through. Doing the read and the write as one indivisible step is what closes the gap.
Data Modeling
Redis (Counter Store — rate limit state):
-- Sliding Window Log
Key: "rl:{clientId}:{endpoint}" → Sorted Set (score = timestamp_ms, member = requestId)
TTL: window_size (e.g., 60s for "100 requests per minute")
-- Fixed Window Counter
Key: "rl:fixed:{clientId}:{endpoint}:{window_start}" → Integer (count)
TTL: 2 × window_size (overlap for sliding window approximation)
-- Token Bucket
Key: "rl:bucket:{clientId}" → Hash { tokens: 10, last_refill: 1720000000 }
Postgres (Rule Store — rate limit configuration):
CREATE TABLE rate_limit_rules (
rule_id UUID PRIMARY KEY,
identifier_type VARCHAR(20) NOT NULL, -- user_id, api_key, ip, endpoint
endpoint_pattern VARCHAR(200),
max_requests INTEGER NOT NULL,
window_seconds INTEGER NOT NULL,
algorithm VARCHAR(20) NOT NULL, -- fixed_window, sliding_log, token_bucket
burst_limit INTEGER,
created_at TIMESTAMP NOT NULL
);
Access Patterns:
| Query | Data Source | How |
|---|---|---|
| Check rate limit (hot path) | Redis | Lua script: INCR + EXPIRE atomically, return remaining quota |
| Sliding window check | Redis | ZREMRANGEBYSCORE (remove old) + ZCARD (count current) + ZADD (add new) — all in one Lua |
| Token bucket refill | Redis | Lua: compute elapsed time × refill_rate, cap at max_tokens, decrement by 1 |
| Load rules on startup | Postgres | SELECT * FROM rate_limit_rules — cached in-memory, refreshed every 30s |
| Override limit for VIP | Postgres + Redis | Update rule → publish to Kafka → all pods refresh in-memory rule cache |
How the Sliding Window Counter Works (Redis Lua Script):
- Request arrives from client X for endpoint
/api/users - Redis Lua script executes atomically:
ZREMRANGEBYSCORE rl:{clientX}:/api/users 0 (now - 60000) -- remove entries older than 60s count = ZCARD rl:{clientX}:/api/users -- count remaining entries if count < max_limit: ZADD rl:{clientX}:/api/users now requestId -- add this request EXPIRE rl:{clientX}:/api/users 60 -- set TTL return ALLOW, remaining = max_limit - count - 1 else: return REJECT, retry_after = oldest_entry_time + 60s - now - Entire check-and-increment is atomic — no race condition between concurrent requests
- Response headers:
X-RateLimit-Remaining: 42,X-RateLimit-Reset: 1720000060
The Fix for Correctness: a Shared Counter
The naive cut’s fatal flaw was that each pod counted alone. Fix only that, and nothing else yet.
New components we need:
- Multiple API Pods - your application servers running behind a load balancer. Requests hit any of them randomly.
- Redis (shared counters) - a single, blazing-fast in-memory database that ALL pods talk to. It holds the rate-limit counters so every pod sees the same global count.
flowchart LR
CLIENT["Client"]
POD1["API Pod 1"]
POD2["API Pod 2"]
POD3["API Pod 3"]
REDIS[("Redis<br/>shared counters")]
CLIENT -->|"1. Request to pod 1"| POD1
CLIENT -->|"2. Request to pod 2"| POD2
CLIENT -->|"3. Request to pod 3"| POD3
POD1 -->|"4. INCR rate counter"| REDIS
POD2 -->|"5. INCR rate counter"| REDIS
POD3 -->|"6. INCR rate counter"| REDIS
All pods check the SAME counter in Redis. Doesn’t matter which pod handles the request - the global count is always accurate.
💡 What is Redis? An in-memory database that responds in under 1 millisecond. Fast enough to check on every request without the check itself becoming the slow part.
What this leaves broken: the count is now correct, and we have bought that correctness by putting a blocking network call in front of every single request.
- 1M checks/sec is 1M round trips/sec. Every request, including the 99%+ that are nowhere near their limit, now waits on Redis before any of our own code runs. At 0.5-2ms that is a floor added to the latency of the entire API, paid overwhelmingly by well-behaved clients.
- Redis is now a single point of failure for 100% of traffic, not just for rate limiting. If the limiter cannot reach its counter it has to choose between rejecting everything and allowing everything, and both answers are bad. The “What Happens When Redis Goes Down?” section below is about that choice.
- And one Redis instance at 1M ops/sec is at the edge of what a single node does. The counter being shared does not have to mean the counter being centralized in one place, which is the distinction the distributed deep dive is actually about.
The algorithm sections below are written against a shared Redis, because that is where this lands. Which algorithm to count with and where the counter lives are separate questions, and the deep dive takes the second one.
Rate Limiting Algorithms
There are 5 main approaches. You need to know all of them for interviews, but Token Bucket and Sliding Window Counter are the most common in production.
Algorithm 1: Fixed Window Counter
How it works: Divide time into fixed intervals (e.g., every 60 seconds). Maintain one counter per user per window. Each request increments the counter. If counter exceeds the limit → reject. At window boundary → counter resets to 0.
Example with numbers:
- Limit: 100 requests per minute
- Window: 12:00:00 – 12:00:59
- User sends request #73 at 12:00:45 → counter = 73 → ✅ ALLOW
- User sends request #101 at 12:00:58 → counter = 101 → ❌ REJECT (429)
- Clock hits 12:01:00 → counter resets to 0
Redis implementation:
key = "rate:{userId}:{minute_number}"
count = INCR key
if count == 1: EXPIRE key 60 ← auto-cleanup
if count > limit: REJECT
else: ALLOW
The boundary burst problem:
- User sends 100 requests at 12:00:58 (end of window 1) → allowed
- User sends 100 requests at 12:01:01 (start of window 2) → allowed
- Result: 200 requests in 3 seconds, but technically “within limits” in both windows
flowchart LR
subgraph W1["Window 12:00-12:01"]
A["100 requests at 12:00:58"]
end
subgraph W2["Window 12:01-12:02"]
B["100 requests at 12:01:01"]
end
RESULT["200 requests in 3 seconds!"]
A -->|"1. Window A: 100 reqs"| RESULT
B -->|"2. Window B: 100 reqs"| RESULT
| Pros | Cons |
|---|---|
| ✅ Dead simple - one INCR + one EXPIRE | ❌ Boundary burst allows 2× the limit |
| ✅ Minimal memory - 1 counter per user | ❌ Not accurate for tight limits |
| ✅ O(1) per request | ❌ Resets abruptly |
Used by: GitHub API (60/hour for unauthenticated), Twitter/X (15-minute fixed windows), Slack API.
Algorithm 2: Sliding Window Log
How it works: Store the exact timestamp of EVERY request in a sorted list (Redis Sorted Set). When a new request arrives:
- Remove all entries older than
now - window_size - Count remaining entries
- If count < limit → allow and add new timestamp; else → reject
Example with numbers:
- Limit: 5 requests per 60 seconds
- Current time: 12:01:30
- Stored timestamps:
[12:00:25, 12:00:45, 12:01:05, 12:01:20, 12:01:28] - Purge entries before 12:00:30 → removes
12:00:25 - Remaining count: 4
- 4 < 5 → ✅ ALLOW, add
12:01:30to the set
Redis implementation:
key = "rate:{userId}"
now = current_timestamp_ms
ZREMRANGEBYSCORE key 0 (now - window_ms) ← purge old
count = ZCARD key ← count remaining
if count < limit:
ZADD key now now ← log this request
ALLOW
else:
REJECT
| Pros | Cons |
|---|---|
| ✅ Perfectly accurate - zero boundary burst | ❌ Memory-heavy: stores every timestamp |
| ✅ True rolling window | ❌ 10K req/min limit = 10K entries per user |
| ✅ No approximation | ❌ O(n) cleanup on each request |
Memory: For a user with 10,000 requests/hour limit, that is 10,000 timestamps stored per user. At 8 bytes each = 80KB per user. With 1M users = 80GB. Expensive.
Used by: Payment/billing systems where exact counts are non-negotiable. Not practical for high-volume public APIs.
Algorithm 3: Sliding Window Counter (Cloudflare’s approach)
💡 This is the “best of both worlds” - accuracy of sliding window + memory of fixed window.
How it works: Keep TWO counters: one for the current fixed window, one for the previous window. Estimate the rolling count using a weighted formula:
estimated_count = current_window_count + (previous_window_count × overlap_percentage)
The overlap percentage = how much of the previous window is still “within” our rolling window.
Example with numbers:
- Limit: 100 requests per minute
- Current time: 12:01:45 (we’re 45 seconds into the current window)
- Previous window (12:00–12:01): 80 requests
- Current window (12:01–12:02): 30 requests so far
- Overlap: we’re 45s into the new window, so 15s of the old window still counts = 15/60 = 25%
- Estimated count: 30 + (80 × 0.25) = 30 + 20 = 50 → under 100 → ✅ ALLOW
flowchart LR
subgraph PREV["Previous Window 12:00-12:01<br/>80 requests"]
OVERLAP["Last 15s<br/>still counts<br/>80 x 0.25 = 20"]
end
subgraph CURR["Current Window 12:01-12:02<br/>30 requests so far"]
NOW["We are here<br/>at 12:01:45"]
end
TOTAL["Estimated: 30 + 20 = 50"]
OVERLAP -->|"1. Weight previous"| TOTAL
CURR -->|"2. Add current"| TOTAL
Redis implementation:
prev_key = "rate:{userId}:{prev_minute}"
curr_key = "rate:{userId}:{curr_minute}"
elapsed = seconds_into_current_window
weight = (window_size - elapsed) / window_size
estimated = GET curr_key + GET prev_key × weight
if estimated < limit:
INCR curr_key
ALLOW
else:
REJECT
| Pros | Cons |
|---|---|
| ✅ Smooth - no boundary bursts | ❌ Approximate (~0.003% error rate) |
| ✅ O(1) memory - just 2 counters per user | ❌ Slightly more logic than fixed window |
| ✅ Cloudflare tested: 400M requests, 0.003% error |
Memory: Same as fixed window - 2 integers per user. At 1M users: ~16MB. Negligible.
Used by: Cloudflare (45M+ req/sec), most modern REST APIs. The go-to choice when you need accuracy without the memory cost of sliding log.
Algorithm 4: Token Bucket ⭐ (most popular in production)
💡 Think of a bucket that fills with tokens at a steady rate. Each request costs one token. If the bucket is empty, request is rejected. This allows controlled bursts.
How it works:
- Each user has a bucket with a maximum capacity (e.g., 10 tokens)
- Tokens are added at a fixed refill rate (e.g., 1 token every 6 seconds = 10/minute)
- Each request consumes 1 token
- If bucket is empty → reject with 429
- Tokens never exceed max capacity (bucket overflows)
Example with numbers:
- Bucket capacity: 10 tokens
- Refill rate: 1 token every 6 seconds (10/minute)
- At 12:00:00 → bucket is full (10 tokens)
- User sends 8 requests instantly → 8 tokens consumed → 2 remaining → all ✅ ALLOWED
- At 12:00:06 → 1 token refilled → bucket = 3
- At 12:00:12 → 1 more token → bucket = 4
- User sends 5 requests → 5 tokens consumed → bucket now has -1? No → 4 used, 1 rejected
Why bursts are OK here: The bucket starts full, so a user can “burst” up to 10 requests instantly. But then they must wait for refills. Over time, the average rate converges to the refill rate (10/min). This matches real user behavior - people don’t send requests at a perfectly steady rate.
flowchart TD
BUCKET["🪣 Token Bucket<br/>capacity = 10<br/>current = 7 tokens"]
REFILL["⏰ Refill<br/>+1 token every 6 sec"]
REQ["📨 Request arrives<br/>costs 1 token"]
CHECK{"tokens >= 1?"}
ALLOW["✅ Allow<br/>tokens -= 1"]
REJECT["❌ 429 Reject"]
REFILL -->|"1. Adds tokens up to max"| BUCKET
REQ -->|"2. Consume token"| CHECK
CHECK -->|"3. Yes"| ALLOW
CHECK -->|"4. No"| REJECT
BUCKET -->|"5. Serve content"| CHECK
Redis implementation (lazy refill - no background timer):
key = "bucket:{userId}"
stored = GET key → {tokens: 7, last_refill: 1750000000}
elapsed = now - last_refill
new_tokens = elapsed × refill_rate
tokens = min(capacity, stored.tokens + new_tokens)
if tokens >= 1:
tokens -= 1
SET key {tokens, last_refill: now}
ALLOW
else:
SET key {tokens, last_refill: now}
REJECT
💡 Lazy refill: Instead of a background timer adding tokens, we calculate how many tokens SHOULD have been added since the last request. Same result, zero background processes.
| Pros | Cons |
|---|---|
| ✅ Allows natural burst behavior | ❌ Two values stored per user (tokens + timestamp) |
| ✅ Smooth long-term rate enforcement | ❌ Tuning capacity + refill rate takes thought |
| ✅ Memory efficient - ~50 bytes per user | ❌ In distributed systems, need Redis for sync |
| ✅ Best UX for API consumers |
Used by: Stripe, AWS API Gateway, GitHub, Amazon. The industry default for public APIs.
Algorithm 5: Leaky Bucket
💡 Like token bucket but inverted: requests go INTO the bucket, and leak out at a constant rate. If the bucket overflows, requests are dropped.
How it works:
- Incoming requests are added to a queue (the bucket) with a fixed capacity
- A background worker processes requests from the queue at a constant, steady rate
- If the queue is full when a new request arrives → drop it (429)
Think of it as: Water (requests) pouring into a bucket with a small hole at the bottom. Water drains at a constant rate. If you pour too fast, the bucket overflows and water spills (requests are rejected).
Example with numbers:
- Bucket size: 5 requests
- Leak rate: 1 request processed every 200ms (5/sec outflow)
- 10 requests arrive simultaneously
- First 5 fill the bucket → queued
- Next 5 → bucket full → ❌ REJECTED
- Over the next second, the 5 queued requests are processed one every 200ms
flowchart LR
IN["Burst of 10 requests"]
BUCKET["🪣 Leaky Bucket<br/>capacity = 5<br/>leak rate = 1 per 200ms"]
OUT["Steady output<br/>1 req every 200ms"]
DROP["❌ Dropped<br/>5 requests overflow"]
IN -->|"1. 5 fit"| BUCKET
IN -->|"2. 5 overflow"| DROP
BUCKET -->|"3. Constant drip"| OUT
Key difference from Token Bucket:
- Token Bucket: controls how many requests a user can SEND (input shaping)
- Leaky Bucket: controls how fast requests are PROCESSED (output shaping)
Token Bucket allows bursts; Leaky Bucket smooths everything to a constant output rate.
| Pros | Cons |
|---|---|
| ✅ Perfectly smooth output - protects backends | ❌ No burst tolerance - strict constant rate |
| ✅ Prevents downstream overload | ❌ Adds latency (requests wait in queue) |
| ✅ Simple FIFO queue implementation | ❌ Old requests processed before new ones |
Used by: Shopify REST API (40 bucket size, 2/sec leak rate), Netflix (streaming traffic shaping). Best for protecting downstream services that can’t handle spikes.
💡 This is backpressure: instead of accepting whatever arrives, the system paces work to what the slowest stage downstream can actually absorb. The queue is where the mismatch is held, and the bucket size is how much mismatch you are willing to hold before dropping.
Comparison Table
| Algorithm | Memory per user | Burst handling | Accuracy | Best for |
|---|---|---|---|---|
| Fixed Window | ~8 bytes (1 counter) | ❌ 2× burst at boundaries | Low | Simple internal APIs, MVPs |
| Sliding Window Log | O(n) - 80KB+ at scale | ✅ None (perfect) | Perfect | Billing, payment systems |
| Sliding Window Counter | ~16 bytes (2 counters) | ✅ Smooth | ~99.99% | Most public REST APIs |
| Token Bucket ⭐ | ~50 bytes (token + timestamp) | ✅ Controlled bursts | High | User-facing APIs (Stripe, AWS) |
| Leaky Bucket | ~50 bytes or 1KB (queue) | ❌ None (smooths all) | High | Traffic shaping, backend protection |
Decision flowchart:
flowchart TD
START["What does your system need?"]
Q1{"Allow short bursts?"}
Q2{"Need exact precision?"}
Q3{"Shaping outbound traffic?"}
TB["Token Bucket ⭐<br/>Stripe, AWS, GitHub"]
SWC["Sliding Window Counter<br/>Cloudflare, most APIs"]
SWL["Sliding Window Log<br/>Payment and billing systems"]
LB["Leaky Bucket<br/>Shopify, Netflix"]
FW["Fixed Window<br/>Simple internal use"]
START -->|"1. Which algorithm?"| Q1
Q1 -->|"2. Yes"| TB
Q1 -->|"3. No"| Q2
Q2 -->|"4. Yes exact"| SWL
Q2 -->|"5. No approx OK"| Q3
Q3 -->|"6. Yes smooth output"| LB
Q3 -->|"7. No just cap input"| SWC
START -->|"8. Simplest possible"| FW
💡 Interview tip: Start with Token Bucket as your default answer. If the interviewer asks “what if we can’t tolerate any burst?” → switch to Sliding Window Counter. If they ask “what if we need to protect a fragile downstream?” → Leaky Bucket.
Where to Rate Limit (3 layers)
flowchart LR
CLIENT["Client"]
L1["Layer 1: Edge"]
L2["Layer 2: Gateway"]
L3["Layer 3: Service<br/>your code<br/>domain-specific"]
API["Backend"]
CLIENT -->|"1. Incoming request"| L1
L1 -->|"2. Pass to user limit"| L2
L2 -->|"3. Evaluate rate limit"| L3
L3 -->|"4. Allow"| API
| Layer | What it blocks | Key | Example |
|---|---|---|---|
| Edge (Cloudflare/WAF) | DDoS, bots, abusive IPs | IP address | “No IP can send >1000 req/sec” |
| Gateway (Kong/Envoy) | Per-user quota enforcement | API key or user ID | “Free tier: 100/min. Paid: 10000/min” |
| Service level | Domain-specific limits | Per resource | “Max 5 password reset emails/hour” |
Why three layers instead of one? Each layer catches a different class of threat at a different cost. Edge blocks volumetric DDoS attacks before they hit your infrastructure (cheapest, highest volume). Gateway enforces business rules like “free vs paid tier” (requires knowing who the user is). Service-level limits handle domain logic only your code understands (“max 5 password resets per hour”). Skipping layers means you’re either blocking too much (service-level can’t handle DDoS volume) or too little (edge doesn’t know your business rules).
💡 A WAF (web application firewall) is a filter that inspects traffic before it reaches your servers, and “edge” means it runs in a provider’s data centres near the user rather than in yours. Blocking a flood there costs you nothing but the provider’s bill; blocking it in your own code means you already paid to receive it.
💡 Why multiple layers? Edge blocks volumetric attacks cheaply (before they hit your servers). Gateway enforces business rules. Service handles logic that only your code understands.
What Happens When Redis Goes Down?
This is a classic interview question. Three options:
💡 Fail-closed means a component that cannot do its job blocks the request; fail-open means it waves the request through. Neither is universally right - a rate limiter that fails closed takes your whole API down with it, while one that fails open leaves the backend undefended exactly when something is already wrong.
flowchart TD
DOWN["Redis is down"]
FC["Fail-Closed<br/>reject all requests"]
FO["Fail-Open<br/>allow all requests"]
FB["Fallback<br/>local in-memory bucket"]
DOWN -->|"1. Redis unavailable"| FC
DOWN -->|"2. Redis unavailable"| FO
DOWN -->|"3. Redis unavailable"| FB
FC -->|"4. ❌ Global outage"| BAD["Users locked out"]
FO -->|"5. ⚠️ No protection"| OK["Backend might overload"]
FB -->|"6. ✅ Graceful"| GOOD["Slightly inaccurate but safe"]
Best answer for interviews: “Fail-open with a local fallback. If Redis is unreachable, each pod switches to a local in-memory token bucket. Less accurate (each pod enforces limit/N independently) but the API stays up. Alert on Redis being down so ops investigates.”
Complete Flow (Sequence Diagram)
Request allowed:
sequenceDiagram
autonumber
participant C as Client
participant GW as API Gateway
participant R as Redis
participant API as Backend API
C->>GW: GET /api/search
GW->>GW: extract API key from header
GW->>R: EVALSHA token_bucket_check
R->>R: refill tokens based on elapsed time
R->>R: tokens >= 1 so decrement
R-->>GW: ALLOWED remaining=87
GW->>API: forward request
API-->>GW: 200 response
GW-->>C: 200 with X-RateLimit-Remaining 87
Request rejected:
sequenceDiagram
autonumber
participant C as Client
participant GW as API Gateway
participant R as Redis
C->>GW: GET /api/search
GW->>R: EVALSHA token_bucket_check
R->>R: tokens = 0
R-->>GW: REJECTED reset_in=42s
GW-->>C: 429 Too Many Requests with Retry-After 42
Response Headers
When your API has rate limiting, always return these headers so clients can self-throttle:
HTTP/1.1 200 OK
X-RateLimit-Limit: 100 ← max requests per window
X-RateLimit-Remaining: 87 ← how many left
X-RateLimit-Reset: 1750860060 ← when the window resets (unix timestamp)
On rejection:
HTTP/1.1 429 Too Many Requests
Retry-After: 42 ← seconds to wait before retrying
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
Deep Dives
1) 1M checks a second, each one a round trip. Does the counter have to be central?
Problem: the counter has to be shared — the naive cut settled that, because 10 pods with 10 private counters hand out 10× the limit. But shared and centralized are not the same thing, and the design above chose centralized: every request blocks on Redis before anything else happens.
flowchart TD
subgraph Central["Centralized - blocks on every request"]
C1["Pod 1"]
C2["Pod 2"]
CR["Redis<br/>exact count"]
C1 -->|"blocking INCR"| CR
C2 -->|"blocking INCR"| CR
end
subgraph Local["Local plus sync - never blocks"]
L1["Pod 1<br/>in-memory count"]
L2["Pod 2<br/>in-memory count"]
LR["Redis<br/>reconciled every 100ms"]
L1 -.async sync.-> LR
L2 -.async sync.-> LR
end
Bad: centralized Redis checked synchronously on every request, which is what the design above built.
- Exact, and it taxes every request to catch the few that are over. 1M checks/sec means 1M blocking round trips/sec, and the clients who never come close to their limit pay the same 0.5-2ms as the abuser.
- It also puts the limiter in the critical path of all traffic. Redis becomes a dependency of every endpoint, and a single instance at 1M ops/sec has no headroom left for the spike that made you want a rate limiter in the first place.
Good: sticky routing — the load balancer consistently sends a given client to the same pod, which counts locally.
- No round trip at all, and the count for that client is exact because only one pod ever touches it.
- Two real costs. Load is now distributed by client rather than by capacity, so one heavy client lands entirely on one pod. And pod membership changes on every deploy and every scale event, which re-pins clients to new pods with empty counters — a rolling deploy effectively grants everyone a fresh quota.
Great: local counters with periodic async sync, and a deliberate split by what the limit is for.
- Each pod counts in memory and reconciles with Redis every ~100ms. The hot path never blocks; the sync is off to the side. Overshoot is bounded by what a pod can serve inside one sync interval, roughly 10%.
- Then the key judgment: protective limits and strict limits are different problems. Abuse prevention tolerates 110 requests where the limit said 100 — the point is stopping someone sending 100,000, and 10% error does not change that. Limits that are billed — API credits, metered usage — cannot overshoot, so those keep the synchronous centralized check and accept the latency, because for those endpoints the count is the product.
- This is why the answer is not one mechanism. Route the cheap, high-volume, protective checks locally and reserve the round trip for the small set of limits where being exactly right is worth 2ms.
2) A client spends its whole minute of quota in one second. Was that allowed?
Problem: Limit is 100/minute. Client sends all 100 in the first second. Technically within quota, but the backend cannot absorb 100 concurrent requests from one client.
Bad: a single sustained limit, which is what every algorithm above implements.
- Yes, including token bucket. A bucket sized for 100/minute refills at ~1.67 tokens/sec and holds 100, so a client that has been idle arrives with a full bucket and can legitimately spend all 100 instantly. Burst capacity is the feature, and it is also the problem.
- The limiter answers correctly and the backend still falls over, which is the uncomfortable part: nothing was violated. 100 requests in a second from each of a few hundred clients is a thundering herd that every counter in the system waves through.
- Shrinking the window is the obvious fix and it is worse. A limit of ~2/sec stops the burst and also breaks every legitimate client that opens a page making eight parallel API calls.
Great: two-tier limiting. Keep the sustained limit and add a short-window limit beside it, so burst and volume are governed separately.
flowchart TD
REQ["Incoming request"]
BURST["Burst check<br/>max 10 per second"]
SUSTAIN["Sustained check<br/>max 100 per minute"]
ALLOW["✅ Allow"]
REJECT["❌ 429 Reject"]
REQ -->|"1. Check burst"| BURST
BURST -->|"2. Pass"| SUSTAIN
BURST -->|"3. Fail"| REJECT
SUSTAIN -->|"4. Pass"| ALLOW
SUSTAIN -->|"5. Fail"| REJECT
Both limits must pass:
- Burst: max 10 requests in any 1-second window
- Sustained: max 100 requests in any 60-second window
This is what Stripe does - they publish both a “per-second” and “per-minute” limit.
Design Self-Audit
- Single points of failure? Redis holds the shared counters, and Deep Dive 1’s local-counting design is what keeps it off the critical path: if Redis is unreachable, pods keep counting locally and enforcement continues with wider overshoot. Whether an unreachable Redis should fail open or closed is a per-limit policy decision, not a global one — a protective abuse limit should stay on, a strict billing limit should refuse.
- Stale reads after writes? By design. Counters reconcile every ~100ms, so the count is eventually consistent and the overshoot is bounded by what one pod can serve inside one sync interval. That bound is the design’s actual guarantee, and it is worth stating as a number rather than calling the limiter “approximate”.
- Clock dependence? Window boundaries are clock-derived, so skew between pods effectively widens a window. Sliding-window counters are less sensitive to this than fixed windows, which is a reason to prefer them beyond smoothness.
- Dead-letter / reconciliation? None needed, and this is the rare design where that is the right answer: a lost sync costs precision for one interval, not data. Adding a DLQ here would be machinery guarding nothing.
- Hot key / skew? Named in Deep Dive 1 — sticky routing concentrates one heavy client on one pod, which is why load is distributed by capacity and the counter is reconciled rather than owned.
- Cost at the hot tier? Counting is nearly free; the cost is sync traffic, which scales with pods times active keys rather than with request volume. A limiter checked 1M times a second can be cheaper than one checked 10K times a second with more keys.
Core Flows
Flow 1 - A request is checked and allowed
sequenceDiagram
autonumber
participant C as Client
participant EDGE as Edge WAF
participant GW as API Gateway
participant L as Pod local counter
participant R as Redis
participant API as Backend Service
C->>EDGE: request
EDGE->>EDGE: IP level check
EDGE->>GW: forward
GW->>L: increment for this key
L-->>GW: under limit
GW->>API: forward with remaining quota header
API-->>C: 200 with limit headers
Note over L,R: reconciliation runs off the request path
L->>R: periodic sync of local deltas
R-->>L: cluster wide count
- Two tiers, deliberately. The edge handles IP-level abuse where the cheapest possible answer is right; the gateway handles per-user and per-key limits where identity is known.
- The hot path touches memory only. Deep Dive 1 is the argument for that: a blocking round trip per request taxes the 99% of traffic that is nowhere near its limit to catch the 1% that is.
- The response carries limit, remaining and reset headers whether or not the request was throttled, so a well-behaved client can pace itself instead of discovering the limit by hitting it.
- Sync is periodic and asynchronous. The overshoot that buys is bounded by what one pod can serve inside one interval, which is the design’s actual guarantee.
Failure worth calling out: if Redis is unreachable, pods keep counting locally and never reconcile, so the effective limit becomes per-pod rather than global — a client spread across ten pods gets roughly ten times its quota. That is the correct behaviour for a protective limit and the wrong one for a strict one, which is why the Design Self-Audit makes fail-open versus fail-closed a per-limit decision instead of a global switch.
Flow 2 - A request is rejected
sequenceDiagram
autonumber
participant C as Client
participant GW as API Gateway
participant L as Pod local counter
participant K as Analytics
participant API as Backend Service
C->>GW: request
GW->>L: increment for this key
L-->>GW: over limit
GW-->>C: 429 with Retry-After
GW->>K: limit exceeded event
Note over GW,API: the backend is never called
- The rejection happens at the gateway, so a throttled request costs no backend capacity. A limiter that forwards the request and then discards the response protects nothing.
Retry-Afteris the part clients actually need — without it, a client’s retry loop becomes the next incident.- The event is published for analytics, not for enforcement, so losing it costs a chart and nothing else.
Failure worth calling out: the burst case in Deep Dive 2 means a client can be inside its per-minute quota and still rejected by the short-window limit, which looks arbitrary from outside. The headers have to say which limit was hit, or the client author concludes the limiter is random and writes a tighter retry loop.
Flow 3 - Multiple granularities on one request
sequenceDiagram
autonumber
participant C as Client
participant GW as API Gateway
participant L as Pod local counter
C->>GW: request with api key to an endpoint
GW->>L: check per api key
GW->>L: check per user
GW->>L: check per endpoint
L-->>GW: all three results
GW->>GW: reject if any limit is exceeded
GW-->>C: allowed or 429 naming the limit
- The checks are independent counters evaluated together, not a hierarchy. Any one of them can reject.
- They are batched into a single call rather than three, because at 1M checks a second the per-call overhead, not the counting, is what costs.
- The strictest limit wins, and the response says which one — see the previous flow for why that matters.
Failure worth calling out: granularities interact in ways nobody configured. A generous per-key limit and a tight per-endpoint limit means one noisy client can exhaust an endpoint’s budget and throttle every other client of that endpoint. Per-endpoint limits therefore need to be per endpoint per client, or they become a shared fate nobody intended.
Final Architecture
flowchart LR
CLIENTS["Clients"]
EDGE["Edge WAF<br/>IP limits and DDoS"]
GW["API Gateway<br/>per-user limits"]
RL["Rate Limit Check<br/>Redis Lua script"]
REDIS[("Redis Cluster<br/>token buckets")]
RULES[("Rules Config<br/>limit per tier")]
API["Backend Services"]
K["Analytics<br/>limit events"]
CLIENTS -->|"Incoming request"| EDGE
EDGE -->|"IP check pass"| GW
GW -->|"Read cache"| RL
RL -->|"INCR rate counter"| REDIS
RL -->|"Load limit rules"| RULES
GW -->|"Allowed"| API
RL -->|"Publish change"| K
How it works end-to-end:
- Client sends request — hits the Edge WAF first for IP-level DDoS protection
- Edge WAF passes clean traffic — volumetric/IP-based attacks blocked; legitimate requests forwarded to API Gateway
- API Gateway applies per-user limits — invokes the Rate Limit Check (Redis Lua script) with the user’s token bucket key
- Redis Lua script executes atomically — reads current token count, checks against Rules Config tier limits, decrements if allowed
- Request allowed — Gateway forwards to Backend Services; response includes X-RateLimit-Remaining headers
- Request denied — returns HTTP 429 with Retry-After header; event published to Analytics for monitoring
- Analytics tracks limit events — enables dashboards showing which users/endpoints hit limits and abuse patterns
Interview Cheat Sheet
| Question | Answer |
|---|---|
| “Which algorithm?” | Token Bucket - allows bursts, caps sustained rate |
| “Where to store counters?” | Redis - sub-ms latency, atomic Lua, built-in TTL |
| “How to make it atomic?” | Redis Lua script - read + check + decrement in one operation |
| “What if Redis is down?” | Fail-open + local fallback. Never be a single point of failure. |
| “Where to put it?” | 3 layers: Edge (IP/DDoS) → Gateway (per-user) → Service (domain logic) |
| “How to handle distributed?” | Centralized Redis for strict limits; local sync for soft limits |
| “What headers to return?” | X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After |
Key Technologies
| Term | What it is |
|---|---|
| Redis | An in-memory database. Responds in < 1ms. Used for counters, caches, and fast lookups. |
| Lua script | A tiny program that runs INSIDE Redis. Lets you read + check + write atomically in one network call. No race conditions between “check count” and “increment count”. |
| API Gateway | A server that sits in front of your APIs. Handles auth, rate limiting, routing. Examples: Kong, Envoy, AWS API Gateway. |
| CDN / Edge | Servers at the “edge” of the network, close to users worldwide. Cloudflare, CloudFront. First line of defense. |
| Token Bucket | Algorithm: bucket of tokens, refills at steady rate. Each request costs a token. Empty bucket = rejected. |
| HTTP 429 | Standard HTTP status code meaning “Too Many Requests.” Client should back off and retry later. |
💡 Redis Lua scripts execute atomically on the server - critical for distributed rate limiting where multiple pods check the same counter.
What’s Expected at Each Level
This section helps you calibrate your depth. You don’t need to cover everything - just know what’s expected for your level.
Mid-level
Explain the token bucket or fixed window algorithm. Propose Redis INCR for counting requests per time window. Understand why in-memory counters fail across multiple servers - each server has its own count, so a client can exceed limits by hitting different servers.
Senior
Compare token bucket vs sliding window vs sliding window log - articulate the tradeoffs (burst tolerance, memory, precision). Propose Redis Lua scripts for atomic check-and-increment. Discuss multi-tier limiting (edge + gateway + service) and what happens when Redis goes down (fail-open vs fail-closed tradeoff).
Staff+
Address distributed rate limiting across multiple regions with eventual consistency (local counters + periodic sync vs centralized Redis). Discuss adaptive rate limits that adjust dynamically based on system load (shed traffic before the backend saturates). Cover per-endpoint granularity (expensive operations like writes get tighter limits than cheap reads) and cost-based limiting where each operation has a “weight” consuming tokens proportionally.
🎯 Key Takeaways
- Token bucket allows bursts; sliding window is smoother but more complex
- Redis Lua scripts make check-and-increment atomic - no race conditions
- Apply at multiple levels: per-user, per-IP, per-endpoint, global
- Return 429 with Retry-After header - good API citizenship
Related Designs
- URL Shortener - high-QPS API design
- Leaderboard - Redis patterns
- Notification System - protecting downstream services
Related Concepts
Understand the building blocks used in this design:
- Rate Limiting → — the core algorithms (token bucket, sliding window) this whole design is built on
- Caching → — Redis holds the per-client counters for sub-millisecond checks
- Distributed Locking → — atomic check-and-decrement via Lua keeps counts correct across many pods
Discussion
Newest first