Practice & Assessment
Test your understanding of Rate Limiting and Throttling
Multiple Choice Questions
6A client sends 95 requests at 11:59:55 and 95 requests at 12:00:05. The limit is 100 per minute with fixed window. How many total requests are allowed?
Why should rate limit counters NOT be stored in server process memory when the API runs on multiple instances?
A token bucket has capacity 50 and refill rate 10 tokens/sec. A client idles for 10 seconds then sends 60 requests instantly. How many are allowed?
Why is a Lua script used for atomic rate limit operations in Redis rather than separate INCR and EXPIRE commands?
Which rate limiting algorithm is most appropriate for forwarding requests to a downstream payment processor at a strictly constant rate?
The Retry-After header on a 429 response is recommended. What critical information does it provide?
Coding Challenges
1Implement sliding window rate limiter with Redis
Write an Express middleware function rateLimiter(limit, windowMs) implementing the sliding window log algorithm using Redis sorted sets. Each request stores a timestamp in a sorted set keyed by client IP. On each request: remove entries older than windowMs, check count against limit, add current timestamp if allowed, set key TTL. Return 429 with Retry-After header (seconds until oldest entry expires) if over limit; otherwise set X-RateLimit-Remaining header. Input: HTTP requests with client IP. Output: 200 with rate limit headers or 429 with Retry-After header. Estimated time: 25-30 minutes.
Mini Project
Tiered Rate Limiting API Gateway Middleware
Build rate-limiting middleware for Express supporting multiple tiers: Anonymous (no API key) 20 req/min, Free tier API keys 100 req/min, Pro tier API keys 1000 req/min. Use fixed-window algorithm backed by Redis with Lua scripts for atomicity. Implement GET /api/keys to create API keys with a specified tier stored in a Redis hash. Every response must include X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers. 429 responses must include Retry-After. Add GET /api/admin/usage protected by a master admin key returning top 10 API keys by request count in the current window. Demonstrate under concurrent load that limits are enforced globally across multiple server instances.
