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.
Cache-aside pattern in 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.
GET user:123 // If null, query database for user 123 SET user:123 "{...user data...}" EX 3600
GET product:456 // If cache miss, fetch product 456 from DB SET product:456 "{...product data...}" EX 1800
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.
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}"
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.
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.
Practice
cache-aside pattern in Redis?Solution
Step 1: Understand cache-aside pattern basics
The cache-aside pattern means the application loads data into cache only when it is needed, not before.Step 2: Compare options with this concept
Load data into cache only when the application requests it and cache misses occur matches this idea exactly, while others describe different caching strategies.Final Answer:
Load data into cache only when the application requests it and cache misses occur -> Option BQuick Check:
Cache-aside = Load on demand [OK]
- Thinking cache is preloaded with all data
- Assuming cache updates automatically without app logic
- Confusing cache-aside with write-through caching
Solution
Step 1: Identify command to check key presence
In Redis,EXISTSchecks if a key is present in cache.Step 2: Match commands with their purpose
GETretrieves value,SETstores value,DELdeletes key. OnlyEXISTSchecks presence.Final Answer:
EXISTS -> Option DQuick Check:
Check key presence = EXISTS [OK]
- Using GET to check existence (GET returns null if missing)
- Confusing SET with checking commands
- Using DEL which deletes keys
if not redis.exists('user:123'):
data = db.query('SELECT * FROM users WHERE id=123')
redis.set('user:123', data)
else:
data = redis.get('user:123')What happens if the key
user:123 is missing in Redis?Solution
Step 1: Analyze the if condition for cache miss
Ifuser:123does not exist in Redis, the code queries the database for data.Step 2: Understand cache population after miss
After fetching from database, it stores the data in Redis withsetfor future requests.Final Answer:
Data is fetched from the database and stored in Redis cache -> Option CQuick Check:
Cache miss triggers DB fetch and cache store [OK]
- Assuming Redis auto-loads data from DB
- Expecting error on missing key
- Thinking Redis returns empty data silently
if redis.get('product:456') is None:
data = db.query('SELECT * FROM products WHERE id=456')
redis.set('product:456', data)
else:
data = redis.get('product:456')But the cache never updates even after database changes. What is the likely problem?
Solution
Step 1: Identify cache update mechanism
The code only sets cache if key is missing but does not update or invalidate cache after DB changes.Step 2: Understand cache staleness cause
Without cache invalidation or update logic after DB writes, cache remains stale and does not reflect DB changes.Final Answer:
The cache is never invalidated or updated after DB changes -> Option AQuick Check:
Cache stale if no invalidation after DB update [OK]
- Assuming GET command causes update
- Blaming DB query syntax without evidence
- Thinking Redis keys are invalid without reason
1. On read: check cache, if miss fetch DB and set cache
2. On write: update DB, then delete cache key to force reload on next read
Why is deleting the cache key after DB update preferred over updating cache directly?
Solution
Step 1: Understand cache update strategies
Deleting cache key after DB update forces next read to reload fresh data, avoiding stale cache.Step 2: Recognize race condition prevention
Direct cache update risks race conditions if multiple writes/read happen concurrently; deleting key is safer.Final Answer:
Deleting cache key avoids race conditions and stale data issues -> Option AQuick Check:
Delete cache key after DB write to avoid stale data [OK]
- Thinking Redis cannot update cache values
- Believing direct cache update is always better
- Assuming deleting cache key crashes Redis
Ready to prove it?
Pass the test and this pattern moves unknown
