Redis and caching¶
Scope: using Redis, and compatible servers such as Valkey, as a cache, session store, rate limiter or message queue, plus the caching patterns that apply to any shared cache. The rules cite the Redis documentation; the Valkey documentation covers the same topics and says the same about security, eviction, persistence and Cluster. Who owns data and how consistent it must be are in general/data.md (DATA-1, DATA-5). Timeouts, retries and circuit breakers for calls to Redis are in general/operations-reliability.md (OPS-3, OPS-5). For a relational system of record, see PostgreSQL; for HTTP and CDN caching, see Web front end and Serverless and edge hosting.
Entries are sorted by score from 1 to 10 (criteria): 9โ10 start here or strongly recommended, 6โ8 recommended, 1โ5 further reading or conditional.
Adopted references¶
- 9 Manage Redis (Redis docs): the baseline for running Redis Open Source: administration, security, ACLs, TLS, configuration, replication, Sentinel, Cluster, persistence, and diagnosing latency and memory problems.
- 8 Caching guidance (Azure Architecture Center): the baseline for caching in general: when to cache, private and shared caches, expiration, keeping the cache consistent on writes, concurrency, availability and protecting cached data, with Redis examples.
- 8 Caching challenges and strategies (AWS Builders' Library): what goes wrong when a service comes to depend on its cache: cold starts, cache outages, request coalescing, negative caching and stale data.
- 7 Cache-Aside pattern (Azure Architecture Center): loading data into a cache on demand and invalidating it on writes, with its consistency trade-offs and when not to use it.
- 7 Valkey documentation by topic (Valkey): the equivalent guides for Valkey, the Redis-compatible key-value store backed by the Linux Foundation.
- 7 Redis data types (Redis docs): strings, hashes, lists, sets, sorted sets, streams and the other types, and which problems each one fits.
- 7 Caching best practices (AWS): lazy caching, write-through, TTLs, eviction policies and the thundering herd.
- 7 Client-side caching reference (Redis docs): how clients keep a subset of the data in their own memory and how the server tells them when to invalidate it.
- 6 Redis pipelining (Redis docs): sending many commands without waiting for each reply, to cut round trips.
- 6 Redis anti-patterns every developer should avoid (Redis): keys without TTLs, hot keys, the
KEYScommand, ephemeral Redis as a primary database and other common mistakes.
Key rules¶
Caching patterns¶
- 8
REDIS-1Keep the authoritative copy of cached data in a durable data store, and keep data only in Redis when you have configured persistence and replication for it on purpose. A cache is a transient store whose entries can be evicted or lost at any time. (Azure, Caching guidance: high availability and scalability, Redis, Key eviction, Redis anti-patterns, Running ephemeral Redis as a primary database) - 8
REDIS-2Give cache entries a TTL, even a long one, unless write-through keeps them current, and setmaxmemorywith an eviction policy that fits the workload, such asallkeys-lrufor a pure cache. On 64-bit systems Redis has no memory limit by default, and thevolatile-*policies evict nothing when no key has a TTL. (AWS, Caching best practices, Redis, Key eviction: maxmemory, Eviction policies) - 7
REDIS-3Choose the write strategy per data set: cache-aside (load on a miss, invalidate on write) as the default, and write-through where readers must see a change right after the write. With cache-aside, a reader can miss or briefly see stale data between a write and the next read. (Azure, Cache-Aside pattern, Azure, Caching guidance: keep the cache consistent on writes, AWS, Caching best practices) - 7
REDIS-4Plan for a cold or unavailable cache: put a timeout on cache calls (OPS-3), make sure the data store can take the load of all misses or cap and shed that load, and load-test with the cache disabled. Falling back to the data store during a long cache outage can overload it. (AWS Builders' Library, Caching challenges and strategies, Azure, Caching guidance: high availability and scalability) - 6
REDIS-5Protect expensive entries from cache stampedes: add random jitter to TTLs, let only one caller recompute a missing entry (request coalescing), or refresh hot entries before they expire. Many keys expiring in the same second can also block Redis while it removes them. (AWS, Caching best practices, AWS Builders' Library, Caching challenges and strategies, Redis, Diagnosing latency: latency generated by expires, Vattani et al., Optimal Probabilistic Cache Stampede Prevention)
Keys, commands and data types¶
- 8
REDIS-6Never callKEYSfrom application code, and avoid other O(N) commands on big keys: iterate withSCAN,SSCAN,HSCANorZSCAN, keep collections and values small, and watch the slow log. Redis runs commands one at a time, so one slow command delays every client. Find big keys withredis-cli --bigkeysand--memkeys. (Redis, Keys and values: KEYS, Diagnosing latency: latency generated by slow commands, Redis CLI: scan for big keys and memory usage, SLOWLOG) - 6
REDIS-7Name keys with one schema, such asapp:object-type:id[:field], with a prefix per application or tenant, and hash long natural keys instead of using them as key names. Redis has no namespaces, so prefixes prevent collisions and let ACLs restrict users to their own keys. (Redis, Keys and values: content of keys, Redis, ACL: key permissions) - 6
REDIS-9Use Streams with consumer groups, not Pub/Sub, for messages that must not be lost. Pub/Sub delivers at most once: a message is gone if the subscriber is disconnected or fails to handle it. Streams persist messages and support at-least-once delivery with acknowledgements. (Redis, Pub/sub: delivery semantics, Redis Streams) - 5
REDIS-8On Redis Cluster, put keys that one multi-key command, transaction or script uses into the same hash slot with a hash tag, such as{user:1000}:cart, and use hash tags only where you need them. Multi-key operations work only when all keys hash to the same slot, but too many keys in one slot eventually hurts performance. (Redis, Keys and values: hashtags, Redis cluster specification: hash tags)
Security¶
- 9
REDIS-10Set thebinddirective inredis.confto private interfaces, firewall the Redis port so that only the application hosts can reach it, and leave protected mode on. Redis is designed for trusted clients in trusted environments, and anyone who reaches the port can, for example, delete the whole data set withFLUSHALL. This is how Redis appliesSEC-20. (Redis, Security: network security, Protected mode, Valkey, Security) - 8
REDIS-11Authenticate every client as a named ACL user with only the commands and key patterns it needs, turn off the passwordlessdefaultuser, and use TLS for every connection that leaves the host. By default, every connection is authenticated asdefault, which may run every command on every key, andAUTHis sent unencrypted without TLS. The general rules areSEC-5andSEC-13in general/security.md. (Redis, ACL, Redis, Security: authentication, Redis, TLS)
Persistence and availability¶
- 7
REDIS-12Choose persistence by what losing the data would cost: none for a cache you can rebuild, RDB snapshots when losing the last minutes of writes is acceptable, and AOF plus RDB for safety close to PostgreSQL's. Copy RDB snapshots off the machine at least daily. (Redis, Persistence: what should I use, Backing up Redis data) - 6
REDIS-13With replication, turn on persistence on the primary and the replicas, or stop a primary without persistence from restarting automatically. A primary that restarts empty replicates the empty data set and wipes its replicas. (Redis, Replication: safety when the master has persistence turned off) - 6
REDIS-14For automatic failover, run Sentinel, with at least three instances on machines that fail independently, or Redis Cluster, and design for lost writes. Replication is asynchronous, so a failover can lose acknowledged writes, even withWAIT. (Redis, Sentinel: fundamental things to know, Redis, Replication, Redis cluster specification: write safety)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7 Redis ACL command categories: built into Redis and Valkey. Give application users rules such as
+@all -@dangerous ~myapp:*, in test environments too, so that Redis rejectsKEYS,FLUSHALL,CONFIGand the other dangerous commands, and keys outside the application's prefix, with an error. Partly checksREDIS-6andREDIS-7. - 6 Checkov Terraform policies: misconfiguration checks for managed Redis in Terraform, such as
CKV_AWS_31(ElastiCache in-transit encryption with an auth token),CKV_AZURE_89(Azure Cache for Redis without public network access),CKV_AZURE_91(only the TLS port),CKV_GCP_95andCKV_GCP_97(Memorystore AUTH and in-transit encryption),CKV_AWS_134(ElastiCache automatic backups) andCKV2_AWS_50(ElastiCache Multi-AZ automatic failover). Partly checksREDIS-10,REDIS-11,REDIS-12andREDIS-14.
Tutorials and further reading¶
- 6 Redis as an in-memory data structure store (Redis docs): a quick start that walks through the core data types.
- 5 Optimal Probabilistic Cache Stampede Prevention (Vattani, Chierichetti and Lowenstein, VLDB 2015): the paper behind probabilistic early expiration.