Cache a Read (Cache-Aside)
Your bookstore API serves one read GET/books/{id} and it's expensive: the detail page compares
each book to its genre, scanning and summing. Every read hits Postgres, which is pinned at its CPU limit
while latency climbs and a fresh empty Redis instance is already deployed alongside it, waiting to be used.
Nothing ever writes to the database. The catalog is seeded once and read forever, so a book's answer never changes and an expensive read that never changes is the easiest thing in the world to cache. That's exactly why it's the right place to learn the pattern.
System Architecture
Your task
Make the read cache-aside serve the answer that never changes from Redis instead of recomputing it in Postgres every time.
cache.py is already written for you, a configured Redis client plus cache_key(), lookup()
and store(). Your whole job is to wire it into one function:
books.py::detail()goes to Postgres every time. Make it cache-aside: build the key → ask the cache → a hit means you're done → on a miss, read the DB → store the result so the next reader doesn't pay. The imports and the step-by-step comments are already in the file.- No
invalidateneeded: nothing writes, so a cached answer can never go stale.
Done when
- Response errors = 0: every response verifies against the real dataset. Wrongly-keyed or fabricated entries count as failures.
- Read latency p50 < 50 ms: the median read time. A working cache lands at a few ms; doing nothing leaves it at seconds. (Grading starts at Submit, so give the cache a few seconds of traffic to warm first.)
- Cache-aside is three steps, in order: look up → on a miss read the DB → store the result. A hit returns early.
- The key is the design:
book_detail:{id}include the id, or you'll serve one book's data for everyone.