StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 15 · Caching

Low-Level Cache Aside

mediumDjango CachingCaching—No data yet

Problem statement

In this Django project, make one helper the only place a product's price summary is looked up. The summary costs two queries to work out, and two pages ask for it constantly: the product page grew its own little cache under a key and a timeout it invented, the catalogue page recomputes every row on every render, and neither write route tells anyone that a price change or a delete has just made those numbers wrong.

Requirements

Implement:

  • summary_cache_key, get_price_summary and invalidate_price_summary in app/cache_aside.py
  • the lookups in catalog_summary, product_summary, product_price_change and product_delete in app/views.py

Only those two files change. Product (app/models.py, read-only) has a name, a unique slug and a unit_price, and orders by name; PriceAdjustment has a label, a signed amount and a product. A product's price today is its unit_price plus every one of its adjustments. app/pricing.py (read-only) holds compute_price_summary(product_id), the expensive source: it returns a dict of product_id, name, base_price, final_price and adjustments, and raises Product.DoesNotExist for a product that is no longer there. It also holds CALLS, a module-level counter of how many times it has done the work; the tests read it, because two reads that return the same numbers are indistinguishable from the outside.

RouteNameView
/catalog/catalog-summarycatalog_summary
/products/<slug>/product-summaryproduct_summary
/products/<slug>/price/product-price-changeproduct_price_change
/products/<slug>/delete/product-deleteproduct_delete

Both templates exist and neither changes. CACHES is already configured, and PRODUCT_SUMMARY_CACHE_SECONDS in project/settings.py is how long a stored summary stays usable.

1. summary_cache_key(product_id) - the key

  • It returns the key one product's summary is stored under, and the scheme is fixed, because it is what the tests look under: ``text product:summary:<product id> ``
  • Every read and every write in the project builds its key by calling this function, so no caller is free to spell it differently. One key names one product: three products must not end up sharing an entry.

2. get_price_summary(product_id) - the read

  • On a hit it returns the stored value and does not call the source, so a second lookup of the same product leaves CALLS where it was and returns the same summary as the first.
  • On a miss it calls compute_price_summary, stores what came back under the key from requirement 1 with settings.PRODUCT_SUMMARY_CACHE_SECONDS as the timeout, and returns it.
  • Once that window has passed the entry is gone, so the next read is a miss and recomputes. Storing with no timeout at all, or with a number of your own, fails that.
  • One product is one entry, so warming one product never warms another.

3. One lookup for every caller

  • product_summary and catalog_summary both read through get_price_summary. The hand-rolled cache in product_summary, with its made-up key and made-up timeout, and the direct call to the source in catalog_summary both go.
  • A cold product page then computes exactly one summary and leaves it in the cache under the documented key; a cold catalogue computes one per product and stores each of them.
  • Once both pages go through the helper they share entries: a summary the product page warmed is one the catalogue does not pay for, so a cold product page followed by a cold catalogue over three products costs three computations in all.
  • What the two pages show never changes: the product page still reports the list price, the price after every adjustment and how many adjustments were applied, and the catalogue still lists every product with its list price and its price today, in name order.

4. invalidate_price_summary(product_id) and the writes

  • Two writes make a stored summary wrong, and both drop it through this function: product_price_change, after saving the new list price, and product_delete, after the product is gone. Both still redirect, so both answer 302.
  • The next read of that product then recomputes, which for a changed price means the new numbers reach the page, and for a deleted product means reaching the source and raising Product.DoesNotExist rather than being served the summary of something that no longer exists.
  • Every other product's entry is still there afterwards, and still served without recomputation.

Notes

  • The low-level API is three calls: cache.get(key), cache.set(key, value, timeout) and cache.delete(key). Cache-aside means the caller owns the sequence - ask the cache, and only on a miss go to the source and store what came back.
  • Use django.core.cache.cache. Do not memoize in a module-level dict, a class attribute or an lru_cache: a process-local dict is not shared, not expirable and not invalidatable.
  • A read and a write that spell the key differently cannot find each other's entries, which is why the scheme lives in summary_cache_key and the views call it too.
  • Invalidate by deleting the one key. cache.clear() throws away everything the whole site has cached, and writing a fresh value over a stale one is not invalidation either.
  • Do not touch compute_price_summary, CALLS, the models, the templates or the settings.
  • Do not reach for cache_page or template fragment caching: this is a value, not a page.
  • Nothing outside requirements.txt is available.

More in Caching

See the module
Cached Expensive ViewThe sales report page folds every sale row together on every single hit, although the table it reads changes a few times a day at most. Cache the whole page response for the defined window so a repeat request inside it never runs the aggregation, the first request after it does, and each query string keeps its own entry.—No data yetmediumFragment Cached SidebarEvery category page recomputes an expensive trending sidebar on every single request, while the rest of the page has to stay dynamic and must not be cached. Cache just the sidebar with a template fragment keyed by the category slug, leaving everything around it rendered per request.—No data yetmediumLayered Store CachingThe storefront caches nothing: the product page rebuilds itself on every hit, the catalogue pays for every product's facts on every render, and a price change walks away leaving the figures it just made wrong on display. Put a page cache on the product page, a cache-aside helper behind every facts read and a cached fragment around each trending row, all keyed by product id, and make a price change drop exactly that product's three entries.—No data yetmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.