0
0
Redisquery~5 mins

Cache-aside (lazy loading) deep dive in Redis

Choose your learning style9 modes available
Introduction

Cache-aside helps speed up data access by storing data in a fast cache only when needed. It keeps the cache and database in sync without extra work.

When you want to reduce slow database reads by caching data on demand.
When data changes are less frequent than reads, so caching saves time.
When you want to keep cache storage small by only caching requested data.
When you want to avoid stale cache by loading fresh data only when needed.
When you want simple cache logic without automatic cache updates.
Syntax
Redis
1. Check if data is in cache (GET key)
2. If found, return cached data
3. If not found, read data from database
4. Store data in cache (SET key value)
5. Return data

This pattern is called 'lazy loading' because data is loaded into cache only when requested.

Cache expiration can be added to keep data fresh.

Examples
Check cache for user data. If missing, get from DB and cache it.
Redis
GET user:123
// If null, query DB for user 123
// Then SET user:123 "{...}"
Lazy load product info into cache on demand.
Redis
GET product:456
// If cache miss, fetch product 456 from DB
// SET product:456 "{...}"
Cache session data with expiration to auto-remove stale sessions.
Redis
GET session:abc
// If not in cache, load session from DB
// SET session:abc "{...}" EX 3600
Sample Program

This simulates cache-aside: first try cache, miss, load from DB, then cache it.

Redis
redis-cli GET user:1
// Suppose output is (nil)
// Then fetch user 1 from DB (simulate with JSON string)
SET user:1 "{\"id\":1, \"name\":\"Alice\"}"
GET user:1
OutputSuccess
Important Notes

Cache misses cause a database read, so expect some delay on first access.

Always handle cache misses gracefully to avoid errors.

Consider cache expiration to avoid stale data.

Summary

Cache-aside loads data into cache only when needed.

It reduces database load by caching frequently accessed data.

It keeps cache and database consistent by loading fresh data on cache miss.