DatabasesIntermediate5h

Redis & caching.

In-memory stores, cache strategies, and invalidation.

What is caching?

A cache stores the result of expensive work so the next request can skip it. Redis is the standard in-memory store for this: data lives in RAM, so reads and writes are sub-millisecond. Used well, caching is the cheapest large performance win available to a backend.

Why it matters

Databases are the usual bottleneck, and a cache in front of hot queries removes most of the load. But caching adds a hard problem — keeping cached data from going stale — and a careless cache serves wrong data confidently. Knowing both the win and the danger is what separates safe caching from bugs.

What to learn

  • Redis as a key-value store: strings, hashes, lists, sets
  • Cache-aside: check cache, fall back to the database, fill cache
  • TTLs and expiry
  • Invalidation strategies and why it is hard
  • Redis for sessions, rate limiting, and queues
  • The thundering-herd problem and how to avoid it
  • When not to cache

Common pitfall

Caching without an invalidation plan, so users see stale data after an update. Decide up front how each cached value gets refreshed — a TTL, an explicit delete on write, or both. "There are only two hard problems in computer science" is a joke about exactly this; treat invalidation as part of the design, not an afterthought.

Resources

Primary (free):

Practice

Put a cache-aside layer in front of one slow query. On a request, check Redis first; on a miss, query Postgres, store the result with a TTL, and return it. Then add an explicit cache delete when the underlying row is updated. Confirm a second request is served from cache and an update is reflected immediately.

Outcomes

  • Implement the cache-aside pattern over a slow query.
  • Choose a TTL and an invalidation strategy for a value.
  • Use Redis for sessions or rate limiting, not just caching.
  • Explain how stale cache data happens and how to prevent it.
Back to Backend roadmap