Skip to the page

Redis and caching · mid

Cache-aside, invalidation and stale prices

In cache-aside, the app reads the cache first and fills it from the database on a miss. The hard part is invalidation: after a write, delete the key, and plan for every cache layer.

The notes

What you must know

  • Read: get the key. On a miss, read the database and set the key with a TTL.
  • Write: update the database, then delete the key. Deleting is idempotent, and two writers cannot leave their values in the wrong order. Updating the cache from two writers can.
  • Deleting before the database write is worse: a reader can refill the old value before the write commits.
  • A race remains: a reader misses and reads the old row, the writer commits and deletes, then the reader sets the old value. It stays until the TTL. Reduce it with short TTLs for volatile fields, a delayed second delete, or version numbers.
  • If the delete fails, retry through a queue or an outbox. The TTL is the safety net, so every key needs one.
  • Do not refill from a lagging replica. Refill from the primary right after writes.
  • Change data capture (for example Debezium reading the binlog or WAL) can delete keys for every change, whichever code made it.
  • Many layers can hold a stale value: CDN, Redis, a cache inside each process, the search index. A price change must reach all of them. Checkout must read the database, not a cache.

The red pen

Common traps: mistake → fix

  • Mistake: Update the cache in the same code, it is fine

    Fix: concurrent writers can leave an old value that stays.

  • Mistake: No TTL is needed if we invalidate

    Fix: a failed delete then lives forever.

  • Mistake: Clear all of Redis to fix a stale value

    Fix: it causes a stampede on the database.

  • Mistake: Only Redis caches the price

    Fix: check the CDN, in-process caches and the search index too.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain cache-aside.
  2. On a price change, do you update the key or delete it, and in what order?
  3. Customers still see the old price after an hour. How do you find the cause?
  4. Which values must never be served from a cache?

Practise

Practise with these questions

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