Fixed-Window Rate Limiter
Medium · Security
Rate limiters like express-rate-limit protect an API from too many requests. Write rateLimit(requests, { limit, windowMs }) using a fixed window per IP.
- requests is [{ ip, time }] sorted by time (in ms).
- Windows are aligned to multiples of windowMs: a request belongs to the window starting at Math.floor(time / windowMs) * windowMs.
- Each IP may make limit requests per window. Allowed requests get { status: 200 }.
- Requests over the limit get { status: 429, retryAfter }, where retryAfter is the number of seconds until the window ends, rounded UP (like the Retry-After header). Rejected requests do not count.
- Different IPs have separate counters.
Next: TTL Cache