Redis for Cache, Locks, and Rate Limiting
Three production patterns that cut database load, prevent race conditions, and protect APIs from abuse.
Redis is more than a cache. On high-traffic Node.js backends I use it for caching hot reads, distributed locks, and rate limiting—often in the same cluster with clear key prefixes.
1. Cache
Pattern: Cache-aside. Read Redis first; on miss, read DB and set TTL (e.g. 60–300s).
Tips:
- Version keys when schema changes:
user:123:v2. - Avoid caching highly personalized or rapidly changing data.
- Monitor hit ratio; low hit rate means wrong keys or TTL.
Impact: I have seen 30–50% DB load reduction on read-heavy endpoints after tuning cache keys and TTLs.
2. Distributed locks
Pattern: SET key token NX EX 30 before critical section; release with Lua compare-and-delete.
Use for: Campaign sends, inventory holds, single-flight invoice generation.
Caution: Always set expiry. Use Redlock only if you understand the trade-offs; for many apps a single Redis primary with short TTL is enough.
3. Rate limiting
Pattern: Sliding window or token bucket per userId / IP / apiKey.
Headers: Return X-RateLimit-Remaining so clients backoff.
Impact: Protects downstream providers (SMS, email) and prevents one tenant from starving others in multi-tenant SaaS.
Operations
- Use connection pooling in Node (
ioredis). - Define key naming conventions in team docs.
- Alert on memory usage and eviction policy (
volatile-lruvsnoeviction).
Takeaway
Redis is a force multiplier when used deliberately—not as a dumping ground for every object. Pick one use case per service path, measure, then expand.