What is rate limiting?
A cap on how much work a client may ask for, per time window or at the same time, so the system only accepts what it can safely do.
The other 900 get HTTP 429 Too Many Requests.
Why every public system needs one
Stop abuse
Scrapers, credential stuffing and bots can't send unlimited requests.
Protect infrastructure
Databases, queues and downstream services never see more than they can take.
Control cost
AI inference, SMS and third-party APIs cost money per call.
Fairness
One noisy tenant can't consume everyone's capacity.
DDoS defence in depth
One layer of a wider traffic-protection strategy.
Business quotas
Free, Pro and Enterprise plans get different limits.
Where should the limiter live?
Several layers can enforce limits, and big systems use all of them. Each rejects what it can see most cheaply.
What do you limit by?
The limiter key decides who shares a quota. Get it wrong and you either block innocent users or miss the abuser.
| Key | Use it for | Watch out for |
|---|---|---|
| IP address | Anonymous traffic, basic abuse control | Many users behind one NAT; attackers rotate IPs |
| User ID | Per-account quotas once logged in | Needs authentication first |
| API key | Developer and partner APIs | Leaked keys: allow rotation and per-key limits |
| Tenant / org | Plan limits in multi-tenant SaaS | One tenant's users share the pool |
| Endpoint | Stricter limits on expensive routes | Keep the route list maintainable |
| Operation | OTP, password reset, AI generation, exports | Often needs several keys at once |
rate:tenant:company_123:user:user_42:route:POST /api/paymentsFixed window counter
Split time into fixed intervals and keep one counter per key per interval.
Window 1: 10:00:00 – 10:00:59 counter resets at 10:01:00
Window 2: 10:01:00 – 10:01:59 counter resets at 10:02:00-- KEYS[1] = rate:user:42:202611181546 (key includes the minute)
-- ARGV[1] = limit, ARGV[2] = window seconds
local count = redis.call("INCR", KEYS[1])
if count == 1 then
redis.call("EXPIRE", KEYS[1], ARGV[2]) -- set the TTL only on the first hit
end
if count > tonumber(ARGV[1]) then
return 0 -- reject
end
return 1 -- allowSliding window log
Store a timestamp for each request and count only those inside the last N seconds, measured from now.
stored: 10:00:25 10:00:40 10:00:55 10:01:10 10:01:18
drop anything older than 10:00:20 → 5 requests in the window-- KEYS[1] = rate:log:user:42
-- ARGV[1] = now (ms), ARGV[2] = window (ms), ARGV[3] = limit, ARGV[4] = unique request id
redis.call("ZREMRANGEBYSCORE", KEYS[1], 0, ARGV[1] - ARGV[2]) -- forget old requests
if redis.call("ZCARD", KEYS[1]) >= tonumber(ARGV[3]) then
return 0
end
redis.call("ZADD", KEYS[1], ARGV[1], ARGV[4])
redis.call("PEXPIRE", KEYS[1], ARGV[2])
return 1Benefit
- Exact rolling limit
- No boundary bursts
Cost
- One entry per request
- A 10,000/min limit can mean 10,000 entries per key
Sliding window counter
Approximate the rolling window by blending the previous window's count with the current one.
previous window count = 80
current window count = 20
current window is 25% elapsed, so 75% of the previous window still overlaps
estimate = 80 × 0.75 + 20 = 80 → under a limit of 100, allowToken bucket
Tokens drip into a bucket at a fixed rate up to its capacity. Each request takes one token; no token, no request.
A client that has been quiet has a full bucket and can send a burst of up to 100 requests at once. But it can never sustain more than 10 per second, because that's how fast tokens come back. Bursts are allowed; the long-run average is capped.
- Tokens
- 10.0
- Allowed
- 0
- 429s
- 0
Send a flood: the first 10 pass because the bucket was full, the rest get 429. Wait a few seconds and tokens come back at 2 per second. That's a burst allowance with a capped average rate.
-- KEYS[1] = bucket key; ARGV: capacity, refill_per_sec, now_ms, cost
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local b = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens = tonumber(b[1]) or capacity
local ts = tonumber(b[2]) or now
tokens = math.min(capacity, tokens + (now - ts) / 1000 * rate) -- refill since last call
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call("HSET", KEYS[1], "tokens", tokens, "ts", now)
redis.call("PEXPIRE", KEYS[1], math.ceil(capacity / rate * 1000) * 2) -- idle buckets expire
return allowedLeaky bucket
Requests pour into a bucket (a queue) and drain out at a constant rate. When the bucket is full, new requests overflow.
Concurrency limiting
When one request takes 50 ms and another 50 seconds, requests per second stops meaning much. Limit what's running instead.
max concurrent AI generations: 20
currently running: 20
new request: reject (429 / 503 + Retry-After) or queueRate limit (RPS)
- How many requests start per interval
- Cheap to check
- Blind to how long each one runs
Concurrency limit
- How many run at the same time
- Bounds CPU, GPU, memory and connections
- Release the slot on finish, error or timeout
Which algorithm should you use?
It depends on how exact the limit must be, whether bursts are OK, how much state you can afford, and how complex you're willing to go.
Fixed window counter
Simple- How
- One counter per key per interval, e.g. per minute.
- Good for
- Simple APIs where edge bursts are acceptable.
- Benefit
- Cheapest possible: one INCR and a TTL.
- Trade-off
- Up to 2× the limit at window boundaries.
Sliding window log
Exact- How
- A timestamp per request; count those inside the rolling window.
- Good for
- Low-to-medium traffic where exact limits matter.
- Benefit
- Exact rolling limit.
- Trade-off
- Memory grows with every request.
Sliding window counter
Balanced- How
- Weighted blend of the previous and current window counts.
- Good for
- Most high-traffic APIs.
- Benefit
- Smooth limits with two counters per key.
- Trade-off
- An approximation (usually within a few %).
Token bucket
Bursts- How
- Refill R tokens/sec up to capacity C; each request spends one.
- Good for
- Public APIs that should tolerate short bursts.
- Benefit
- Bursts allowed, average still capped.
- Trade-off
- Refill and spend must be atomic.
Leaky bucket
Smooth- How
- Queue requests; process them at a constant rate.
- Good for
- Protecting a downstream that needs steady input.
- Benefit
- Turns bursts into predictable output.
- Trade-off
- Adds waiting; overflow is dropped.
Concurrency limiter
In flight- How
- Cap the number of operations running at once.
- Good for
- AI inference, exports, uploads, slow queries.
- Benefit
- Bounds real resource use when durations vary.
- Trade-off
- Doesn't cap requests per second by itself.
Distributed rate limiting with Redis
A limiter inside one server is easy. With many servers behind a load balancer, each one only sees part of the traffic.
The broken local design
Effective limit: 300 per minute, and it grows with every server you add.
Shared state
Why atomicity matters
Request A: GET counter → 99
Request B: GET counter → 99
A: 99 < 100 → allow B: 99 < 100 → allow
Both increment → counter = 101. The limit is broken.The fix is to make check + update one atomic step. Redis runs a Lua script without interleaving other commands, so every script in this guide is race-free. Load it once with SCRIPT LOAD and call it with EVALSHA to avoid resending the script.
HTTP 429 and rate-limit responses
Tell clients clearly that they were limited, and when they can try again.
HTTP/1.1 429 Too Many Requests
Retry-After: 30
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 30
Content-Type: application/json
{ "error": "rate_limited", "message": "Too many requests. Try again in 30 seconds.", "retryAfterSeconds": 30 }Bursts and hot keys
A limiter must tell an acceptable short burst from sustained overload, and survive one identity sending enormous traffic.
Burst capacity
Temporary traffic above the steady rate (the bucket size).
Sustained rate
Long-term throughput (the refill rate).
Queueing
Work that can wait goes to a queue instead of being rejected.
Load shedding
Under extreme pressure, drop optional requests first.
The rate limiter's own hot key
Local + global limits
A small per-instance limit absorbs most excess before it reaches Redis.
Sharded counters
For approximate limits, spread one counter across several keys.
Edge enforcement
Reject obvious floods before central infrastructure.
Dedicated capacity
Very large tenants get their own limiter state.
Multi-region rate limiting
A worldwide limit gets hard when each region handles traffic independently.
Independent regional limits could allow 1,200 instead of 1,000.
| Approach | Accuracy | Cost |
|---|---|---|
| Central global counter | Exact | Cross-region latency on every request, plus a global dependency |
| Split quota per region | Exact overall | Unused quota gets stranded in quiet regions |
| Async-synced counters | Briefly overshoots | Fast and local |
| Hybrid | Close | Strict local ceilings, global quota reconciled in the background |
Rate limiting a ticket flash sale
Tickets for a blockbuster open at exactly 10:00 AM, and half a million people press the button together.
| Limit | Why |
|---|---|
| Per IP | Cut obvious bot floods early. |
| Per user | One account can't hammer the booking API. |
| Per show | One hot show can't overwhelm shared booking state. |
| OTP sends | No unlimited SMS (fail closed). |
| Payment attempts | Protect the payment provider and limit fraud. |
| Search | Higher limits, since browsing isn't correctness-critical. |
Layered protection, in order
Edge
Filters obvious abusive traffic.
Gateway
Enforces IP, user and API-key quotas.
Booking service
Applies stricter business limits.
Token bucket
Allows a controlled burst at 10:00:00.
Load balancer
Spreads the accepted traffic.
Redis
Holds distributed quota state and seat holds.
Seat locking
Prevents concurrent booking conflicts.
Database
Guarantees final booking correctness.
Failures and metrics
The limiter sits on the critical path, so its own failure modes need explicit answers.
| Failure | What to do |
|---|---|
| Redis is down | Fail open or closed per endpoint; fall back to a local in-memory limit. |
| Race condition | Atomic Lua scripts so concurrent requests can't exceed the quota. |
| Clock skew | Use Redis server time (TIME) or one clock source, not each app server's clock. |
| Hot key | Local pre-limits, sharded counters, edge enforcement. |
| Limiter adds latency | Co-locate Redis, pipeline calls, use local limits for coarse checks. |
| Config mistake | 10/min deployed instead of 10,000/min is an outage: validate and roll out in stages. |
| Regional partition | Global quotas drift; define the acceptable overshoot. |
| Retry storm | Retry-After, client backoff with jitter. |
Fail open vs fail closed
Fail open
Limiter down → allow the request.
- When availability beats strict quotas
- Search, browsing, public reads
- Best with a local fallback limit
Fail closed
Limiter down → reject the request.
- When the operation is costly or abusable
- Login, OTP, payments, AI generation
- Show a clear “try again shortly” message
Metrics to watch
- Allowed requests
- Rejected requests
- 429 rate
- Limiter latency
- Redis latency & errors
- Hot keys
- Top limited users & IPs
- Limit utilisation
- Fail-open count
- Fail-closed count
- Burst rate
- Quota exhaustion
- Regional drift
- Config changes
Rate limiting interview questions, with answers
Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.
1Why do we need rate limiting?
To protect services and their dependencies from more work than they can handle, whether from abuse, bots, bugs or genuine spikes; to keep one tenant from starving others; to cap the cost of expensive operations like AI inference or SMS; and to enforce plan quotas.
2Where should a rate limiter be placed?
In layers. Coarse per-IP and bot limits at the CDN or WAF, per-user, per-API-key and per-plan quotas at the API gateway, and business rules such as one OTP every 30 seconds inside the service. Each layer rejects what it can see cheapest.
3Rate limiting vs throttling?
They're often used interchangeably. A useful distinction: rate limiting rejects requests over the limit (429), while throttling slows them down by queueing or delaying them so they're served later at a controlled rate.
4Explain the fixed window counter and its boundary problem.
Count requests per key in fixed buckets, such as each calendar minute, and reject once the count passes the limit. It's cheap, one counter with a TTL, but a client can send the full limit at 10:00:59 and again at 10:01:00, so up to double the limit passes in about a second.
5Explain the sliding window log. Why is it memory-heavy?
Store a timestamp for every request (for example in a Redis sorted set), drop entries older than the window, and count what's left. It's exact, but it stores one entry per request, so a 1,000-per-minute limit means up to 1,000 entries per key.
6Explain the sliding window counter.
Keep counts for the current and previous fixed windows and weight the previous one by how much of it still overlaps the rolling window: estimate = previous × (1 − elapsed fraction) + current. It's nearly as smooth as a log with just two counters per key.
7Explain the token bucket. Why does it allow bursts?
A bucket holds up to C tokens and refills at R tokens per second; each request takes a token or is rejected. A client that has been quiet has a full bucket and can burst C requests at once, but its sustained rate can never exceed R.
8Token bucket vs leaky bucket?
Token bucket limits the average rate but lets bursts through when tokens have saved up. Leaky bucket queues incoming requests and lets them out at a constant rate, so output is smooth and bursts wait or overflow. Use token bucket for APIs, leaky bucket to protect something that needs steady input.
9What is concurrency limiting, and how is it different from an RPS limit?
It caps how many operations are in progress at once, for example at most 20 AI generations running at a time. An RPS limit caps how many requests start per second. When request durations vary wildly, concurrency is what actually protects CPU, GPU or connection pools.
10How do you rate limit across many application servers?
Per-server counters let each server allow the full limit, so three servers mean three times the limit. Keep the counter in shared, fast state, usually Redis, keyed by identity, and update it atomically; or use a gateway that does this for you.
11How do race conditions break a rate limiter, and how does Lua help?
If two requests both read 99, both decide they're under 100, and both increment, the limit is exceeded. A Redis Lua script runs atomically on the server, so the read, the check and the update happen as one step with no other command in between.
12What should a client receive when it's rate limited?
HTTP 429 Too Many Requests with a Retry-After header (seconds, or an HTTP date), ideally plus RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers, and a clear JSON error body. Clients should wait at least Retry-After and back off with jitter.
13How do you prevent retry storms after 429s?
Always send Retry-After, add jitter on the client so retries spread out, use exponential backoff with a cap, and make SDKs honour these by default. The limiter should also be cheap enough that rejecting requests doesn't overload it.
14How do free and premium users get different limits?
The gateway resolves the caller's plan from the token or API key, looks up that plan's rule (for example 100 vs 5,000 per minute, with its own burst size) and builds the limiter key from the identity, such as rate:plan:pro:user:42.
15How would you rate limit OTP generation?
Use several keys at once: per phone number (one every 30 seconds and five per hour), per IP and per device, plus a daily cap. Fail closed if the limiter is unavailable, because SMS costs money and OTP floods are a common abuse vector.
16How do you handle a hot key in the rate limiter?
Enforce a local per-instance limit first so most excess traffic never reaches Redis, reject obvious floods at the edge, shard the counter across several keys for approximate limits, or give very large tenants dedicated limiter capacity.
17How would you implement a global limit across regions?
Choose by how exact it must be. A central counter is exact but adds cross-region latency and a dependency. Splitting the quota between regions is fast but can strand unused quota. Locally enforced limits with asynchronous global sync are fast but may briefly overshoot. Most systems use a hybrid.
18Exact vs approximate rate limiting: when does it matter?
Abuse protection can tolerate a few percent of overshoot, so approximate algorithms and async sync are fine. Billing quotas, paid API credits or anything with real cost per call needs stronger, exact enforcement.
19When would you fail open, and when fail closed?
Fail open (allow traffic when the limiter is down) for low-risk reads where availability matters more than strict quotas. Fail closed for login, OTP, payments and expensive operations where unlimited access is dangerous. A local in-memory limit is a good middle ground for both.
20How would you protect an expensive AI inference endpoint?
Combine a per-user token bucket for request rate, a per-user and global concurrency limit for in-flight jobs, a quota on tokens or credits per day, and a queue with backpressure when GPUs are saturated, returning 429 or 503 with Retry-After.
Quick quiz
6 questions. Pick an answer to see why it's right or wrong.
Limit: 100 requests per minute, fixed windows. What is the most a client can get through in about 2 seconds?
Rate limiting glossary
The terms from this guide, in one line each.
- Rate limit
- A cap on requests per time window for a given key (user, IP, API key…).
- Limiter key
- The identity a quota belongs to, e.g. rate:user:42:route:/payments.
- Fixed window
- Counts per calendar interval; cheap, but allows bursts at the boundaries.
- Sliding window
- Counts over the last N seconds from now: exact with a log, approximate with two counters.
- Token bucket
- Tokens refill at rate R up to capacity C; each request spends one.
- Leaky bucket
- Requests queue and leave at a constant rate, smoothing bursts.
- Concurrency limit
- A cap on operations in flight at the same time.
- HTTP 429
- Too Many Requests: the standard response to a client over its limit.
- Retry-After
- Response header telling the client how long to wait before retrying.
- Fail open / closed
- Allow, or reject, traffic when the limiter itself is unavailable.
Key takeaways
- Rate limiting protects capacity, cost and fairness. It's a safety system, not a feature.
- Layer it: coarse limits at the edge, identity-based quotas at the gateway, business rules in the service.
- Pick the key carefully: IP alone is unfair behind NAT; prefer user, API key or tenant once authenticated.
- Token bucket for APIs that should allow bursts; sliding window counter for smooth limits at low memory; concurrency limits for slow, expensive work.
- Across servers, keep counters in shared state (Redis) and update them atomically with Lua.
- Always return 429 with Retry-After, and make clients back off with jitter.
- Decide fail-open vs fail-closed per endpoint before the outage, not during it.
Rate limiting: frequently asked questions
What is rate limiting in system design?
Rate limiting controls how many requests a client, user, API key, tenant or route may make in a period, or how many operations may run at once. Requests beyond the limit are rejected with HTTP 429 or queued, which protects services from overload and abuse.
Which rate limiting algorithm is best?
There's no single best one. Token bucket is the common default for APIs because it allows controlled bursts; sliding window counter gives smooth limits with little memory; fixed window is simplest; leaky bucket smooths output; concurrency limits protect slow, expensive operations.
Why is Redis used for distributed rate limiting?
Redis is fast, shared by all application servers, supports TTLs, and can run Lua scripts atomically. That lets every server check and update the same counter in about a millisecond without race conditions.
What HTTP status code should a rate limiter return?
429 Too Many Requests, with a Retry-After header telling the client when to try again. Many APIs also send RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers.
Should rate limits be based only on IP address?
No. IP limits are useful for anonymous traffic, but many users can share one IP behind NAT or a corporate proxy, and attackers rotate IPs. Once a user is authenticated, limit by user ID, API key, tenant or route as well.
What is the difference between token bucket and leaky bucket?
Token bucket allows short bursts up to the bucket size while capping the average rate. Leaky bucket processes requests at a constant rate, queueing or dropping the excess, so its output is smooth.
Once traffic is under control, make the reads fast: cache-aside, invalidation, stampedes, hot keys and Redis design.
Combine rate limiting with caching, databases, load balancing, queues, locking and failure handling in complete HLD interview designs.
- Rate limiter
- Redis
- Caching
- Queues
- BookMyShow
- Concurrency
Last reviewed 18 November 2026