System designReliabilityIntermediate

Rate Limiting in System Design

How systems protect themselves from abuse, spikes and runaway clients: every major algorithm, how to make it work across many servers with Redis, and what to do when the limiter itself breaks.

The short answerRate limiting caps how much work a client may ask for: N requests per time window, or N operations in flight at once, keyed by IP, user, API key, tenant or route. Requests over the limit are rejected with HTTP 429 and a Retry-After header, or queued. Token bucket (allows short bursts) and sliding window counter (smooth, low memory) are the usual choices, enforced atomically in a shared store like Redis so every server sees the same count.

HLD book
01Fundamentals

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.

Client1,000 requests
Rate limiterAllows 100 / min
ApplicationProtected

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.

02Architecture

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.

Internet traffic
CDN / edge / WAFCoarse per-IP and bot limits
API gatewayPer-user, per-API-key, per-route quotas
ApplicationBusiness rules: “one OTP per 30 s”
Database / downstreamThe protected resources
03Identity

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.

KeyUse it forWatch out for
IP addressAnonymous traffic, basic abuse controlMany users behind one NAT; attackers rotate IPs
User IDPer-account quotas once logged inNeeds authentication first
API keyDeveloper and partner APIsLeaked keys: allow rotation and per-key limits
Tenant / orgPlan limits in multi-tenant SaaSOne tenant's users share the pool
EndpointStricter limits on expensive routesKeep the route list maintainable
OperationOTP, password reset, AI generation, exportsOften needs several keys at once
A composite limiter keytext
rate:tenant:company_123:user:user_42:route:POST /api/payments
04Algorithm 1

Fixed window counter

Split time into fixed intervals and keep one counter per key per interval.

Limit: 100 requests per minutetext
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
Fixed window in Redis (atomic)lua
-- 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                                   -- allow
05Algorithm 2

Sliding window log

Store a timestamp for each request and count only those inside the last N seconds, measured from now.

Rolling 60-second window at 10:01:20text
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
Sliding log with a Redis sorted setlua
-- 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 1

Benefit

  • Exact rolling limit
  • No boundary bursts

Cost

  • One entry per request
  • A 10,000/min limit can mean 10,000 entries per key
06Algorithm 3

Sliding window counter

Approximate the rolling window by blending the previous window's count with the current one.

The estimatetext
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, allow
07Algorithm 4

Token bucket

Tokens drip into a bucket at a fixed rate up to its capacity. Each request takes one token; no token, no request.

Refill+10 tokens / second
Token bucketCapacity 100
APIRequest allowed

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.

Try it: a live token bucketcapacity 10 · refills 2 tokens / sec
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.

Token bucket in Redis (atomic Lua)lua
-- 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 allowed
08Algorithm 5

Leaky bucket

Requests pour into a bucket (a queue) and drain out at a constant rate. When the bucket is full, new requests overflow.

Burst traffic1,000 requests / sec
Bucket / queueFinite capacity
BackendSteady 100 requests / sec
09Expensive operations

Concurrency limiting

When one request takes 50 ms and another 50 seconds, requests per second stops meaning much. Limit what's running instead.

In-flight captext
max concurrent AI generations: 20
currently running:             20
new request:                   reject (429 / 503 + Retry-After) or queue

Rate 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
10Selection

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.

  1. 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.
  2. 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.
  3. 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 %).
  4. 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.
  5. 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.
  6. 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.
11Distributed systems

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

UserLimit = 100 / min
API 1allows 100
API 2allows 100
API 3allows 100

Effective limit: 300 per minute, and it grows with every server you add.

Shared state

API 1
API 2
API 3
Redisrate:user:42 → 76 / 100

Why atomicity matters

The race that breaks a naive limitertext
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.

12API behaviour

HTTP 429 and rate-limit responses

Tell clients clearly that they were limited, and when they can try again.

A good 429 responsehttp
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 }
13Traffic spikes

Bursts and hot keys

A limiter must tell an acceptable short burst from sustained overload, and survive one identity sending enormous traffic.

Normal traffic100 requests / sec
Flash event10,000 requests / sec
Token bucketAllows a bounded burst
BackendProtected

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

