Expiry with a sidecar dict

Sessions, caches, rate limiters all need keys that disappear on their own. We add a parallel dict from key to expiry timestamp. Every read checks if a key has expired and lazily deletes it.

04-expiry/server.py
python
EXPIRES: dict[str, float] = {}  # key -> unix ts when it dies

def _check_expired(key: str) -> bool:
    ts = EXPIRES.get(key)
    if ts is None:
        return False
    if time.time() >= ts:
        STORE.pop(key, None)
        EXPIRES.pop(key, None)
        return True
    return False

def _store_get(key):
    _check_expired(key)
    return STORE.get(key)

EXPIRES is the sidecar. _check_expired runs on every read. Lazy means we never sweep, we only delete when someone touches the key.

Lazy vs active expiry

Lazy: clean up on read. Active: clean up on a timer. Real Redis does both.

Yes, until something reads it. That is the lazy-expiry leak. Real Redis adds active expiry: a periodic timer that walks a random sample of TTL keys and deletes any past their deadline. We add this in the event-loop step.

Quiz: Quiz

Loading practice…

AI prompt: Try it: reproduce the lazy-expiry leak

Loading practice…