Why Caching Is the First Performance Fix

Reading from memory takes microseconds; a database query can take milliseconds; a cross-region API call can take hundreds of milliseconds. A cache keeps copies of frequently used data somewhere faster, so most requests never touch the slow source.

Caching is easy to add and famously hard to get right. As the old joke goes, there are two hard things in computer science: cache invalidation, naming things, and off-by-one errors. This guide covers the main strategies and the traps.


🎯 Quick Answer (30-Second Read)

  • Cache-aside (lazy loading): the app checks the cache, and on a miss reads the database and fills the cache. The most common pattern.
  • Read-through: the cache itself loads missing data from the database.
  • Write-through: writes go to the cache and database together; reads are fresh, writes are slower.
  • Write-back (write-behind): writes go to the cache first and reach the database later; fast, but risky.
  • TTL + eviction (LRU/LFU) keep the cache from serving stale data forever or running out of memory.
  • Watch for: stale data, thundering herds (cache stampedes), and caching errors or empty results.

Where Caches Live

flowchart LR U["👤 User"] --> B["Browser cache"] B --> CDN["CDN edge cache"] CDN --> APP["App server
(in-memory cache)"] APP --> R[("Distributed cache
Redis / Memcached")] R --> DB[("Database
(+ its own buffer cache)")]

Each layer saves a trip to the next. Static files belong at the CDN; computed results and database rows usually belong in Redis.


The Strategies

1. Cache-Aside (Lazy Loading)

sequenceDiagram participant A as App participant C as Cache (Redis) participant D as Database A->>C: GET user:42 alt Hit C-->>A: user data else Miss C-->>A: (nothing) A->>D: SELECT * FROM users WHERE id=42 D-->>A: user data A->>C: SET user:42 (TTL 10 min) end
def get_user(user_id):
    key = f"user:{user_id}"
    cached = redis.get(key)
    if cached:
        return json.loads(cached)
    user = db.fetch_user(user_id)
    redis.set(key, json.dumps(user), ex=600)   # 10-minute TTL
    return user

Pros: simple; only caches what's actually requested; cache failure doesn't break reads. Cons: first request is slow; data can be stale until TTL or invalidation.

2. Read-Through

Like cache-aside, but the cache library or service loads from the database on a miss. Cleaner app code, same staleness trade-offs.

3. Write-Through

Every write updates the database and the cache together. Reads are always fresh, at the cost of slower writes and caching data that may never be read.

4. Write-Back (Write-Behind)

Writes go to the cache and are flushed to the database later in batches. Very fast writes, but if the cache crashes before flushing, data is lost. Use only when that's acceptable (counters, analytics) or with durable queues.

Strategy Read freshness Write speed Risk
Cache-aside Stale until TTL/invalidation Normal Low
Read-through Same as cache-aside Normal Low
Write-through Fresh Slower Low
Write-back Fresh in cache Fastest Data loss on crash

Invalidation: Keeping Data Fresh

  • TTL: every entry expires after a time; simplest safety net
  • Delete on write: when data changes, delete the cache key (safer than updating it, which can race)
  • Versioned keys: user:42:v7, bump the version on change
  • Event-driven invalidation: publish "user 42 updated" so all caches drop it
  • Tag-based invalidation: frameworks like Next.js let you revalidate everything tagged blog at once
Watch out: "update DB, then update cache" can race: two writers may finish in a different order in the cache than in the database, leaving stale data forever. "Update DB, then delete cache key" plus a TTL is the safer default.

Eviction: When the Cache Is Full

Policy Evicts Good for
LRU (least recently used) Items not accessed recently Most workloads
LFU (least frequently used) Items accessed least often Stable popular items
TTL-based Expired items first Time-sensitive data
Random Random items Simple, surprisingly OK

Redis lets you configure the policy with maxmemory-policy (for example allkeys-lru).


The Cache Stampede

When a popular key expires, thousands of requests miss at once and all hit the database together, sometimes taking it down.

Fixes:

  • Locking / single flight: only one request rebuilds the value; others wait or get the old value (Distributed Locks Explained)
  • Stale-while-revalidate: serve the expired value while refreshing in the background
  • Jittered TTLs: add randomness so keys don't expire together
  • Pre-warming hot keys before big events

Frequently Asked Questions

What is the most common caching strategy?

Cache-aside, also called lazy loading. The application checks the cache first, and on a miss reads from the database and stores the result in the cache with a TTL. It's simple, caches only requested data, and reads still work if the cache fails.

What is the difference between write-through and write-back caching?

Write-through writes to the cache and database at the same time, keeping them consistent but slowing writes. Write-back writes to the cache first and updates the database later, which is faster but can lose data if the cache fails before flushing.

How do you prevent a cache stampede?

Let only one request rebuild an expired key using a lock or single-flight mechanism, serve stale data while refreshing in the background, add random jitter to TTLs so keys don't expire together, and pre-warm popular keys before known traffic spikes.


Conclusion

Start with cache-aside plus TTLs, invalidate by deleting keys when data changes, choose an eviction policy like LRU, and protect hot keys from stampedes. Use write-through when reads must always be fresh, and write-back only when occasional data loss is acceptable.


Sources

Last verified: 2 November 2026.


Related reads: Redis Explained · Distributed Locks Explained · URL Shortener System Design · Horizontal vs Vertical Scaling

I write about system design and how real products are built. Follow on LinkedIn or X, or invite me to speak.