R1
R2
R3
Millions
rate:api-key:popularOne hot Redis 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.

14Global systems

Multi-region rate limiting

A worldwide limit gets hard when each region handles traffic independently.

Global userLimit = 1,000 / min worldwide
Indiaallows 400
USallows 400
Europeallows 400

Independent regional limits could allow 1,200 instead of 1,000.

ApproachAccuracyCost
Central global counterExactCross-region latency on every request, plus a global dependency
Split quota per regionExact overallUnused quota gets stranded in quiet regions
Async-synced countersBriefly overshootsFast and local
HybridCloseStrict local ceilings, global quota reconciled in the background
15Case study

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.

500K+ usersTickets open
CDN / edgeStatic assets + coarse abuse controls
Rate limiterIP + user + booking limits
Load balancer
Booking 1
Booking 2
Booking N
RedisSeat holds + quota state
Booking DBDurable bookings
LimitWhy
Per IPCut obvious bot floods early.
Per userOne account can't hammer the booking API.
Per showOne hot show can't overwhelm shared booking state.
OTP sendsNo unlimited SMS (fail closed).
Payment attemptsProtect the payment provider and limit fraud.
SearchHigher limits, since browsing isn't correctness-critical.

Layered protection, in order

  1. Edge

    Filters obvious abusive traffic.

  2. Gateway

    Enforces IP, user and API-key quotas.

  3. Booking service

    Applies stricter business limits.

  4. Token bucket

    Allows a controlled burst at 10:00:00.

  5. Load balancer

    Spreads the accepted traffic.

  6. Redis

    Holds distributed quota state and seat holds.

  7. Seat locking

    Prevents concurrent booking conflicts.

  8. Database

    Guarantees final booking correctness.

16Production engineering

Failures and metrics

The limiter sits on the critical path, so its own failure modes need explicit answers.

FailureWhat to do
Redis is downFail open or closed per endpoint; fall back to a local in-memory limit.
Race conditionAtomic Lua scripts so concurrent requests can't exceed the quota.
Clock skewUse Redis server time (TIME) or one clock source, not each app server's clock.
Hot keyLocal pre-limits, sharded counters, edge enforcement.
Limiter adds latencyCo-locate Redis, pipeline calls, use local limits for coarse checks.
Config mistake10/min deployed instead of 10,000/min is an outage: validate and roll out in stages.
Regional partitionGlobal quotas drift; define the acceptable overshoot.
Retry stormRetry-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
Interview prep

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.

1

Why 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.

2

Where 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.

3

Rate 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.

4

Explain 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.

5

Explain 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.

6

Explain 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.

7

Explain 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.

8

Token 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.

9

What 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.

10

How 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.

11

How 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.

12

What 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.

13

How 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.

14

How 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.

15

How 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.

16

How 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.

17

How 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.

18

Exact 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.

19

When 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.

20

How 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.

Check yourself

Quick quiz

6 questions. Pick an answer to see why it's right or wrong.

Question 1 of 60 / 6

Limit: 100 requests per minute, fixed windows. What is the most a client can get through in about 2 seconds?

Reference

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.
Summary

Key takeaways

  1. Rate limiting protects capacity, cost and fairness. It's a safety system, not a feature.
  2. Layer it: coarse limits at the edge, identity-based quotas at the gateway, business rules in the service.
  3. Pick the key carefully: IP alone is unfair behind NAT; prefer user, API key or tenant once authenticated.
  4. Token bucket for APIs that should allow bursts; sliding window counter for smooth limits at low memory; concurrency limits for slow, expensive work.
  5. Across servers, keep counters in shared state (Redis) and update them atomically with Lua.
  6. Always return 429 with Retry-After, and make clients back off with jitter.
  7. Decide fail-open vs fail-closed per endpoint before the outage, not during it.
Questions

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.

Next topicCaching

Once traffic is under control, make the reads fast: cache-aside, invalidation, stampedes, hot keys and Redis design.

Go deeperSee rate limiting inside complete designs

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
Explore the book

Last reviewed 18 November 2026