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

Layered Store Caching

mediumDjango CachingCaching—No data yet

Problem statement

In this Django project, cache the storefront at the three grains its repetition actually has. The product page rebuilds a whole response on every hit, the catalogue pays for every product's facts on every render, and the trending sidebar re-scores the shelf for a panel nobody expects to be live to the second, so one cache in one place cannot fix all three. The one route that changes a product answers a redirect and tells nobody, so every stale figure keeps being served until it happens to fall out on its own.

Requirements

Implement:

  • get_product_facts, invalidate_product_facts, invalidate_product_trend and invalidate_product_page in app/cache_layers.py
  • the caching and the invalidation calls in app/views.py
  • the cached trending row in app/templates/app/catalogue.html

Only those three files change. The routes are given in app/urls.py: GET /catalogue/ (named catalogue) carries a per-request serial, a trending row per product in an <aside> and a facts row per product in the main list; GET /products/<id>/ (named product-page) is one product's page and also answers ?variant=gift, which quotes a gift-wrapped price instead of the plain one; POST /products/<id>/ changes that product's list price and redirects back with 302, and is the only write in the project.

app/storefront.py is given and read-only. It holds the three expensive computations, one per surface, each with its own call log: compute_product_detail(product_id, variant=None) behind the product page's body, appending to DETAIL_CALLS; compute_product_facts(product_id) for one facts entry, appending to FACTS_CALLS; and compute_product_trend(product_id) for one trending row, appending to TREND_CALLS. The tests read those lists, because two reads that return the same figures look identical from the outside. A fourth counter, PAGE_RENDERS, is appended to by {% count_render %} in the given product page template, which is what tells a response handed back whole by a page-level cache apart from a view that remembered only its figures and rebuilt the page around them.

app/storefront.py also gives the page layer two things: PAGE_VARIANTS, which is (None, "gift") - every variant the product page answers on, with None meaning the plain URL - and page_cache_request(request, product_id, variant=None), which builds an equivalent GET request for one product's page URL out of the live request, so its scheme and host match whatever the project is being served on.

The three windows are in project/settings.py, which is read-only: PRODUCT_PAGE_CACHE_SECONDS, PRODUCT_FACTS_CACHE_SECONDS and PRODUCT_TREND_FRAGMENT_SECONDS, two seconds each, short because the tests prove the expiry by waiting out real time rather than by pretending the clock moved. CACHES is configured there too. The catalogue view already hands PRODUCT_TREND_FRAGMENT_SECONDS to its template as trend_seconds.

1. get_product_facts(product_id) - the facts entry, through one helper

  • It is a cache-aside read: return the stored entry when there is one, and otherwise call compute_product_facts(product_id), store the result and return it.
  • The key is the product's id in this exact scheme: ``text product:<product id>:facts ``
  • The timeout is settings.PRODUCT_FACTS_CACHE_SECONDS. A read on an empty cache computes once and stores, a read inside the window computes nothing, and a read after the window computes again.
  • Both surfaces read through it: the catalogue builds facts_rows from the helper instead of from compute_product_facts, and the product page gets its facts from the helper too. Two surfaces, one entry per product, so once the catalogue has filled a product's entry the product page reads it without computing.

2. The product page's whole response

  • product_page in app/views.py caches its response for settings.PRODUCT_PAGE_CACHE_SECONDS.
  • A second request for the same URL inside the window comes back 200 and is the same page the first request got, with the same detail-serial. The detail computation does not run again, and PAGE_RENDERS does not grow either, so what comes back is the stored response and not a rebuilt one.
  • The stored page belongs to the URL rather than to one client, so a second visitor asking for the same URL is served it too.
  • More than PRODUCT_PAGE_CACHE_SECONDS later the next request computes afresh, and the page then shows detail-serial of 2.
  • /products/<id>/ and /products/<id>/?variant=gift are two entries, each quoting its own price, and storing one leaves the other exactly as it was.
  • The POST to the same URL is not a cached page and is not stored as one; it still runs every time.

3. The trending row - one fragment per product

  • In app/templates/app/catalogue.html, the one <div class="trend-row"> inside the loop, with its {% trending_score %} call, ends up inside a cached fragment, and nothing else does.
  • The window is trend_seconds, the fragment name is exactly product_trend written bare in the tag, and the block varies on the product's id. A quoted name or a different varying value is a different entry from the one the tests look under with make_template_fragment_key("product_trend", [product_id]).
  • The sidebar is then one entry per product: each row's score is computed once per window, each product keeps its own entry, and after the window the rows are rendered again.
  • The per-request serial and the facts list outside the block are still rebuilt for every request.

4. A price change drops that product's three entries, and nothing else

  • invalidate_product_facts(product_id) deletes the facts key from requirement 1.
  • invalidate_product_trend(product_id) deletes the fragment from requirement 3, named with make_template_fragment_key and the same varying value.
  • invalidate_product_page(request, product_id) deletes the page entries from requirement 2. The page-level key was hashed from a URI, so ask django.utils.cache.get_cache_key for each one, handing it page_cache_request(request, product_id, variant) for every variant in PAGE_VARIANTS, and delete every key it gives back that is not None.
  • change_price in app/views.py calls all three after the price is saved.
  • After the write, the next read of that product recomputes at all three layers and shows the new price in the detail, the facts and the trending row alike. The next read of any other product is still a cache hit at all three.

Notes

  • Which cache fits depends on what repeats: a whole response is the page-level decorator, a single value is the low-level cache.get/cache.set pair behind one helper that owns the key, and one region of an otherwise per-request page is a template fragment.
  • The page-level key is built from the request's full URI, which is why one page answering on two query strings holds two entries and both are stale after a write.
  • Do not re-implement any of the three computations, and do not edit app/storefront.py; the tests count its calls.
  • Cache the product page's response, not a value inside the view body: on a cache hit the page must not be rendered again, and PAGE_RENDERS is how that is checked.
  • Cache one trending row, not the whole sidebar and not the whole catalogue: the per-request serial has to change on every request.
  • Invalidate by naming keys. cache.clear() is not invalidation, and a test asserts that another product's three entries survive a write.
  • Every entry at every layer is keyed by the product's id, so each product's three entries can be dropped on their own.
  • Leave the catalogue's request_serial, trend_seconds and context names alone, and keep the given templates' ids and classes: the pages are compared element by element.
  • Nothing outside requirements.txt, and no second cache backend: CACHES is configured and read-only.

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 yetmediumLow-Level Cache AsideOne hot price lookup hammers the database from two different pages, and each caller either invented its own caching or did without. Centralize the lookup in a cache-aside helper that reads the cache, computes and stores on a miss under the documented key and timeout, and drops a product's entry whenever a price change or a delete makes it wrong.—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 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.