MediumStateful DesignPython 3

TTL Key/Value Store

Build a deterministic in-memory store where every read path treats expired keys as missing.

35m3 sample tests7 hidden tests

Implement an in-memory Store with set, get, delete, and scan. A makes a value disappear at an exact injected-clock boundary.

Requirements

  • Store(now) receives a zero-argument clock function.
  • set(key, value, ttl=None) stores a value. ttl is measured in seconds.
  • Overwriting a key replaces both its value and expiry; ttl=None clears any prior expiry.
  • get(key) returns the value or None when missing or expired.
  • delete(key) removes a key and returns True if it existed and was not expired.
  • scan(prefix) returns sorted (key, value) pairs for non-expired keys whose key starts with prefix.
  • Expiry is inclusive: a key is expired when now() >= expires_at.

Example

A value written at time 0 with ttl=10 stays visible at 9.999 and expires at exactly 10. Overwriting it without a TTL clears the old deadline instead of letting the stale expiration delete the replacement.

The following assertions test that inclusive expiry boundary:

python
1clock = {"t": 0} 2store = Store(lambda: clock["t"]) 3store.set("user:1", "Ada", ttl=10) 4assert store.get("user:1") == "Ada" 5clock["t"] = 10 6assert store.get("user:1") is None

Constraints

  • Don't use sleep in tests or implementation.
  • Use standard-library Python only.
  • Apply the same expiry rule on reads, deletes, and prefix scans.

Editor