Redis Patterns
Quick reference for Redis best practices across common backend use cases.
How It Works
Redis is an in-memory data structure store that supports strings, hashes, lists, sets, sorted sets, streams, and more. Individual Redis commands are atomic on a single instance; multi-step workflows require Lua scripts, MULTI/EXEC transactions, or explicit synchronization to stay atomic. Data is optionally persisted via RDB snapshots or AOF logs. Clients communicate over TCP using the RESP protocol; connection pools are essential to avoid per-request handshake overhead.
When to Activate
- Adding caching to an application
- Implementing rate limiting or throttling
- Building distributed locks or coordination
- Setting up session or token storage
- Using Pub/Sub or Redis Streams for messaging
- Configuring Redis in production (pooling, eviction, clustering)
Data Structure Cheat Sheet
Core Patterns
Cache-Aside (Lazy Loading)
Write-Through Cache
Cache Invalidation
Session Storage
Rate Limiting
Fixed Window (Simple)
Sliding Window (Lua — Atomic)
Distributed Locks
Distributed Lock (Single Node — SET NX PX)
For multi-node setups use the
redlock-pylibrary which implements the full Redlock algorithm.
Pub/Sub & Streams
Pub/Sub (Fire-and-Forget)
Redis Streams (Durable Queue)
Prefer Streams over Pub/Sub when you need delivery guarantees, consumer groups, or replay.
Key Design
Naming Conventions
TTL Strategy
Always set a TTL. Keys without TTL accumulate indefinitely and cause memory pressure.
Connection Management
Connection Pooling
Cluster Mode
Sentinel (High Availability)
Eviction Policies
Set via redis.conf: maxmemory-policy allkeys-lru
Anti-Patterns
Cache Miss Stampede Prevention
Note: for multi-process deployments, replace the in-process lock with
acquire_lock/release_lockfrom the Distributed Locks section above.
Examples
Add caching to a Django/Flask API endpoint:
Use cache-aside with setex and a 5-minute TTL on the response. Key on the request parameters.
Rate-limit an API by user:
Use fixed-window with pipeline(transaction=True) for low-traffic endpoints; use sliding-window Lua for accurate per-user throttling.
Coordinate a background job across workers:
Use acquire_lock with a TTL that exceeds the expected job duration. Always release in a finally block.
Fan-out notifications to multiple subscribers: Use Pub/Sub for fire-and-forget. Switch to Streams if you need guaranteed delivery or replay for late consumers.
Quick Reference
Related
- Skill:
postgres-patterns— relational data patterns - Skill:
backend-patterns— API and service layer patterns - Skill:
database-migrations— schema versioning - Skill:
django-patterns— Django cache framework integration - Agent:
database-reviewer— full database review workflow


