← All bricks

Node / TS · Intermediate

Redis Cache Layer with TTL & Eviction Awareness

Add a cache-aside layer in front of a slow data source — with TTL, a key convention, and a fallback so a cache outage never becomes a service outage.

A cache makes reads fast — until it makes an incident worse. Here we put a Redis cache-aside layer in front of a slow data source, one small change at a time: read-through, write-back, a TTL, a key naming convention, and the detail most tutorials skip — what happens when Redis itself is slow or full. We build the cache helper a few lines at a time so the pattern stays obvious.

What you'll build

  • Implement the cache-aside (read-through) pattern
  • Add a TTL so cached data cannot go stale forever
  • Adopt a consistent key naming convention
  • Fall back to the source when the cache is unavailable
  • Reason about memory limits and eviction

Contents

  1. An empty Node service
  2. A service to cache for
  3. Make it listen
  4. A deliberately slow source
  5. Read straight from the source
  6. Add a Redis
  7. Connect to Redis
  8. Cache-aside: the read path
  9. Write back on a miss
  10. Give entries a TTL
  11. Put the cache on the hot path
  12. Survive a cache read failure
  13. Make the write best-effort too
  14. Bound the memory