Implementing Rate Limiting

1. Using Token Bucket Algorithm

PropertyValue
CapacityMax tokens (burst size)
Refill rateTokens added per second
BehaviorEach request consumes 1 token; reject if empty
ProsAllows bursts, smooth average

2. Using Fixed Window Algorithm

PropertyValue
WindowFixed time slot (e.g. each minute)
CounterResets at window boundary
ProsSimple, low memory
ConsBoundary burst (2x limit at window edge)

3. Using Sliding Window Algorithm

VariantHow
Sliding logStore timestamps; count in last N sec; accurate, memory-heavy
Sliding counterWeighted blend of current+previous fixed windows; approximate, low memory

4. Implementing Per-User Rate Limits

KeyNotes
userId / API keyAuthenticated requests
IP addressAnonymous; account for NAT/proxies
userId + endpointPer-endpoint quotas

5. Implementing Per-IP Rate Limits

Warning: X-Forwarded-For can be spoofed. Trust only from your load balancer; use the client's connecting IP at edge.
Use CaseLimit
Login endpoint5-10 / minute / IP
Public read60-100 / minute / IP
Anonymous abuseStricter; combine with CAPTCHA

6. Using X-RateLimit Headers

HeaderValue
X-RateLimit-LimitTotal per window
X-RateLimit-RemainingRemaining count
X-RateLimit-ResetUnix epoch when reset
RateLimit NEW (RFC 9239)limit=100, remaining=42, reset=30

7. Returning 429 Status Code

Example: Rate Limit Exceeded

HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json
Retry-After: 60
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1747304460

{
  "type": "https://example.com/errors/rate-limit",
  "title": "Rate Limit Exceeded",
  "status": 429,
  "detail": "100 requests/minute exceeded; retry in 60s"
}

8. Implementing Retry-After Header

FormatExample
Seconds (delta)Retry-After: 120
HTTP dateRetry-After: Sat, 15 May 2026 10:30:00 GMT
When to send429, 503, 3xx redirects

9. Providing Rate Limit Information

On Every ResponseWhy
X-RateLimit-RemainingClients pace themselves preemptively
X-RateLimit-ResetPredictable backoff
DocumentationLimits per tier published

10. Implementing Tiered Rate Limits

TierLimit
Anonymous60 / hour
Free5,000 / hour
Pro50,000 / hour
EnterpriseCustom (SLA-based)

11. Handling Burst Traffic

TechniqueEffect
Token bucket with high capacityPermit short bursts
Leaky bucketSmooth output; queue excess
Backpressure (429 + Retry-After)Push load back to client
Auto-scale workersAbsorb sustained surges