ElastiCache — Caching Patterns

Caching is about reducing database hits by storing frequently accessed data in fast memory (ElastiCache). There are different strategies depending on how your data is read and written.


1. Lazy Loading (Cache-Aside)

Load data into cache only when it is requested — nothing is cached until someone actually asks for it.

Analogy: Like loading apps on your phone only when you open them. Nothing runs in the background until needed.

How It Works

Step 1: App requests data
            ↓
Step 2: Check cache
            ↓
      Cache Hit? ──── YES ──→ Return data immediately (Fast)
            │
           NO (Cache Miss)
            ↓
Step 3: Read from database (Slow)
            ↓
Step 4: Return data to app
            ↓
Step 5: Write data to cache for next time
            ↓
Next request for same data = Cache Hit (Fast)

Pros

Cons


2. Write-Through

Update the cache every time you write to the database — cache is always in sync.

Analogy: Like updating both your notebook and whiteboard at the same time. Both always show the same thing.

How It Works

App writes data (INSERT / UPDATE)
            ↓
Write to database first
            ↓
Write to cache immediately after
            ↓
Database and cache are always in sync