0
0
Redisquery~5 mins

Write-through pattern in Redis

Choose your learning style9 modes available
Introduction
The write-through pattern helps keep data in the cache and database the same by saving data to both at the same time. This makes sure the cache always has the latest data.
When you want to speed up reading data by using a cache but keep data accurate.
When you update data often and want the cache to reflect changes immediately.
When you want to avoid stale or outdated data in your cache.
When your application reads data more often than it writes.
When you want simple and reliable cache management without complex invalidation.
Syntax
Redis
1. Write data to the database.
2. Write the same data to the cache (Redis).

Example commands:
SET key value  # Redis command to save data
-- plus your database update command
The write-through pattern means writing to the database first, then to the cache.
If the database write fails, do not update the cache to avoid inconsistency.
Examples
Save user data in Redis cache and database at the same time.
Redis
SET user:1 "Alice"
-- Also update user with ID 1 in your database
Write product info to both Redis and database to keep them synced.
Redis
SET product:100 "Laptop"
-- Update product 100 details in your database
Sample Program
This example shows updating a user's name in the database first, then saving the same data in Redis cache with the key 'user:2'.
Redis
-- Simulate write-through pattern
-- Step 1: Update database (simulated here as a comment)
-- UPDATE users SET name = 'Bob' WHERE id = 2;

-- Step 2: Write to Redis cache
SET user:2 "Bob"
OutputSuccess
Important Notes
Always write to the database first to ensure data is saved permanently.
If writing to Redis fails, you can retry or handle the error, but the database remains the source of truth.
This pattern helps keep cache and database data consistent automatically.
Summary
Write-through pattern saves data to both database and cache at the same time.
It keeps cache data fresh and avoids stale reads.
Use it when you want simple, reliable cache updates on every write.