Back to results for “Caching”
Redis › Caching Patterns

What is the cache aside pattern, and how does it work with Redis?

Beginner

Answer

In the cache aside pattern, your application first checks Redis for the data it needs, and if the data is not found, it fetches it from the primary database, stores a copy in Redis for next time, and then returns the result, keeping Redis populated only with data that has actually been requested.
value = redis.get('user:123')
if value is None:
    value = database.get_user(123)
    redis.set('user:123', value, ex=3600)
return value
Real-world example A social media app checks Redis first when loading a user profile, only querying the slower main database the first time that specific profile is requested, then serving it instantly from Redis on every later request.

Common follow-ups: What happens if the data in the database changes after it has already been cached?;How do you decide an appropriate expiration time for cached data?