Implementing Rate Limiting and Throttling

1. Understanding Brute-Force Attacks

TypeDetail
Password sprayingOne password across many accounts
Credential stuffingLeaked credentials from other breaches
EnumerationProbe for valid usernames
MitigationRate limit + lockout + MFA + CAPTCHA

2. Implementing Login Rate Limiting

Example: Express + Redis

import rateLimit from "express-rate-limit";
import RedisStore from "rate-limit-redis";

app.post("/login", rateLimit({
  store: new RedisStore({ sendCommand: (...a) => redis.call(...a) }),
  windowMs: 15 * 60_000, max: 5,
  keyGenerator: (req) => req.body.email + ":" + req.ip,
  standardHeaders: true
}), loginHandler);

3. Using IP-Based Rate Limiting

AspectDetail
ProCatches unauthenticated abuse
ConNAT (corporate, mobile carriers) — false positives
CDNUse True-Client-IP / CF-Connecting-IP; trust only proxy

4. Implementing User-Based Rate Limiting

KeyDetail
AuthenticatedBy user ID
AnonymousFall back to IP / fingerprint
Combined(user + IP) tuple

5. Using Sliding Window Algorithm

AlgorithmDetail
Fixed windowBursty at boundary
Sliding logAccurate but memory-heavy
Sliding window counterApproximation — best balance
Token bucketAllows bursts up to capacity
Leaky bucketSmooth output rate

6. Implementing Token Bucket Algorithm

Example: Redis Lua

-- KEYS[1]=bucket, ARGV: now, rate, capacity, cost
local b = redis.call("HMGET", KEYS[1], "tokens","ts")
local tokens = tonumber(b[1]) or tonumber(ARGV[3])
local ts = tonumber(b[2]) or tonumber(ARGV[1])
tokens = math.min(tonumber(ARGV[3]), tokens + (ARGV[1]-ts)*ARGV[2])
if tokens < tonumber(ARGV[4]) then return 0 end
tokens = tokens - ARGV[4]
redis.call("HMSET", KEYS[1], "tokens", tokens, "ts", ARGV[1])
return 1

7. Using Rate Limit Headers

HeaderStandard
RateLimit-Limitdraft-ietf-httpapi-ratelimit-headers
RateLimit-RemainingSame
RateLimit-ResetSeconds to reset
Retry-AfterRFC 9110 — on 429/503

8. Implementing Progressive Delays

AttemptDelay
1-30
41s
52s
6+Exponential (2^n) up to cap

9. Handling Rate Limit with CAPTCHA

ServiceDetail
reCAPTCHA v3Score-based, invisible
hCaptchaPrivacy-focused
Cloudflare TurnstilePrivacy-first, no puzzle
Apple Private Access TokensRFC 9577 — anonymous client attestation

10. Implementing Distributed Rate Limiting

ApproachDetail
Redis clusterSingle source for counters
Sliding window in RedisZADD + ZREMRANGEBYSCORE
EdgeCloudflare/Fastly rate limit rules
SidecarEnvoy ratelimit service