Module 7: Security
Rate Limiting Algorithms
Token bucket, leaky bucket, fixed and sliding window rate limiting — dimensions, Redis counters, 429s, and where to enforce quotas.
Rate limits protect availability and fairness. Place them at gateway/edge, choose an algorithm that matches burst needs, and always tell clients when to retry.
What you will learn
- Explain why rate limits exist and where to enforce them
- Compare token bucket, leaky bucket, fixed window, and sliding window
- Pick dimensions (user, IP, API key, tenant) for quotas
- Design distributed counters (e.g. Redis) without losing the plot
- Return correct client signals (HTTP 429, Retry-After, headers)
Why rate limit?
- Unlimited clients will find a way to melt your API — accidentally or on purpose.
- Protect availability — stop one tenant from starving everyone
- Control cost — outbound SMS, LLM, and email calls are expensive
- Fairness — enforce plan quotas (free vs paid)
- Abuse defense — credential stuffing, scraping, brute force
- Buy time for autoscaling — smooth spikes instead of cliff failures
Where to enforce
- Defense in depth beats a single checkbox in one service.
- Edge/CDN — coarse IP/bot limits before origin
- API gateway — authenticated user/API-key quotas for most public APIs
- Service layer — expensive endpoints get stricter per-operation limits
- Downstream clients — apply backpressure when calling third parties
- Local in-process limits can shed load fast; global store keeps multi-instance consistency
Dimensions & identity
- What you key the counter on matters as much as the algorithm.
- userId / accountId — fair per logged-in user
- API key / client_id — partner and machine clients
- IP address — anonymous traffic (proxies/NAT make this blunt)
- tenantId — SaaS multi-tenant budgets
- Route/method — stricter on /login and /search than on health checks
- Combine dimensions: e.g. 100/min per user and 1000/min per IP
Token bucket
- The interview favorite for APIs that should allow short bursts.
- Bucket holds up to capacity tokens; refill at a steady rate
- Each request costs one (or N) tokens; reject if empty
- Bursts allowed up to the bucket size, then sustained rate kicks in
- Great default for public REST APIs
- Parameters to state: refill rate + burst capacity
Leaky bucket
- Smooths traffic into a steady outflow — think queue drained at fixed rate.
- Requests enter a bucket/queue; leak (process) at constant rate
- When full, excess requests are dropped or rejected
- Output is smoother than token bucket’s bursty edge
- Good when downstream (DB, legacy SOAP) needs steady flow
- Can add latency if you queue instead of reject
Fixed window counters
- Simple: count requests in 00:00–00:59, reset at the next minute.
- Easy in Redis INCR + TTL
- Boundary problem: double burst at window edges (end of one + start of next)
- Fine for coarse quotas; weaker when fairness at boundaries matters
- Often a first implementation before sliding windows
- Still state the edge-burst caveat in interviews
Sliding window
- Counts a rolling time horizon so boundary double-bursts shrink.
- Sliding log: store timestamps; drop entries outside the window (accurate, heavier)
- Sliding window counter: weight previous window + current (approximate, cheaper)
- Fairer than naive fixed windows for “100 requests per minute”
- Redis sorted sets or Lua scripts are common implementations
- Pick approximation when QPS is huge and exact logs are too costly
Algorithm cheat sheet
- Use this when the interviewer asks “which one and why?”
- Need bursts + simple story → token bucket
- Need smooth downstream rate → leaky bucket
- Need cheap quota with mild fairness → fixed window
- Need fairer rolling quota → sliding window
- Many gateways implement token bucket or sliding counters under the hood
Distributed enforcement
- Multiple gateway replicas must share one budget per key.
- Central store (Redis) for atomic INCR / token updates
- Use atomic scripts to avoid racey read-modify-write
- Local + global: tiny local shed for spike protection, Redis for accurate quotas
- Fail policy: fail open (availability) vs fail closed (safety) — say which and why
- Shard Redis by key hash if limit QPS is extreme
Client experience & headers
- A silent drop teaches clients to retry harder. Be explicit.
- HTTP 429 Too Many Requests on reject
- Retry-After seconds (or HTTP date) for well-behaved clients
- Optional headers: X-RateLimit-Limit / Remaining / Reset
- Document quotas in the developer portal
- Idempotent clients + jittered backoff prevent retry stampedes
Interview framing
- Use this order when abuse or noisy neighbors come up.
- Name the goal (abuse, fairness, cost) and the identity key
- Place limiters at edge/gateway (+ optional service limits)
- Pick algorithm with burst vs smooth rationale
- Store counters in Redis; mention atomicity
- Return 429 + Retry-After and cite example numbers (e.g. 100/min burst 20)
Quick revision checklist
- Limit by userId + IP + API key dimensions.
- Local + global limits for defense in depth.
- State burst size and sustained rate for token bucket.
- Call out fixed-window boundary bursts.
- Always mention HTTP 429 and Retry-After.
- Decide fail-open vs fail-closed if Redis is down.
FAQs
Where to enforce limits?
Prefer API gateway/edge for coarse limits; services may add finer per-tenant rules on expensive operations.
Token bucket vs leaky bucket?
Token bucket allows controlled bursts up to capacity. Leaky bucket emits at a steady rate and is better when downstream needs smoothing.
Why is a fixed window unfair?
A client can spend a full quota at the end of one window and another full quota at the start of the next — effectively double the rate briefly.
How do we rate limit across many servers?
Keep shared counters in Redis (or similar) with atomic updates so every replica decrements the same budget for a given key.
What should the API return when limited?
HTTP 429 with Retry-After. Optionally include limit/remaining/reset headers and document the quota.
Should we fail open if Redis is down?
It depends. Fail open preserves availability but risks abuse; fail closed protects the system but may outage everyone. State the product choice.
Learner’s Task
- Practice out loud for 8–10 minutes. Add rate limiting to a public API design.
- Pick an API (URL shortener create or login) and state the goal: abuse, fairness, or cost.
- Choose identity dimensions and where enforcement lives (edge/gateway/service).
- Pick token bucket or sliding window; give example numbers (rate + burst/window).
- Explain Redis counters + what the client sees on 429.
- Write a 4-sentence closing: placement, algorithm, dimension, and fail-open/closed choice.