SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Rate Limiting
  • Authentication vs Authorization
  • Session vs Token Based Auth
  • JWT
  • OAuth / OAuth2
  • Single Sign-On (SSO)
  • API Keys
  • OpenID Connect (OIDC)
  • CSRF
  • Input Validation
  • mTLS and Request Signing (HMAC)
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Security

Rate Limiting

Limit how many requests one user can make, so nobody can overload the system.

⏱ 15 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Rate limiting controls how many requests one user (or app) can make in a period of time. Extra requests are refused.

  • It protects the system from overload, abuse and bills that grow out of control.
  • A refused request gets HTTP status 429 Too Many Requests.
  • Four common ways: fixed window, sliding window, token bucket and leaky bucket.

02Concept: What is it?

A rate limiter sits in front of your API. For every request it asks one question: β€œHas this caller already used too much?” If yes, it says no before the request reaches your servers.

Where the limiter sits
πŸ“±Clients
→↓
🚦Rate limiterAPI gateway / proxy
→↓allowed
πŸ–₯️API servers
🚦Rate limiter
→↓429 Too Many Requests
πŸ“±Client waits
Rejected requests never touch the servers or the database, so they cost almost nothing.
🧠Three things a limiter needs
Who to count (user id, API key, IP address), how much is allowed (for example 100 per minute), and what to do when the limit is passed (reject, slow down or queue).

03Real-Life Example

🍡The Bank Counter
A bank has one counter. If one customer asks 200 questions, nobody else gets served. So the bank says: β€œEach customer gets 5 minutes. Then you go back in the line.” The line stays fair and the clerk does not burn out.
Bank counter
API
Customer
User, app or IP address
Clerk
Your server
β€œ5 minutes each” rule
Rate limit (for example 100 requests per minute)
β€œPlease go back in the line”
HTTP 429 and a Retry-After header
VIP customers get 20 minutes
Paid plans get higher limits

04Why Do We Need It?

πŸ›‘οΈProtect from overload
A flood of requests can crash the system. A limit keeps it healthy.
βš–οΈBe fair
One heavy user should not slow down everyone else.
πŸ€–Stop abuse
Bots, scrapers and password guessing are slowed down a lot.
πŸ’°Control cost
Every request costs CPU, database work and sometimes a paid call to another service.
🧾Sell plans
Free plan: 100 calls a day. Paid plan: 10,000 a day.
πŸ”Stop retry storms
A broken client that retries in a loop is slowed down.
Rate limiting is a seat belt for your API. You hope you never need it, and you are glad it is there.

05Where Do We Use It?

πŸ”‘Public APIs
Limits per API key, for example requests per minute.
πŸ”Login pages
Only a few password tries per minute. Stops password guessing.
πŸ“¨SMS and email sending
Each message costs money, so cap it.
πŸ”Search and autocomplete
Heavy queries need a ceiling.
🧱API gateways
The usual home: one place to apply limits for all services.
πŸ”ŒService to service
Protect a small service from a big neighbour.

Where in the system?

🌍CDN / edgefirst line of defence
πŸšͺAPI gatewaymost common
πŸ–₯️App codeper feature rules
πŸ—„οΈDatabaseconnection limits

06Types / Parts / How It Works

There are four classic algorithms. Each one counts in a different way.

Four ways to count
Fixed window
0-10scount: 5/5
10-20scount: 0/5
Reset at each block
Sliding window
last 10s from nowcount what is inside
Window moves with time
Token bucket
πŸͺ™tokens refill steadily
↓each request takes 1
Leaky bucket
πŸͺ£requests wait in bucket
↓leaves at a steady speed
Token bucket and leaky bucket both use a bucket. One allows bursts, the other smooths them.
AlgorithmHow it worksGoodNot so good
Fixed windowCount per time block (for example per minute). Reset at the start of each block.Very simple, tiny memoryEdge burst: 100 at 12:00:59 plus 100 at 12:01:00 = 200 in 2 seconds
Sliding windowCount requests in the last N seconds from now (a log of timestamps, or two weighted counters).No edge burst, smooth and fairUses more memory or more math
Token bucketA bucket holds tokens. A request takes one. Tokens refill at a fixed rate up to a maximum.Allows short bursts, simple, very popularTwo numbers to tune (size and refill rate)
Leaky bucketRequests join a queue and leave at a constant rate. A full queue drops new requests.Smooth, steady output to the backendBursts wait or get dropped; old requests can be stuck behind the queue
πŸ’‘Which one?
Not sure? Token bucket is the usual first choice: it is easy and friendly to normal bursts. Use a sliding window when exact fairness matters.
VisualizerFire requests at a rate limiterPick an algorithm, send a burst, then wait and send again. Time is simulated.
Algorithm
πŸ“±Clientsends requests
→↓
🚦Rate limitertoken bucket
⇒⇣
πŸ–₯️API serverprotected
Tokens left5 / 5
Last 0 requests (newest on the right)
None yet. Press β€œSend 1 request”.
Clock
0s
simulated
Allowed
0
200 OK
Rejected
0
429
A bucket holds up to 5 tokens. Each request takes one. 1 token is added every 2 seconds. Bursts are fine until the bucket is empty.

07How to Use It / Steps / Implementation

