Start learning free

LESSON 184 OF 188 · BACKEND: INTERVIEW QUESTIONS

A Key-Value Store with Expiry

Practice

The interview question: "Build a tiny Redis: PUT /kv/<key>?ttl=60 stores a value that lives 60 seconds, with GET and DELETE too. How do keys expire?" The expected answer: when you write a key, keep the moment it dies, not a countdown, and run no timer. When a read finds a key whose moment has come, delete it and answer 404. That's lazy expiry. Real stores also sweep a few keys in the background, for the dead keys nobody reads.

The same trick works for anything that runs out, like a login session that lasts 15 minutes:

session = {"user": "ana", "expires": now() + 900}

if now() >= session["expires"]:
    print("Please log in again")

The tests never wait: they move a hidden clock. So always ask the given now() for the time, never time.time(). Use >=: a key set at 1000 with ttl 60 is already dead at 1060.

Your code must give these answers:

PUT /kv/greeting?ttl=60  {"value": "hello"}  at clock 1000  →  200  {"key": "greeting", "value": "hello"}
PUT /kv/theme?ttl=3600   {"value": "dark"}   at clock 1000  →  200  {"key": "theme", "value": "dark"}
GET /kv/greeting  at clock 1059  →  200  {"key": "greeting", "value": "hello"}
GET /debug/keys   at clock 1060  →  200  ["greeting", "theme"]
GET /kv/greeting  at clock 1060  →  404  {"error": "Key not found"}
GET /debug/keys   at clock 1060  →  200  ["theme"]
GET /kv/theme     at clock 1060  →  200  {"key": "theme", "value": "dark"}
PUT /kv/greeting        {"value": "hi"}  →  400  {"error": "ttl must be a whole number above 0"}
PUT /kv/greeting?ttl=0  {"value": "hi"}  →  400  {"error": "ttl must be a whole number above 0"}

Your task: the routes, store and now() are given. In put_value, read ttl from the query string as a whole number, answer 400 with the error above when it is missing or not above 0, and keep the moment the key dies in entry["expires"]. In get_value, before the 404 check, delete the key when it is stored and now() has reached its "expires".


Assignment
Follow the Coding Tutorial to add the ttl check and the expiry moment to put_value, and lazy expiry to get_value.


Hint
request.args.get("ttl", type=int) gives None for a missing or non-number ttl. Check for None before comparing with 0, because comparing None with a number crashes.


STEP 1 OF 6
    Ctrl + Enter to check