BE4: Caching with Redis

Lesson 5 of 5 · reading 15–25 minutes; practice and project time is on the module page

When Redis is down, and HTTP caching

🎯You'll be able to

Keep an endpoint working (more slowly) when the cache is unavailable, and use HTTP cache headers where they help.

🏠The everyday picture

When the canteen's display board breaks, the staff read prices from the printed price list. Service is slower, but nobody goes hungry.

📘What it really is

📝A worked example

Input: Redis stops while the API is running; a customer loads kitchen 7's menu.

Steps in the finished getMenu():

  1. redis.get(...) fails within 500 ms (timeout or "connection closed").
  2. The catch loads the menu from the database (2 queries, about 20 to 60 ms).
  3. The response is sent with X-Cache: BYPASS.
  4. When Redis is back, the next requests miss, load and cache again; X-Cache: HIT returns.

Expected output: the menu answers correctly within about a second while Redis is down. The kit's cache test 9 cuts the connection to Redis on purpose to check this.

🌍Where it's used

📝Case scenario

An API uses Redis with default client settings: an offline queue and long retries. When Redis restarts for an upgrade, every menu request waits 20 seconds for a reply that never comes; the app's own timeouts fire and the site is "down" though the database is fine. With short timeouts and a database fallback, customers would have seen menus a little slower for a minute.

🖱️Try it

With the starter kit running, stop Redis (redis-cli shutdown, or stop the Docker container) and load a menu, then start Redis again. Note what happens. Also check which Cache-Control header (if any) GET /v1/me/orders sends. Success: you can explain what your finished version should do in both cases.

⚠️Common mistakes

🛠️For your project

Project 2 test 9 cuts Redis and expects a correct menu within 1.5 seconds, then caching again once Redis is back.

✅Quick check

What should the menu endpoint do if Redis doesn't answer?

Show the answer

Give up on the cache quickly and serve the menu from the database.

Which Cache-Control value suits a customer's own order list?

Show the answer

private or no-store, so shared caches never keep it.

← PreviousStampedes and hot keys
ProLearners Assist