Find the bug · #62 · Caching and state Easy Python
A price change doesn’t show up
An admin updates a price, but the shop keeps showing the old one.
On this page
The report
Admins can change a product’s price. The change is saved, but the shop keeps showing the old price until the server restarts.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Catalog:
def __init__(self, db):
self.db = db
self.cache = {}
def price(self, sku):
if sku not in self.cache:
self.cache[sku] = self.db[sku]
return self.cache[sku]
def update_price(self, sku, new_price):
self.db[sku] = new_priceRead it, then pick a line.
After the price is saved, what does the cache still hold?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
cat = Catalog({"pen": 20})
print(cat.price("pen"))
cat.update_price("pen", 25)
print(cat.price("pen"))It prints
20 20
It should print
20 25
Show the answer: the bug, the fix, and how you’d find it
The bug (line 12)
Line 12 saves the new price to the database, but the cache still holds the old one, and price answers from the cache first. Nothing ever clears it, so the old price lives until the server restarts. Whenever the data changes, drop (or update) its cache entry.
The fix
10 11 def update_price(self, sku, new_price):12 self.db[sku] = new_price13 self.cache.pop(sku, None)How you’d find it
- Reproduce: read the price (it gets cached), update it, read it again. Still the old price.
- Check the database: the new price is there. So the read path is serving stale data from the cache.
- Look for where the cache is cleared on a write: nowhere.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
cat = Catalog({"ink": 100})
cat.price("ink")
cat.update_price("ink", 120)
assert cat.price("ink") == 120Where else this bites
- “There are only two hard things in computer science: cache invalidation and naming things.”
- A CDN serving an old JavaScript file after a deploy.