FullStack AI Hub
Studio
System Design · 05. Reliability
11 min
11 steps
Beginner

Rate Limiting

Protect APIs from bot floods and noisy neighbors with token buckets, sliding windows, atomic Redis Lua counters, and HTTP 429 backoff.

System Design05. ReliabilityLesson 1 of 4
11 minBeginner11 steps

Rate Limiting

Protect APIs from bot floods and noisy neighbors with token buckets, sliding windows, atomic Redis Lua counters, and HTTP 429 backoff.

TOTAL RPS
4,600/s
BOT SHARE
74%
P95 LATENCY
1,180 ms
DB LOAD
98%
unthrottled1,200/sScraper Bot3,400/s floodSearch API96%Primary DB98%STARVEDNo edge quota: bot floods straight through
allowed request
bot burst / surge
Redis Lua quota sync
HTTP 429 rejected
In This LessonStep 1 of 11
What You Will Master
  • ✓Choose between Fixed Window, Sliding Window, Token Bucket, and Leaky Bucket algorithms
  • ✓Enforce accurate distributed quotas across multiple gateways using atomic Redis Lua scripts
  • ✓Shape client traffic cleanly with HTTP 429 Retry-After headers, jittered backoff, and tiered quotas
  • ✓Decide consciously between Fail-Open and Fail-Closed behavior when the rate-limit store fails

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Token BucketGeneral public APIs allowing short user burstsTwo parameters (burst + refill); bursts still reach backend briefly
Leaky BucketStrict smooth outflow into fragile downstream partnersQueues bursts and adds latency; recent traffic waits behind old queue
Sliding Window CounterMemory-efficient fairness without boundary 2× spikesSlight approximation using weighted previous-window overlap
Redis Atomic LuaConsistent global quotas across horizontally scaled gatewaysAdds 1–2 ms Redis RTT; requires explicit Fail-Open/Closed policy

Step-by-Step Architectural Breakdown (11 Steps)

Full architectural walkthrough transcript and state transitions for Rate Limiting.

STEP 01 · PROBLEMJump to step →

One scraper bot starves every paying user

Your public API normally handles **1,200 req/s** from legitimate apps. Suddenly a misconfigured partner script enters a tight retry loop and fires **3,400 req/s** at your search endpoint.

With no rate limiter at the edge, that single noisy neighbor saturates both **API Servers** and **Primary DB (98% CPU)**—taking every paying customer down with it.

watch:Rate limiting is not just for malicious DDoS attacks—most production API floods come from accidental retry loops inside your own clients.

Noisy NeighborDenial of ServiceEdge Protection
STEP 02 · TECHNIQUEJump to step →

Fixed Window Counter & the 2× edge-burst flaw

The simplest guard is a **Fixed Window Counter** at the API Gateway: allow up to **1,500 requests per 60-second bucket** (`12:00`, `12:01`, …) and reject anything above with **HTTP 429**.

It takes just one integer per key, but hides a classic flaw: a burst of 1,500 requests at **12:00:59** followed by 1,500 at **12:01:01** slips **2× the allowed rate** through in 2 seconds!

watch:Fixed Window counters let savvy or synchronized clients double your intended rate right across minute boundaries.

Fixed Window CounterBoundary Burst FlawEdge Rejection
STEP 03 · SOLUTIONJump to step →

Eliminate boundary spikes with Sliding Window Counter

A **Sliding Window Counter** keeps just two numbers per client: the **previous minute’s count** and the **current minute’s count**. At 15 seconds into the new minute, it weights the previous bucket by **75%** plus 100% of the current bucket.

That one weighted sum (`0.75 × prev + curr`) eliminates the 2× boundary loophole while using almost **zero extra memory** compared to storing every request timestamp.

good:Cloudflare’s production edge uses Sliding Window Counters—within 0.003% of an exact timestamp log at a fraction of the RAM.

Sliding Window CounterWeighted OverlapMemory Efficiency
STEP 04 · TECHNIQUEJump to step →

Token Bucket: allow healthy user bursts

Real users are naturally bursty: opening a dashboard fires **12 API calls at once**, then goes quiet for 30 seconds. **Token Bucket** models each user’s quota as a bucket holding up to `B` tokens that refills at steady rate `R` tokens/sec.

Each request spends 1 token. Saved tokens let short bursts fly through with **zero artificial delay**, while sustained abuse drains the bucket empty and hits **HTTP 429**.

good:Token Bucket is the default choice at AWS API Gateway and Stripe because it feels snappy to bursty humans while capping sustained abuse.

Token BucketBurst Capacity (B)Refill Rate (R)
STEP 05 · TRADE-OFFJump to step →

Leaky Bucket: smooth jagged spikes into steady drips

