Redis Caching: Keys, Expiry, and Cache-Aside
Redis is an in-memory data store that serves reads in well under a millisecond. The most common use is a cache sitting in front of a slower database.
The cache-aside pattern works like this: check Redis first, and if the key is missing, load from the database, store the result with an expiry, and return it.
bash redis-cli SET user:42:profile '{"name":"Ana"}' EX 300 redis-cli GET user:42:profile redis-cli TTL user:42:profile
The EX 300 option sets a time-to-live of 300 seconds, so stale entries disappear without manual cleanup. Use SET key value NX when you need a lock that only one client can create.
A few rules keep caches predictable:
- Use clear, namespaced key names such as user:42:profile. - Always set a TTL unless the data truly never changes. - Invalidate or overwrite the key when the source record changes. - Use SCAN instead of KEYS on live systems, because KEYS blocks the server while it walks every key.
To see memory use and eviction behaviour, run redis-cli INFO memory and check the maxmemory-policy setting. Setting maxmemory-policy allkeys-lru tells Redis to evict least recently used keys when it reaches its memory limit.