Design steps

  1. 1
    Pick the key to count
    User id when logged in, API key for apps, IP address for anonymous traffic.
  2. 2
    Pick the rule
    For example 100 requests per minute, with a burst of 20. Different rules for different routes (login is stricter than reading).
  3. 3
    Pick the algorithm
    Token bucket is a good default.
  4. 4
    Keep the counters in fast shared storage
    With many servers, the counts must be shared, for example in Redis. Use an atomic operation so two servers cannot both read β€œ4” and both allow the 5th.
  5. 5
    Answer clearly when refusing
    Send 429 and tell the client when to come back.
  6. 6
    Watch and tune
    Track how many requests are refused. Too many refused may mean the limit is too low, or a client is broken.

What a good 429 response looks like

HeaderMeaning
Retry-After: 30Try again after 30 seconds
X-RateLimit-Limit: 100Your limit in this period (a common header name, not a strict standard)
X-RateLimit-Remaining: 0Requests you have left
X-RateLimit-Reset: 1700000060When your count resets (often a Unix time)

Where to keep the counters

Local counters
in each server's memory
  • Very fast, no network
  • With 5 servers, a user may get 5 times the limit
  • Fine for rough protection
Shared counters
for example Redis
  • One true count for all servers
  • A small network call per request
  • The store must stay up (decide: fail open or fail closed)

08Key Terms to Know

TermMeaning in easy words
Rate limitThe maximum number of requests allowed in a time period
ThrottlingSlowing a caller down (or delaying their requests) instead of refusing them
429 Too Many RequestsThe HTTP status code for β€œyou went over the limit”
Retry-AfterA header that tells the client how long to wait
BurstA short spike of many requests at once
WindowThe time period that is being counted
Token bucketA bucket that refills with tokens; each request spends one
Leaky bucketA queue that lets requests out at a steady speed
QuotaA longer-term cap, for example 10,000 calls per month
Fail open / fail closedIf the limiter breaks: let everything in (open) or block everything (closed)

09Pros, Cons and Trade-offs

βœ… Pros
  • Keeps the system up under heavy or bad traffic
  • Fair share for everyone
  • Slows down bots and password guessing
  • Makes costs predictable
  • Lets you sell different plans
⚠️ Cons
  • A real user can be blocked by mistake (shared office IP)
  • Needs shared fast storage when you have many servers
  • One more thing to tune and monitor
  • Clients must handle 429 properly
  • Adds a little delay to every request

Trade-offs

ChoiceWe gainWe lose
Limit per IPWorks for anonymous usersMany people can share one IP (office, school, mobile network)
Limit per user or keyFair and exactNeeds login or a key first
Strict limitStrong protectionMore blocked real users
Fail openUsers are never blocked by a broken limiterNo protection while it is broken

10Common Problems and Mistakes

Common mistakes

  1. Counting only per server. With many servers, each one has its own count, so the real limit is much higher than you set.
  2. Race conditions. Two servers read the count at the same time and both allow the last request. Use an atomic increment.
  3. Using only the IP address. A whole office can be blocked, and an attacker with many IPs gets through.
  4. No Retry-After. Clients retry at once and make it worse. Good clients wait and use exponential backoff.
  5. Same limit for every route. Login and password reset need much tighter limits than reading a page.
  6. Forgetting the limiter can fail. Decide in advance what happens when the counter store is down.
🧨Edge burst
Fixed windows allow double the limit around a boundary.
πŸ”₯Hot key
One very busy key hammers one counter in the store.
πŸ•°οΈClock differences
Servers with different clocks count windows differently. Use the store's clock.
🌐Many regions
A global limit across regions is slow. Often each region gets its own share.

11Real-World Examples

πŸ™Public developer APIs
Most big APIs publish limits per key or per user and answer 429 when passed.
πŸ’³Payment APIs
Limits protect the service and also stop card-testing bots.
πŸ”Login systems
A few tries, then a wait or a CAPTCHA.
☁️Cloud gateways and CDNs
Offer built-in rate limiting rules you can switch on.
πŸ“²OTP / SMS sending
Strict caps per phone number and per hour.
πŸ”ŽSearch services
Heavy queries are limited per user.
πŸ“Note
These are general ideas. Each company picks its own numbers and algorithm, and does not always publish them.
Many servers, one shared counter
πŸ“±User
→↓
πŸšͺGateway 1
πŸšͺGateway 2
πŸšͺGateway 3
↔count++
⚑Redisshared counters
Client Limiter Shared store
All gateways ask the same fast store, so the user cannot get 3 times the limit by hitting 3 servers.

12Related Topics to Read Next

Authentication vs Authorization→

Limits are often counted per user or per API key, so you need to know who is calling.

What are Load Balancers?β†’

A load balancer shares traffic. A limiter decides how much traffic is allowed in.

Scalability→

Rate limiting helps a system survive spikes while it scales.

Message Queues→

A queue can smooth out bursts, similar to a leaky bucket.

Idempotency→

Clients that retry after a 429 need requests that are safe to repeat.

Reliability→

A system that sheds extra load stays correct under pressure.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: cap how many requests one caller can make in a period.
  • βœ”Refuse with: HTTP 429 and a Retry-After header.
  • βœ”Four algorithms: fixed window, sliding window, token bucket, leaky bucket.
  • βœ”Default choice: token bucket (simple, allows bursts).
  • βœ”Fixed window problem: edge burst, up to double the limit at the boundary.
  • βœ”Many servers: shared counters (Redis) and atomic updates.
  • βœ”Count by: user id, API key or IP. Use stricter rules for login.
  • βœ”Decide early: fail open or fail closed if the limiter breaks.
  • βœ”One line: β€œA rate limiter says no early and politely, so the system can keep saying yes to everyone else.”
← Previous
Bulk APIs and File Upload
Next β†’
Authentication vs Authorization