Stage 3 · Build
Caching, Queues & Background Jobs
Rate Limiting
Implement token buckets, leaky buckets, per-user quotas, Redis counters, and HTTP 429 responses.
Why Rate Limit
Rate limiting protects your API from abuse, ensures fair usage, and prevents cascading failures. Without rate limits, a single client can exhaust your resources and cause downtime for all users.
Token Bucket
The token bucket algorithm adds tokens at a fixed rate. Each request consumes a token. When the bucket is empty, requests are rejected. This allows bursts while enforcing an average rate.
Sliding Window
Per-User Quotas
Redis Counters
Redis provides atomic counters that work across multiple application instances. INCR is atomic and fast. Combined with EXPIRE, it implements rate limiting without locks.
HTTP 429 Responses
When rate limiting kicks in, return HTTP 429 Too Many Requests. Include headers that tell the client when to retry. This helps clients implement proper backoff logic.
Rate limit by IP for anonymous endpoints. Rate limit by user ID for authenticated endpoints. Rate limit by API key for third-party integrations. Use different limits for different tiers.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.