0
0
Redisquery~5 mins

Cache-aside pattern in Redis

Choose your learning style9 modes available
Introduction

The cache-aside pattern helps speed up data access by storing frequently used data in a fast cache. It keeps the cache and database in sync by loading data into the cache only when needed.

When you want to reduce slow database reads by using a fast cache.
When your application reads the same data many times but updates it less often.
When you want to keep your cache updated only with data that is actually requested.
When you want to avoid stale data by loading fresh data from the database on cache misses.
When you want simple control over when data is cached and when it is refreshed.
Syntax
Redis
1. Check if data is in cache (GET key)
2. If data is found, return it
3. If not found, load data from database
4. Store data in cache (SET key value EX expiration)
5. Return the data

This pattern requires your application to handle cache misses by loading data from the database.

Cache entries should have expiration times to avoid stale data.

Examples
Try to get user data from cache. If missing, get from database and save in cache for 1 hour.
Redis
GET user:123
// If null, query database for user 123
SET user:123 "{...user data...}" EX 3600
Cache product info for 30 minutes after loading from database on cache miss.
Redis
GET product:456
// If cache miss, fetch product 456 from DB
SET product:456 "{...product data...}" EX 1800
Sample Program

First, we try to get item 101 from cache but it is missing. Then we simulate loading from the database and store it in cache with a 5-minute expiration. Finally, we get the cached item successfully.

Redis
127.0.0.1:6379> GET item:101
(nil)
127.0.0.1:6379> // Cache miss, load from DB (simulated)
127.0.0.1:6379> SET item:101 "{\"name\": \"Pen\", \"price\": 1.5}" EX 300
OK
127.0.0.1:6379> GET item:101
"{\"name\": \"Pen\", \"price\": 1.5}"
OutputSuccess
Important Notes

Always handle the case when cache returns null or missing data.

Set expiration times on cached data to prevent stale information.

Write operations should update the database first, then invalidate or update the cache.

Summary

The cache-aside pattern loads data into cache only on demand.

It helps improve performance by reducing database load.

It requires your application to manage cache misses and updates.