SitePoint18 min readtutorialintermediate
Building Distributed Sliding-Window Rate Limiters in TypeScript and Redis
Summary
This guide details building a distributed sliding-window rate limiter using TypeScript and Redis. It leverages Redis sorted sets and an atomic Lua script to prevent race conditions and over-admission under high concurrency, supporting dual RPM/TPM quotas.
- Atomic operations via Lua scripts are critical for distributed rate limiting to avoid time-of-check-to-time-of-use (TOCTOU) race conditions.
- The sliding-window log uses Redis sorted sets, storing request timestamps as scores and encoding costs within member strings.
- A single Lua script atomically prunes expired entries, sums current costs, conditionally admits new requests, and sets key expiry.
- Use `EVALSHA` for script execution performance, with a fallback to `EVAL` if the script isn't cached; `MULTI/EXEC` is insufficient for read-then-write logic.
Engineers building robust distributed services need to understand how to implement correct rate limiting without race conditions, which this article addresses with a concrete, production-ready solution.
7/10




