Skip to main content
Effective caching requires choosing strategies that match data characteristics. This guide covers various cache strategies and how to use them.

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

Data that rarely changes
TTL: "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
Long TTL:
  • Data up to 1 hour old
  • Recalculates on expiration (slow)
Recommendation: Use Grace for heavy operations

Namespace Strategy

What is Namespace?

Namespace is a feature that logically isolates caches.

Per-User Isolation

Advantages:
  • 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 needed
@cache decorator automatically implements this pattern

2. Write-Through

Update cache on write: Update cache simultaneously with data change
Advantage: Cache always up-to-date Disadvantage: Write performance degradation

3. Write-Behind (Write-Back)

Write to cache first: Update cache then asynchronously save to DB
Advantage: Fast response Disadvantage: Complex implementation, potential data loss

4. Refresh-Ahead

Pre-refresh before expiration: Prepare fresh data before TTL ends
Grace period serves this role

Combined Strategies

TTL by Layer

Strategies by Priority

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

Cache Strategy Selection Cautions:
  1. TTL Too Long: Serves stale data
  2. TTL Too Short: Reduced cache effectiveness
  3. Grace Overuse: Grace unnecessary for fast queries
  4. Namespace Overuse: Too many namespaces are hard to manage

Strategy Summary Table

Next Steps

Cache Configuration

Configure Stores and Drivers

@cache Decorator

Apply caching to methods

Cache Invalidation

Tag-based cache invalidation