TTL (Time To Live) Strategy
What is TTL?
TTL is the duration a cache remains valid. Once TTL expires, the cache is invalidated and fresh data is fetched.TTL Settings by Data Characteristics
- Static Data
- Semi-static Data
- Dynamic Data
- Very Short-lived Data
Data that rarely changesTTL:
"forever", "1d", "1w"TTL Units
Grace Period (Stale-While-Revalidate)
What is Grace?
Grace is a strategy that returns stale cache even after TTL expiration while refreshing in the background.How It Works
When to Use Grace
Use Grace ✅
Heavy computations/queries
- Aggregate statistics
- Complex join queries
- External API calls
- Large data processing
Grace Unnecessary ❌
Fast queries
- Simple SELECT
- Index lookups
- Cached data
Grace Practical Examples
Grace vs Long TTL
Grace Strategy:- Mostly fresh data (within 5 minutes)
- Returns stale immediately on expiration (fast)
- Background refresh
- Data up to 1 hour old
- Recalculates on expiration (slow)
Namespace Strategy
What is Namespace?
Namespace is a feature that logically isolates caches.Per-User Isolation
- User A’s changes don’t affect User B
- Selective invalidation possible
Multi-Tenant
Per-Feature Isolation
Cache Patterns
1. Cache-Aside (Lazy Loading)
Most basic pattern: Query and cache when needed2. Write-Through
Update cache on write: Update cache simultaneously with data change3. Write-Behind (Write-Back)
Write to cache first: Update cache then asynchronously save to DB4. Refresh-Ahead
Pre-refresh before expiration: Prepare fresh data before TTL endsCombined Strategies
TTL by Layer
Strategies by Priority
- Critical Data
- Important Data
- Nice-to-have Data
Data that must always be accurate
Time-Based Strategy
Performance Optimization
Cache Warming
Pre-populate cache on server start.Batch Caching
Cache multiple items at once.Conditional Caching
Decide whether to cache based on conditions.Cautions
Strategy Summary Table
| Data Type | TTL | Grace | Tags | Invalidation |
|---|---|---|---|---|
| Static Config | forever | ❌ | ["config"] | Manual |
| User Profile | 1h | ❌ | ["user"] | On change |
| Product Info | 30m | 1h | ["product"] | On change |
| Post List | 5m | 30m | ["post", "list"] | On create/update |
| Real-time Stats | 1m | 10m | ["stats"] | TTL dependent |
| Aggregated Dashboard | 10m | 2h | ["dashboard"] | TTL dependent |