Cache Aside Pattern with Redis: What It Is and How It Works
cache aside pattern with Redis is a way to keep data in cache only when needed. Your application first checks Redis for data; if missing, it loads from the database, stores it in Redis, then returns it. This helps speed up reads while keeping cache fresh.How It Works
Imagine you have a library where books are stored in a big warehouse (the database) and a small shelf in the reading room (the cache). When you want a book, you first check the shelf. If the book is there, you grab it quickly. If not, you go to the warehouse, get the book, and put a copy on the shelf for next time.
The cache aside pattern works the same way with Redis. Your app first asks Redis if the data is there. If yes, it uses it immediately. If no, it fetches the data from the main database, then saves a copy in Redis for future requests. This way, Redis only stores data that is actually needed, keeping cache efficient and fresh.
Example
import redis import time import ast # Simulated database database = { 'user:1': {'name': 'Alice', 'age': 30}, 'user:2': {'name': 'Bob', 'age': 25} } # Connect to Redis cache = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) def get_user(user_id): key = f'user:{user_id}' # Try to get from cache user = cache.get(key) if user: user_data = ast.literal_eval(user) return f'Cache hit: {user_data}' # Cache miss, get from database user_data = database.get(key) if user_data: # Store in cache with expiration cache.set(key, str(user_data), ex=60) return f'Cache miss: {user_data}' return 'User not found' # Test calls print(get_user(1)) # Miss, loads from DB print(get_user(1)) # Hit, loads from cache print(get_user(3)) # Not found
When to Use
Use the cache aside pattern when your data is mostly read and changes less often. It helps reduce database load and speeds up response times by caching only requested data.
Common cases include user profiles, product details, or configuration settings where data updates are less frequent but reads are many. It also works well when you want to control cache freshness manually.
Key Points
- The application controls when to load and update cache.
- Cache stores data only after a cache miss.
- Cache expiration helps keep data fresh.
- Good for read-heavy workloads with less frequent writes.