Skip to main content
In this lesson you’ll place a Redis cache in front of your database to accelerate read requests. You’ll measure response behavior before and after adding the cache, then modify the underlying database and observe the application returning stale data because it was served from Redis. This demonstrates the cache-aside (lazy-loading) pattern: on a cache miss the application reads from the database and populates Redis; on a cache hit it serves data directly from Redis. If the database changes and the cache is not invalidated or updated, the application may continue returning stale data until the cache entry expires or is refreshed. Here is an example interaction showing a request for a user profile, a repeated request (served from cache), and a short look at the application logs:
This lesson demonstrates the cache-aside pattern: on a cache miss the application reads from the database and populates Redis; on a cache hit it serves data directly from Redis. If the database is updated without invalidating or updating the cache, the application may continue to serve stale data until the cache entry expires or is refreshed.

What you’ll observe

  • Baseline: requests read directly from the database (no Redis), with typical latency.
  • After adding Redis: first request for an item populates the cache (cache miss → DB read); subsequent requests for the same item are served from Redis (cache hit), reducing latency.
  • Stale data scenario: if you update the database directly without invalidating the Redis entry, the application may return the old value until the cached key expires or is explicitly refreshed/invalidated.

Quick commands and examples

How the cache-aside pattern works (summary)

  1. Application receives a request for resource X.
  2. Check Redis for key X:
    • If present (cache hit): deserialize and return to client.
    • If absent (cache miss): read X from the database, return to client, and write X into Redis (optionally with a TTL).
  3. If the database is modified by another process, the cache must be invalidated or updated to avoid serving stale data. Common strategies are: write-through, write-behind, explicit invalidation, or short TTLs.

Debugging tips

  • Look for log lines indicating cache behavior, e.g. cache: hit for profile 7 or cache: miss for profile 7.
  • When debugging stale reads:
    • Verify if the database row actually changed.
    • Check whether the Redis key still exists and contains the old value.
    • Confirm whether your application invalidates cache keys on updates.
  • Use Redis CLI to inspect keys: redis-cli GET profile:7 (or the key format your app uses).

Common invalidation strategies

References and further reading

Watch Video

Practice Lab