Choosing a cache pattern
medium 24 minCache-aside, write-through and write-back differ in what happens on a save, what a reader can see and what a crash can take.
See it run
Three patterns, a few questions, and what each answer costs you.
Operations
Walk the questions
Start with the main worry. Each answer leads to another question or to a pattern.
Step 1 of 5
Main worry?
Reads, writes, or seeing the latest value. Pick the one that hurts.
Step 1: Main worry?
def choose(worry, changes, loss_ok, read_own_save): if worry == "reads": if changes == "rarely": return "cache-aside" if changes == "sometimes": return "write-through" return "write-back" if loss_ok else "write-through" if worry == "writes": return "write-back" if loss_ok else "no write cache" return "write-through" if read_own_save else "cache-aside"- When
- 2 minutes
- You leave with
- One choice, one reason
- Starting with a pattern
- the reason comes too late
Say the question and its answer out loud. The path is the argument.
In the real world
The same choosing a cache pattern doing real jobs. Pick one and step through it.
A million readings a second arrive. A rare loss is fine.
Step 1 of 3
Through the database
- Database load
- 100%
One row per reading does not fit on one database.
Step 1: Through the database
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Choosing before asking
criticalWithout the read and write rates and the allowed loss, any pattern is a guess.
Wrongpattern = "write-through" # sounds safeRightpattern = choose(worry, changes, loss_ok, read_own_save)Believing write-through makes the pair exact
majorTwo writes to two systems can fail apart or arrive in different orders. Readers can also be between them.
Wrong# consistent, so check the balance in the cacheif cache.get("balance:42") >= 20: pay()Rightwith db.transaction(): if db.balance(42, lock=True) >= 20: pay()One pattern for the whole system
majorCatalogue pages and payments have different needs.
WrongCACHE_PATTERN = "write-back"RightCACHE_PATTERN = {"views": "write-back", "catalogue": "cache-aside"}Forgetting the read side
minorWrite-through and write-back describe saves. Reads still need a fallback when the copy is missing.
Wrongreturn cache.get(key)Rightreturn cache.get(key) or load_and_fill(key)
Interview tips
How to explain it
- Ask about reads, writes, allowed age and allowed loss.
- Pick per kind of data.
- Say what you give up.
Memory trick: ATB
- Aside: ask the cache first, then go aside to the database.
- Through: the write goes through both before the answer.
- Back: the write goes back to the database later, in batches.
Quick picks
- Read-heavy, a little stale is fine: cache-aside.
- Must see own save: write-through.
- Write-heavy, small loss is fine: write-back.
Or no cache
- Money, stock at checkout, seats.
- Every request asks for something else.
- An index would be enough.