Rate Limiting & Brute-Force Protection
Token bucket vs fixed/sliding window algorithms, edge vs application enforcement, choosing rate-limit keys, and returning 429 Too Many Requests with Retry-After.
TL;DR
Rate limiting caps request rates per key (IP, user ID, API token, or email) to stop brute force, credential stuffing, and resource exhaustion. Use Token Bucket for controlled bursts or Sliding Window for smooth limits, enforce coarse limits at the edge and business limits in the app, and return 429 Too Many Requests with Retry-After.
Intent
Pick the right rate-limiting algorithm and key, place enforcement at both the edge and application layers, and signal backoff cleanly with 429 + Retry-After.
Problem
Without rate limits, an attacker can run millions of password guesses against /login, exhaust DB connections with expensive search queries, or rack up third-party SMS/AI bills. Conversely, a naive IP-only fixed-window limit can block an entire office behind one NAT IP or allow 2× bursts at minute boundaries.
Solution
Combine the right algorithm, key, and enforcement point:
| Algorithm | How it works | Best for |
|---|---|---|
| Fixed Window | Counter resets every $N$ seconds. | Simple coarse quotas (beware 2× boundary bursts). |
| Sliding Window | Weighted or rolling log over the last $N$ seconds. | Smooth API quotas with no boundary spikes. |
| Token Bucket | Bucket holds up to $B$ tokens, refilling at $R$/sec; each request consumes 1 (or $cost$) tokens. | Legitimate UI bursts (loading a dashboard) with a steady average rate. |
- Keys: Key unauthenticated routes by client IP (from a trusted proxy header, never a spoofable
X-Forwarded-Forfrom untrusted clients), login/reset routes by IP + normalized account identifier, and authenticated APIs by user ID / API key. - Response: Return
429 Too Many RequestswithRetry-After: <seconds>so well-behaved clients back off instead of retrying in a tight loop.
Real-world analogy
▶ Flow: watch it work
Token Bucket Rate Limiter (Allow vs 429 Retry-After)
Press Start or tap any step dot to trace the path.
▸All steps (8)
Code
An in-memory token bucket (suitable for single-instance demos; use atomic Redis Lua scripts in multi-instance production):
// SAFE: token bucket with explicit capacity, refill rate, and Retry-After calculation
type Bucket = { tokens: number; updatedAt: number };
const buckets = new Map<string, Bucket>();
export function checkTokenBucket(
key: string,
capacity = 5,
refillPerSec = 0.5,
now = Date.now(),
): { allowed: boolean; retryAfterSec: number } {
const b = buckets.get(key) ?? { tokens: capacity, updatedAt: now };
const elapsedSec = Math.max(0, (now - b.updatedAt) / 1000);
const tokens = Math.min(capacity, b.tokens + elapsedSec * refillPerSec);
if (tokens < 1) {
buckets.set(key, { tokens, updatedAt: now });
return { allowed: false, retryAfterSec: Math.ceil((1 - tokens) / refillPerSec) };
}
buckets.set(key, { tokens: tokens - 1, updatedAt: now });
return { allowed: true, retryAfterSec: 0 };
}When to use / when to avoid
- Enforce tight limits on authentication, password reset, OTP verification, and expensive search/export routes.
- Use atomic store operations (Redis Lua/MULTI) so concurrent requests cannot race past the cap.
- Return 429 with Retry-After and fail safely (or alert) if the rate-limit store is unreachable.
- Never trust client-supplied X-Forwarded-For headers unless your trusted reverse proxy strips and rewrites them.
- Do not use IP-only limits for sensitive endpoints without also keying on account/token.
How to implement
Configure edge limits first
Enable Cloudflare/WAF/Nginx rate-limiting rules to drop volumetric floods at the perimeter.
Add route-specific app limits
Apply tighter token-bucket or sliding-window limits on /login, /forgot-password, and /api/export.
Emit 429 and monitor spikes
Return 429 Too Many Requests with Retry-After and alert on sustained 429 surges.
Pros / Cons
- Token bucket accommodates natural UI request bursts while enforcing a strict long-term average.
- Layered edge + app limits protect both infrastructure bandwidth and business logic.
- Distributed rate limiting adds a Redis/edge hop and requires careful fail-open vs fail-closed decisions.
- Shared NATs (universities, mobile carriers) can trigger false positives on IP-only keys.
Relations
Check yourself
Check Yourself
1. Why should an application never trust X-Forwarded-For directly without configuring trusted proxy hops?
2. Which HTTP status code and header tell a rate-limited client to back off and when to try again?
Sources
Related Notes
Secure File Uploads & Downloads
How to validate uploaded files by content, enforce size limits, store outside the web root with randomized names, scan for malware, and serve safely with Content-Disposition.
Secrets Management & CI OIDC
Environment variables vs secret managers, secret rotation, what to do if a secret is committed to Git, and replacing long-lived CI keys with OIDC.