Start learning free

LESSON 64 OF 66 · NOSQL: REDIS

Cache a Slow Answer

Practice

Some answers are slow to get, like a big database query or a call to another service. When the same question comes again, you can keep a copy of the first answer in Redis and give that back instead. This copy is a cache. The lesson runs on an in-memory Redis that takes the same commands. The same code runs on a real Redis server.

Every read follows the same plan. Look in Redis first. If the key is there, it's a hit, and you return the copy. If r.get gives back None, it's a miss: run the slow function, store its answer in Redis, and return it. The next read of the same key is then a hit.

Redis keeps strings, not dicts, so a dict goes in as JSON text. json.dumps turns the dict into text, and json.loads turns the text back into a dict. With ex=, the copy goes away by itself, so an old answer doesn't stay forever:

user = {"name": "Ana", "city": "Oslo"}
r.set("user:7", json.dumps(user), ex=60)
text = r.get("user:7")             # '{"name": "Ana", "city": "Oslo"}'
print(json.loads(text)["city"])    # Oslo

The script asks for product 1, product 1 again, then product 2. slow_product writes each id it is asked for into calls. With the cache, the second read of product 1 costs nothing. After your code runs, the check prints what Redis holds under product:1 and how many seconds it has left:

{'name': 'Mug', 'price': 12}
{'name': 'Mug', 'price': 12}
{'name': 'Lamp', 'price': 29}
Slow calls: [1, 2]
Stored: {"name": "Mug", "price": 12}
TTL: 300

Your task: finish get_product(product_id). Build the key product: plus the id, look it up with r.get, and on a hit return it through json.loads. On a miss, after the slow_product call that's already there, store the product with r.set as JSON for 300 seconds.


Assignment
Follow the Coding Tutorial to add the Redis lookup and the store to get_product, so a second read of the same product never calls slow_product.


Hint
r.get gives None when the key isn't there, so test cached is not None. Redis keeps text: json.dumps on the way in, json.loads on the way out, and ex=300 keeps the copy for 5 minutes.


STEP 1 OF 5
    Ctrl + Enter to check