What if a legacy banking partner crashes whenever it sees even a 1-second burst? **Leaky Bucket** puts incoming requests into a **fixed-size FIFO queue** and drips them downstream at an **exact constant rate**.

Downstream load becomes flat as a ruler, but the trade-off is **added queueing latency**: during a spike, fresh requests sit waiting behind older queued ones—and overflow drops with 429.

idea:Pick Token Bucket when you want fast bursts; pick Leaky Bucket when downstream systems require a strictly constant outflow rate.

Leaky BucketTraffic ShapingConstant Outflow Rate
STEP 06 · SOLUTIONJump to step →

Distributed rate limiting with Redis + Lua

In production you run **multiple API Gateways** behind a Load Balancer. If each gateway keeps counters in local RAM, a client allowed 100 req/s can sneak **300 req/s** across 3 gateways!

Instead, every gateway shares a centralized **Redis Quota Store**. Executing the token refill + decrement inside a single **Redis Lua script** makes it atomic in **1.2 ms** with zero race conditions.

good:Redis executes Lua scripts single-threaded and atomically—eliminating check-then-set race conditions across dozens of gateways.

Distributed QuotaRedis Atomic LuaShared Counter Store
STEP 07 · TRADE-OFFJump to step →

Race conditions & local-sync latency trade-offs

Naive code that runs `GET count` then `SET count + 1` in two round-trips suffers from a **classic race condition**: two concurrent requests both read `99`, both pass, and your limit leaks.

Atomic **Redis Lua** fixes races in 1 RTT. At massive global scale (1M+ RPS), gateways can even **batch-sync local counters every 500 ms**—trading tiny ~2% quota drift for zero per-request Redis latency.

idea:Use Atomic Redis Lua for strict billing/login limits; use periodic async batch sync for high-volume edge DDoS protection.

Check-Then-Set RaceAtomic Lua ScriptEventual Quota Sync
STEP 08 · TECHNIQUEJump to step →

Speak HTTP 429 + Retry-After + Jittered Backoff

Never silently drop throttled requests or return generic 500s—clients interpret 500s as server crashes and retry aggressively. Return **`429 Too Many Requests`** along with standard **`X-RateLimit-Remaining`** and **`Retry-After`** headers.

Well-behaved SDKs honor `Retry-After` and apply **Exponential Backoff + Random Jitter** so thousands of throttled clients do not all wake up and slam your API on the exact same second.

good:Jitter is essential: synchronized retries without randomness turn one rate-limit wave into repeating thundering herds.

HTTP 429 Too Many RequestsRetry-After HeaderExponential Backoff + Jitter
STEP 09 · TECHNIQUEJump to step →

Multi-tier quotas: isolate Free vs Enterprise tenants

One global rate limit treats a free-tier hobby script the same as a $100k/year Enterprise tenant. Production gateways stack **layered rules**: a coarse **IP limit** at the CDN edge, plus **per-API-key tiered limits** (`Free: 20 req/s`, `Pro: 500 req/s`).

Even if ten thousand free accounts spike simultaneously, their bucket caps independently—**Enterprise traffic sails through unaffected**.

good:Always key rate limits by Authenticated Tenant/API Key first, and fall back to Client IP only for unauthenticated login/signup routes.

Per-Tenant QuotasLayered IP + API Key LimitsTenant Isolation
STEP 10 · TRADE-OFFJump to step →

When Redis dies: Fail-Open vs Fail-Closed

What should your API Gateway do if the **Redis Rate Limiter crashes**? **Fail-Open** lets requests pass through without quota checks (preserving uptime for paying users, but temporarily exposing backends to abuse).

**Fail-Closed** rejects all traffic with 503 until Redis recovers (protecting strict security/billing endpoints like login or LLM token spend, at the cost of immediate downtime).

watch:Default to Fail-Open + a local in-memory fallback cap for customer-facing APIs, and Fail-Closed only for strict security or paid-metering gates.

Fail-OpenFail-ClosedLocal Fallback Limiter
STEP 11 · RECAPJump to step →

Production edge & distributed rate-limiting blueprint

A complete rate-limiting defense combines **Token Bucket** (or Sliding Window Counter) quotas enforced across **redundant Edge Gateways**, backed by **Atomic Redis Lua**, returning clear **`429 Retry-After`** headers with a **local Fail-Open fallback**.

Launch a 2.2× bot flood while killing Gateway A below to verify that your backend fleet stays completely calm.

good:Enforce per-tenant Token Buckets via Redis Lua, communicate 429 + Retry-After clearly, and add a local in-memory fallback so Redis blips never take down your API.

Edge Rate-Limit BlueprintToken Bucket + Lua429 Backoff + Fallback

Related Production Deep-Dives & Simulators

Related Systems Course
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.