Implement rate limiting en prevent brute-force attacks
Rate limiting caps le nombre de requests per time window, preventing brute-force, credential stuffing, et DoS attacks. Apprendre jeton bucket et sliding window algorithmes.
- 1
Rate limiting restricts how many requests a client can make in a time window. Common algorithms: (1) Fixed window — simple but allows bursts at window boundaries; (2) Sliding window — smoother, tracks requests in a rolling window; (3) Token bucket — allows bursts up to a capacity, refills at a steady rate.
- 2 Calculatrice de hash →
Hash the client identifier (IP, user ID, API key) to use as a rate limit key. Use SHA-256 to avoid storing raw IPs. The hash maps to a counter in a fast store (Redis, in-memory map).
- 3 Générateur HMAC →
Sign the rate limit state (count, window start) with an HMAC to prevent tampering. If using client-side rate limiting (e.g., JWT-based), the signed token prevents the client from resetting their own counter.
- 4
For brute-force protection on login: limit to 5 attempts per 15 minutes per account, and 10 per IP. Use exponential backoff — each failed attempt increases the wait time. After 5 failures, lock the account and require email verification. For API rate limiting: 100 requests/minute for free tier, 1000 for paid. Return 429 Too Many Requests with a Retry-After header.
Questions fréquentes
- Token bucket vs sliding window?
- Token bucket allows controlled bursts (up to bucket capacity) then steady-state rate — good for APIs where occasional bursts are acceptable. Sliding window enforces a strict limit in any window — better for security-critical endpoints like login. Choose based on whether bursts are acceptable.
- How do I handle distributed rate limiting?
- Use a shared store (Redis, Memcached) so all servers see the same counters. For high throughput, use a sliding window with Lua scripting in Redis (atomic check-and-increment). For global rate limiting at the edge, use CDN features (Cloudflare, AWS WAF).