Skip to the page

Data, ORMs and caching · mid

Caching with Redis: cache-aside, TTL and invalidation

Cache-aside means the app first reads from the cache (Redis), and on a miss reads the database, stores the result with a TTL and returns it, while writes update the database and delete the cached key, accepting that the cache can be briefly stale.

The notes

What you must know

  • Cache layers: browser (Cache-Control), CDN, application cache (Redis or in-process LRU), database buffer cache. Cache as close to the user as the data's privacy allows.
  • Redis: in-memory key-value server with data structures (strings, hashes, lists, sets, sorted sets, streams), TTL per key (SET key value EX 60), atomic operations; Redis 8 and the Valkey fork are the current lines.
  • Cache-aside (lazy loading): read -> GET; miss -> query DB -> SET with TTL. Write -> update DB, then DELETE the key (do not try to update both perfectly).
  • Write-through: write to cache and DB together. Write-behind: write to cache, flush to DB later (risk of loss). Read-through: the cache library loads on a miss.
  • TTL is your safety net against stale data and forgotten invalidations; add jitter so many keys do not expire at once.
  • Keys must include everything that changes the answer: user id, locale, filters, version (e.g. product:42:v3:en). Never cache per-user data under a shared key.
  • Do not cache what must be exactly current (balances at payment time, stock at checkout); measure hit rate and memory.

The red pen

Common traps: mistake → fix

  • Mistake: Caching fixes a slow query

    Fix: it hides it; fix the query and cache what is hot.

  • Mistake: Update the cache on write instead of deleting

    Fix: two concurrent writers can leave the older value in the cache; delete and let the next read reload.

  • Mistake: Cache personalised responses under the URL alone

    Fix: users see each other's data.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you use Redis in your projects? What is a TTL?
  2. Explain cache-aside step by step for reads and writes.
  3. How do you keep the cache consistent with the database?
  4. What would you never cache?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview