# Redis Patterns and Documentation for AI Coding Agents > Comprehensive Redis design patterns, best practices, and command references for LLM coding agents. ## Important Notes **Redis-Specific Documentation**: These documents are specific to Redis (https://redis.io) and may not apply to other systems that share parts of the codebase, such as Valkey, KeyDB, Dragonfly, or other Redis-compatible databases. When working with these forks or alternatives, verify compatibility as implementations may differ. **Official Source Code**: The official Redis source code is available at https://github.com/redis/redis **Official Documentation**: For authoritative command documentation, refer to the official docs repository at https://github.com/redis/docs which is mirrored at https://redis.io/docs/ --- ## Commands Reference The official Redis documentation is mirrored locally: - [Commands Index](commands-index.md): Auto-generated index of all commands organized by category - [Command Documentation](commands/content/commands/): Individual command files (e.g., set.md, hset.md, zadd.md) - [Full Documentation](commands/content/): develop/, integrate/, operate/ guides Upstream: https://github.com/redis/docs ## Fundamental Design Patterns Core architectural patterns for building systems with Redis. - [Atomic Update Patterns](fundamental/atomic-updates.md): Ensure data integrity with atomic read-modify-write operations using WATCH/MULTI/EXEC for optimistic locking, Lua scripts for complex logic, and shadow-key patterns for safe bulk updates. - [Cache-Aside Pattern (Lazy Loading)](fundamental/cache-aside.md): Use Cache-Aside for read-heavy workloads: on cache miss, fetch from the database and populate the cache; on write, invalidate or update the cache explicitly. - [Cache Stampede Prevention](fundamental/cache-stampede-prevention.md): Prevent multiple clients from simultaneously regenerating an expired cache key using locking, probabilistic early refresh, or request coalescing. - [Server-Assisted Client-Side Caching](fundamental/client-side-caching.md): Eliminate network round-trips for frequently accessed keys by caching values in application memory, with Redis 6+ automatically sending invalidation messages when data changes. - [Cross-Shard Consistency Patterns](fundamental/cross-shard-consistency.md): Detect and handle torn writes across multiple Redis instances using transaction stamps, version tokens, and commit markers when atomic multi-key operations aren't possible. - [Delayed Queue Pattern](fundamental/delayed-queue.md): Schedule tasks for future execution using a Sorted Set where the score is the Unix timestamp when the task should run. - [Distributed Locking with Redis](fundamental/distributed-locking.md): Implement mutual exclusion across distributed processes using `SET key value NX PX timeout` for atomic lock acquisition with automatic expiration. - [Hash Tag Co-location Patterns](fundamental/hash-tag-colocation.md): Force related keys to the same Redis Cluster slot using hash tags, enabling atomic multi-key operations, transactions, and Lua scripts across logically related data. - [Lexicographic Sorted Set Patterns](fundamental/lexicographic-sorted-sets.md): Use Sorted Sets with identical scores (typically 0) to create B-tree-like indexes supporting prefix queries, range scans, and composite key lookups on string data. - [Memory Optimization Patterns](fundamental/memory-optimization.md): Reduce Redis memory consumption by leveraging compact encodings (listpack, intset), using Hashes for small object storage, and choosing memory-efficient data structures. - [Probabilistic Data Structures](fundamental/probabilistic-data-structures.md): Count unique items with HyperLogLog (12KB fixed), test set membership with Bloom filters, or estimate frequencies with Count-Min Sketch—trading small accuracy loss for massive memory savings. - [Rate Limiting Patterns](fundamental/rate-limiting.md): Implement distributed rate limiting using fixed window, sliding window log, sliding window counter, token bucket, or leaky bucket algorithms with Redis atomic operations. - [Redis as a Primary Database](fundamental/redis-as-primary-database.md): Use Redis as the authoritative data store for applications requiring sub-millisecond latency and high write throughput, treating disk as a recovery mechanism rather than the primary storage layer. - [The Redlock Algorithm](fundamental/redlock.md): Achieve fault-tolerant distributed locking by acquiring locks on a majority (N/2+1) of N independent Redis instances, tolerating node failures without losing lock consistency. - [Reliable Queue Pattern](fundamental/reliable-queue.md): Guarantee at-least-once message delivery using LMOVE to atomically transfer messages to a processing list, enabling recovery if consumers crash before completing work. - [Streams Consumer Group Patterns](fundamental/streams-consumer-patterns.md): Implement reliable message processing with Redis Streams consumer groups, handling failure recovery, poison pills, and memory management—the operational patterns that production systems require beyond basic XREADGROUP usage. - [Redis Streams and Event Sourcing](fundamental/streams-event-sourcing.md): Build persistent message queues with consumer groups, message acknowledgment, and historical replay using Redis Streams—ideal for event sourcing and multi-consumer workloads. - [Vector Sets and Similarity Search](fundamental/vector-sets.md): Store vectors and find similar items using Redis 8's native Vector Sets—an HNSW-based data structure supporting semantic search, RAG, recommendations, and classification with optional filtered queries. - [Write-Behind (Write-Back) Caching Pattern](fundamental/write-behind.md): Maximize write throughput by writing only to Redis and asynchronously syncing to the database later—trades immediate durability for performance. - [Write-Through Caching Pattern](fundamental/write-through.md): Maintain cache-database consistency by synchronously writing to both Redis and the database before returning success—ensures reads always hit cache with fresh data. ## Community Patterns Patterns developed by the Redis community for common use cases. - [Bitmap Patterns](community/bitmap-patterns.md): Store millions of boolean flags in minimal memory using Redis bitmaps—1 bit per flag with O(1) access, plus fast aggregate operations across entire datasets. - [Geospatial Patterns](community/geospatial.md): Store locations and query by radius, distance, or bounding box using GEOADD, GEOSEARCH, and GEODIST commands built on geohash-encoded Sorted Sets. - [Leaderboard Patterns](community/leaderboards.md): Build real-time rankings with Sorted Sets: O(log N) score updates, O(log N) rank lookups, and efficient range queries for top-N or around-me leaderboards. - [Pub/Sub Patterns](community/pubsub.md): Broadcast real-time events to multiple subscribers using fire-and-forget messaging—ideal for notifications, chat, and live updates where missed messages are acceptable. - [Session Management Patterns](community/session-management.md): Store user sessions in Redis with automatic expiration using TTL, choosing between Hashes (field-level access), Strings (serialized), or JSON (nested data) based on access patterns. - [Vector Search and AI Patterns](community/vector-search-ai.md): Build semantic search, RAG pipelines, recommendation systems, and AI agent infrastructure using Redis Vector Sets—native HNSW-based similarity search with sub-millisecond latency. ## Production Patterns Real-world patterns from major tech companies at scale. - [Linux Kernel Tuning for Redis](production/kernel-tuning.md): Configure Linux kernel parameters to prevent latency spikes, persistence failures, and connection drops in production Redis deployments—essential settings that override defaults hostile to in-memory databases. - [Pinterest: Task Queue and Functional Partitioning](production/pinterest-task-queue.md): Learn Pinterest's Redis scaling patterns: functional partitioning by use case, List-based reliable queues for background jobs, and horizontal scaling from 1 to 1000+ instances. - [Twitter/X: Deep Internals and Custom Data Structures](production/twitter-internals.md): Historical case study of Twitter's Redis customizations—many of these innovations are now built into Redis core (quicklist, improved memory management). - [Uber: Resilience Patterns and Staggered Sharding](production/uber-resilience.md): Study Uber's resilience techniques: staggered sharding to prevent coordinated failures, circuit breakers, and graceful degradation patterns for 150M+ ops/sec cache workloads. --- ## For Agents: Quick Reference ### Caching Pattern Selection | Use Case | Pattern | Key Commands | |----------|---------|--------------| | Read-heavy, stale OK | Cache-Aside | GET, SETEX | | Strong consistency | Write-Through | SET, GET | | High write throughput | Write-Behind | SET, async sync | | Popular keys | Client-Side Cache | CLIENT TRACKING | ### Queue Pattern Selection | Use Case | Pattern | Key Commands | |----------|---------|--------------| | Simple FIFO | List | LPUSH, RPOP | | Reliable delivery | LMOVE | LMOVE, LREM | | Delayed execution | Sorted Set | ZADD, ZRANGEBYSCORE | | Multiple consumers | Streams | XADD, XREADGROUP, XACK | ### Counting/Analytics | Use Case | Structure | Memory | |----------|-----------|--------| | Exact unique count | Set | O(N) | | Approximate uniques | HyperLogLog | 12KB fixed | | Membership test | Bloom Filter | Configurable | | Percentiles | T-Digest | Configurable | --- ## Source Code and Documentation Links - Redis Source: https://github.com/redis/redis - Redis Documentation: https://github.com/redis/docs → https://redis.io/docs/ - Redis Commands: https://redis.io/commands/ - Redis Clients: https://redis.io/docs/latest/develop/clients/