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)
- Application receives a request for resource X.
- 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).
- 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 7orcache: 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
- Redis documentation
- Cache-aside pattern overview (Martin Fowler)
- [Designing Data-Intensive Applications (Book) — caching patterns]