Skip to Content
Mengty Learns
Security

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.

explanationintermediateTested with asvs 5.0.0 (V2, V6, V15), rfc RFC 9110 (429 / Retry-After)Updated Nov 26, 2026

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

TL;DR

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.

Edge limits absorb raw IP floods; application limits protect expensive actions per user or account.

Solution

Combine the right algorithm, key, and enforcement point:

AlgorithmHow it worksBest for
Fixed WindowCounter resets every $N$ seconds.Simple coarse quotas (beware 2× boundary bursts).
Sliding WindowWeighted or rolling log over the last $N$ seconds.Smooth API quotas with no boundary spikes.
Token BucketBucket 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-For from untrusted clients), login/reset routes by IP + normalized account identifier, and authenticated APIs by user ID / API key.
  • Response: Return 429 Too Many Requests with Retry-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)

Overview of Token Bucket Rate Limiter (Allow vs 429 Retry-After). 8 steps.
Overview8 steps in this flow

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

When to use
  • 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.
When to avoid
  • 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

Pros
  • 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.
Cons
  • 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