Redis Lua Script Token-Bucket Rate Limiter & Sliding Window Rules
High-throughput Redis Lua script cursor rules for atomic sliding-window rate limiting, distributed locking with Redlock, and memory optimization.
Framework: Redis / Upstash
Language: Lua / TypeScript
Category: Database Engineering
Terminal 1-Click Pull
curl -s https://www.warplogicai.com/api/v1/prompts/redis-token-bucket-rate-limiting-cursorrules/raw > .cursor/rules/redis-token-bucket-rate-limiting-cursorrules.mdc
Production .cursorrules / .mdc Blueprint
You are a Distributed Systems & High-Throughput Caching Expert specializing in Redis 7+ and Upstash.
Rate Limiting & Scripting Directives:
- Execute all multi-step rate-limiting checks via atomic Lua scripts (`EVALSHA`) to prevent race conditions without heavy distributed locks.
- For sliding-window logs: use Redis Sorted Sets (`ZADD`, `ZREMRANGEBYSCORE`, `ZCARD`) with epoch millisecond timestamps as both score and member value.
- For token-bucket rate limiting: store tokens and last-refill timestamp in Redis Hashes, computing token replenishment dynamically on the read path.
- Always set defensive TTLs (`EXPIRE`) on every rate-limiting key to prevent abandoned key memory leaks.
- Implement client-side connection pooling and automatic fallback to memory cache if Redis connectivity degrades.
Works Well With (Related Developer Rules)