Caching with Redis
Cache-aside in front of PostgreSQL, expiry, invalidation on write, and a session every pod behind a Route can read.
A cache stores a copy of something whose real home is elsewhere. In this lab the home is PostgreSQL and the copy is Redis, reached through the cache Service from the OpenShift lab. The pattern is cache-aside: the application reads Redis first, and on a miss it reads Postgres and fills Redis. Redis is never the only place the catalog row exists.
The same Redis also holds sessions, which have no other home. Lose Redis and the user signs in again. Lose Redis and the catalog is merely slower, because Postgres still has the row. Those two cases share a server and almost nothing else.
Prerequisites
- The
cacheService in namespacecache, answeringPING redis-clion the workstation- A PostgreSQL the application already uses. The Crunchy lab builds one. A local database is enough for the commands below
oc get svc cache -n cache
oc port-forward -n cache svc/cache 6379:6379
Leave the port-forward running. The commands use redis-cli with no -h. If you set a password, add -a "$PASS" --no-auth-warning.
Cache-aside
The key names the row, and names nothing else. catalog:product:42 is the product whose primary key is 42. The value is a string the API can return as JSON.
redis-cli GET catalog:product:42
A miss returns (nil). The application then reads Postgres:
SELECT sku, price FROM product WHERE id = 42;
and fills Redis with a lifetime:
redis-cli SET catalog:product:42 '{"sku":"42","price":120}' EX 300
redis-cli TTL catalog:product:42
EX 300 is five minutes. The next GET is a hit and does not touch Postgres. TTL returns the seconds left. -1 would mean the key has no expiry, which is a bug for a cache entry: a key with no expiry lives until something deletes it, and a full memory limit will evict whatever the policy chooses.
Two pods can miss at the same moment, both read Postgres, and both SET. That race is harmless when they write the same value. It costs one extra SQL read.
Expiry
Expiry is the backstop, not the invalidation plan. Use it so a forgotten DEL still repairs itself.
| Command | What it does |
|---|---|
SET key value EX 300 |
Write and set a lifetime in one step |
EXPIRE key 300 |
Set a lifetime on a key that already exists |
EXPIRE key 300 NX |
Set it only if the key has none. Redis 7 and later |
TTL key |
Seconds left. -2 means the key is already gone |
GETEX key EX 300 |
Read and reset the lifetime in one step |
PERSIST key |
Remove the lifetime. Wrong for a cache entry |
For a server that holds only cache keys, maxmemory-policy allkeys-lru evicts the least recently used key when memory is full. For a server that mixes cache keys and sessions, give every cache key a TTL and use volatile-lru, so a key you forgot to expire is the one that goes, and a session key with a TTL is predictable. Set that in the Redis config the operator mounts, then check it:
redis-cli CONFIG GET maxmemory-policy
The security and monitoring lab is the right place to alert when evicted_keys climbs. Eviction means the working set no longer fits, or the TTLs are longer than they need to be.
Invalidation
When the price changes, delete the key. Do not write the new value into Redis from the request that updated Postgres.
UPDATE product SET price = 140 WHERE id = 42;
redis-cli DEL catalog:product:42
redis-cli GET catalog:product:42
The next reader fills Redis from the new row. DEL is safe to repeat. UNLINK is the same idea and frees the memory in the background; use it for large values.
Writing the new JSON from the updater races. Request A reads the old price. Request B commits the new price and deletes the key. Request A then SETs the old price, and Redis is wrong until the TTL. If only the updater writes to Postgres, and Redis is filled only by readers after a DEL, that window shrinks to the requests already in flight. The TTL closes it the rest of the way. A reader that must not see a stale price for those few seconds reads Postgres and skips the cache.
Delete the key you can name. KEYS catalog:* blocks the shard. If you cannot name the key, SCAN is the search that yields:
redis-cli --scan --pattern 'catalog:product:*'
A foreign key that changes a set of products (a category rename) needs those keys named, or a version suffix in the key (catalog:v7:product:42) so the old generation dies by TTL.
Shared sessions
An OpenShift Route sends the next request to any pod. The pod that handled sign-in is not the pod that handles the request after it. A session stored in that pod's memory is a session the next pod cannot see.
The cookie carries an id. Redis carries the session. Any pod can load it.
redis-cli HSET session:7f3a user karim warehouse dac
redis-cli EXPIRE session:7f3a 1800
redis-cli HGETALL session:7f3a
On each request the application resets the lifetime, so an active user is not signed out at a fixed time:
redis-cli EXPIRE session:7f3a 1800
Sign-out is a delete:
redis-cli DEL session:7f3a
Thirty minutes is a product choice; pick the one your session policy already states. The cookie should be HttpOnly and Secure, and the id in it should be random. The session payload stays in Redis, where a stolen cookie still expires and where sign-out can kill it. Putting the whole session in the cookie means you cannot revoke it before it expires.
A counter with a window is the same expiry idea, and it is how a Route and an API share a rate limit across pods:
redis-cli INCR rate:api:karim
redis-cli EXPIRE rate:api:karim 60 NX
redis-cli GET rate:api:karim
EXPIRE ... NX starts the window on the first hit and does not extend it on later hits. When the key expires, the next INCR starts a new minute.
What failure looks like
Redis down, cache-aside: the request falls through to Postgres and is slower. The application has to treat a connection error as a miss, not as a failed request. Redis down, sessions: sign-in state is gone. Run sessions on the replicated setup in the high-availability lab once they matter, and keep the catalog row in Postgres either way. The persistence lab is about the copy that survives a restart, which a pure cache can often skip and a session store cannot.
What's next
High availability keeps this Service answering when a pod dies. Pub/sub and streams cover the case where the message is the data, which a cache key is not. Catalog reads in the .NET and Spring Boot labs are the calls this pattern is for.