In this lesson, you will learn how to implement the Cache-Aside pattern to reduce database load by serving frequently accessed data directly from memory.
The Cache-Aside Flow
The Cache-Aside pattern (or "lazy loading") places the application code in charge of keeping the cache and database synchronized. Instead of the database pushing updates to the cache, the application checks the cache first. If the data isn't there—a "cache miss"—the application fetches it from the database and populates the cache for future requests.
This approach is highly efficient because it only caches data that is actually requested, preventing your cache from being cluttered with unused records.
Implementation Logic
To implement this, your application follows a standard three-step dance whenever it needs to retrieve a record:
- Check: Query the cache using the lookup key.
- Handle Miss: If the key is missing, query the primary database.
- Populate: Store the database result in the cache so the next request finds it.
Here is what that logic looks like in practice:
def get_user_profile(user_id):
# 1. Check the cache
user = cache.get(f"user:{user_id}")
if user is None:
# 2. Cache miss: Fetch from DB
user = db.query("SELECT * FROM users WHERE id = ?", user_id)
# 3. Populate cache for next time
cache.set(f"user:{user_id}", user, expire=3600)
return user
Critical Considerations
When using Cache-Aside, remember that your application is now responsible for consistency. If you update a user’s record in the database, the old version might still be sitting in your cache. To maintain data integrity, you must either delete the cache entry immediately after a database write or set a reasonable Time-To-Live (TTL) on your cache keys so they eventually expire and refresh.
By offloading repetitive read operations to memory, you ensure your database remains performant and focused on complex write operations or unique queries.
Key Takeaway: Cache-Aside is a "lazy" loading strategy where the application explicitly orchestrates data retrieval, ensuring the cache stays updated only with the data that is actively requested by users.