Skip to main content
App basics: HTTP, auth, dataLesson 7 of 11

How an Application Cache Works

Follow one product page through an application cache: app → cache server → database. Watch a miss fill the cache, a write invalidate it, memory run out, a hot key expire under load, and the cache itself go down.

Lookup—
Latency—
DB loadevery request
Hit ratio—
ServiceUsersGET /product/42App serverCache-aside logicCache serverRedis / Valkey · RAMDatabaseSource of truthAdminUpdates priceMetricsHit ratioGET /product/42
RequestResponse / reportWatchAppears in a later step

What you will learn

  • Cache-aside: check the cache, fall back to the DB, then fill the cache
  • Why a write deletes the key, and the stale data window that remains
  • What maxmemory and the eviction policy decide when RAM is full
  • Cache stampedes on a hot key and three ways to stop them
  • Why the database must survive the cache going down

Caching patterns​

PatternReadWriteGood forWatch out
Cache-aside (lazy loading)App checks cache, loads DB on miss, fills cacheApp writes DB, deletes the keyMost read-heavy apps; the cache can fail without losing dataFirst read after a miss or a restart is slow; stale window until TTL
Read-throughThe cache layer loads the DB on a miss for the appUsually combined with write-throughKeeping load logic out of app codeNeeds a cache library or product that knows how to load from the DB
Write-throughReads hit a cache that is always filledEvery write goes to cache and DB togetherData read right after it is writtenWrites are slower; caches data that may never be read
Write-behind (write-back)Reads hit the cacheWrite to cache now, flush to DB later in batchesVery high write rates, such as countersData written to the cache but not yet flushed is lost if the cache dies

Try it yourself​

redis-cli SET product:42 '{"price":100}' EX 300 # Store with a 300 s TTL
redis-cli GET product:42 # Hit: returns the value
redis-cli TTL product:42 # Seconds left (-1 no TTL, -2 no key)
redis-cli EXPIRE product:42 60 # Change the TTL
redis-cli DEL product:42 # Invalidate after a write
redis-cli SET lock:product:42 1 NX EX 5 # Stampede lock: only the first caller gets OK
redis-cli INFO stats | grep -E 'keyspace_(hits|misses)|evicted_keys' # Hit ratio and evictions
redis-cli CONFIG GET maxmemory-policy # What happens when memory is full

valkey-cli takes the same commands.

Check yourself

  1. Another service changes a price directly in the database, and users keep seeing the old price for a few minutes. What limits how long this lasts?
  2. A hot key on the front page expires and the database suddenly spikes with the same query many times over. Which fix lets only one request reload it?
  3. A Redis server used as a pure cache keeps the default maxmemory-policy. What happens when its memory fills up?

Further reading: Redis key eviction · Redis EXPIRE · Redis INFO · Valkey documentation · How a CDN Serves a Request · Database Basics