How Write-Through Works
How Write-Through Works
Write-Through ensures data is written to both cache and database synchronously before returning to the client.
Flow Diagram
Write-Through Flow:
App → Write to Cache → Write to DB (synchronous) → Acknowledge to App
1. Data written to cache first
2. Data written to database
3. Both writes must succeed
4. Client receives acknowledgment after both complete
Implementation
class WriteThroughCache:
def __init__(self, cache_client, db_client):
self.cache = cache_client
self.db = db_client
def set(self, key, value, ttl=3600):
"""Write-through: write to cache AND database"""
# Write to cache first
self.cache.set(key, value, ttl)
# Write to database
self.db.upsert(key, value)
return True
def delete(self, key):
"""Delete from both cache and database"""
self.cache.delete(key)
self.db.delete(key)
return True
# Usage
cache = WriteThroughCache(redis_client, db_client)
cache.set('user:123', user_data) # Writes to both Redis and DB
Characteristics
- Synchronous writes to both cache and DB
- Strong consistency - cache and DB always in sync
- Higher write latency due to dual writes
- Cache is always warm for recently written data
Consistency
Write-Through Consistency
Strong Consistency Guarantee
Consistency Model:
After write completes:
- Cache: Contains new value ✓
- Database: Contains new value ✓
- Both are identical ✓
No stale data possible!
Comparison with Other Patterns
| Pattern | Consistency | Write Latency | Cache State |
|---|---|---|---|
| Cache-Aside | Eventual | Low | May be stale |
| Write-Through | Strong | High | Always fresh |
| Write-Behind | Eventual | Low | May be stale |
Handling Failures
def write_through_with_failure_handling(key, value):
"""Write-through with proper failure handling"""
try:
# Start transaction
with db.transaction():
# Write to database first (source of truth)
db.upsert(key, value)
# Then update cache
cache.set(key, value, ttl=3600)
return True
except Exception as e:
# Rollback database if cache write fails
db.rollback()
raise e
Why Write to DB First?
- Database is the source of truth
- If cache write fails, DB still has the data
- Cache will be populated on next read (Cache-Aside style)
- Maintains data durability
Performance Impact
Performance Impact of Write-Through
Write Latency Analysis
Write Latency Breakdown:
Without Cache:
App → DB Write (50ms) → Response = 50ms total
With Write-Through:
App → Cache Write (1ms) → DB Write (50ms) → Response = 51ms total
Overhead: ~2% increase in write latency
Throughput Considerations
| Metric | Without Cache | With Write-Through |
|---|---|---|
| Write Latency | 50ms | 51-55ms |
| Write Throughput | 1,000 WPS | 800-900 WPS |
| Read Latency | 100ms | 1-5ms |
| Read Throughput | 10,000 RPS | 100,000+ RPS |
Optimizing Write-Through
class OptimizedWriteThrough:
def __init__(self, cache, db, batch_size=100):
self.cache = cache
self.db = db
self.batch_size = batch_size
self.write_buffer = []
def set(self, key, value):
"""Buffer writes for batch processing"""
# Immediate cache write for reads
self.cache.set(key, value, ttl=3600)
# Buffer DB writes for batching
self.write_buffer.append((key, value))
if len(self.write_buffer) >= self.batch_size:
self.flush_buffer()
def flush_buffer(self):
"""Batch write to database"""
if self.write_buffer:
self.db.batch_upsert(self.write_buffer)
self.write_buffer = []
When to Use Write-Through
Good for:
- Read-heavy workloads with occasional writes
- When strong consistency is required
- Data that's expensive to compute
- Leaderboards, counters, session data
Not ideal for:
- Write-heavy workloads (use Write-Behind)
- When write latency is critical
- Bulk data imports
- Analytics workloads
Practice Problems
Design a scalable Write-Through system. Cover high-level architecture, data model, and API design.
Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliabilityHow would you scale Write-Through to handle 10x the current load? Identify bottlenecks and solutions.
Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decompositionAnalyze potential failure modes for Write-Through and design mitigation strategies.
Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradationQuiz
1. In Write-Through, when is the client notified of success?
2. What is the main trade-off of Write-Through?
3. Which should be written first in Write-Through for safety?
4. Write-Through provides which consistency guarantee?
5. When is Write-Through most appropriate?
Flashcards
Question
What is Write-Through caching?
Click to reveal answer
Answer
A pattern where data is written to both cache and database synchronously before acknowledging to the client
Question
Write-Through consistency guarantee?
Click to reveal answer
Answer
Strong consistency - cache and database are always in sync after a successful write
Question
What is the main drawback of Write-Through?
Click to reveal answer
Answer
Higher write latency because both cache and database must be written synchronously
Question
Which write first in Write-Through?
Click to reveal answer
Answer
Database first (source of truth), then cache. Ensures data safety if cache write fails.
Question
Best workload type for Write-Through?
Click to reveal answer
Answer
Read-heavy workloads with occasional writes, where strong consistency is required
Revision Notes
Key Takeaways
- 1.Write-Through writes to both cache and DB synchronously for strong consistency
- 2.Write latency increases by 2-10% due to dual writes
- 3.Always write to database first (source of truth), then cache
- 4.Best for read-heavy workloads where occasional write overhead is acceptable
- 5.Cache is always warm - no cache miss on recently written data
Interview Tips
- •Emphasize strong consistency as the key benefit
- •Quantify the write latency overhead (usually 2-10%)
- •Explain why DB should be written first for safety
- •Compare with Cache-Aside: Write-Through guarantees consistency, Cache-Aside doesn't
Cheat Sheet
Cheat Sheet: Write-Through
Flow
App → Cache Write → DB Write (sync) → Acknowledge
Key Points
- Synchronous dual writes
- Strong consistency guaranteed
- Higher write latency (~2-10% overhead)
- Cache always warm for written data
- Write DB first (source of truth)
When to Use
- Read-heavy with occasional writes
- Strong consistency required
- Expensive-to-compute data
Optimization
- Batch DB writes
- Use write buffers
- Pipeline cache operations