Simulate a Read-Through TTL Cache

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Build a deterministic in-memory simulator for a key-value cache that supports per-entry time-to-live (TTL) expiration and a read-through loader adapter:

def execute_ttl_cache(operations: List[List[object]]) -> List[List[object]]:

You are given operations, a chronological list of commands starting from an empty cache. Every command is a list whose first two elements are the command name (str) and the current timestamp time_ms (int):

  • ["put", time_ms, key, value, ttl_ms] — Write integer value under string key with lifespan ttl_ms, overwriting any existing record (and its expiration metadata) for key. Return ["ok"].
  • ["get", time_ms, key] — If key holds an unexpired entry at time_ms, return ["ok", value]; otherwise return ["ok", None] (["ok", null] in JSON) without removing any stored record.
  • ["delete", time_ms, key] — Remove key from storage if present. Return ["ok", True] whenever key was physically stored (including if it had already expired), or ["ok", False] if key was absent.
  • ["size", time_ms] — Return ["ok", count], where count is the total number of keys currently held in storage, including expired entries that have not yet been deleted.
  • ["fetch", time_ms, key, ttl_ms, loader_status, loader_payload] — Perform a read-through lookup whose external loader result is pre-supplied for determinism:
    • Cache hit: If key currently holds an unexpired value at time_ms, return ["ok", cached_value] immediately while keeping its existing value and expiration unchanged (ignoring the loader outcome).
    • Cache miss or expired key: Apply the supplied loader result:
      • When loader_status == "ok", loader_payload is an integer; store loader_payload under key with lifespan ttl_ms starting at time_ms (replacing any stale record for key) and return ["ok", loader_payload].
      • When loader_status == "error", loader_payload is an error string; leave cache storage completely untouched (preserving any stale record for key) and return ["error", loader_payload].

Expiration & Storage Rules

  • When an entry is written at timestamp t with ttl_ms > 0, it remains valid while time_ms < t + ttl_ms and becomes expired at the exact timestamp t + ttl_ms (so time_ms >= t + ttl_ms is invalid).
  • When ttl_ms == 0, the entry never expires.
  • Expired records are not evicted automatically; they stay in storage until removed by "delete" or overwritten by "put" or a "fetch" miss with loader_status == "ok".

Examples

Example 1

Input:
operations = [
    ["put", 10, "token", 42, 15],
    ["get", 24, "token"],
    ["get", 25, "token"],
    ["size", 25],
    ["fetch", 30, "token", 20, "ok", 99],
    ["fetch", 35, "profile", 10, "error", "timeout"],
    ["size", 35],
    ["delete", 40, "token"],
    ["size", 40]
]

Output:
[
    ["ok"],
    ["ok", 42],
    ["ok", None],
    ["ok", 1],
    ["ok", 99],
    ["error", "timeout"],
    ["ok", 1],
    ["ok", True],
    ["ok", 0]
]

Walk-through: 1. "token" is stored at t = 10 with ttl_ms = 15, so it expires at 10 + 15 = 25. 2. At t = 24, "token" is still valid (42); at t = 25, it has just expired (None), yet "size" at t = 25 still counts 1 stored record. 3. At t = 30, "fetch" sees that "token" is expired, applies the "ok" loader result to store 99 (new expiry 30 + 20 = 50), and returns ["ok", 99]. 4. At t = 35, "fetch" misses on "profile" and receives "error", leaving the cache unchanged ("size" stays 1) and returning ["error", "timeout"]. 5. Deleting "token" at t = 40 removes the record (True) and drops "size" to 0.

Example 2

Input:
operations = [
    ["put", 0, "cfg", 0, 0],
    ["put", 5, "otp", 777, 5],
    ["fetch", 8, "otp", 100, "error", "unreachable"],
    ["get", 10, "otp"],
    ["delete", 12, "otp"],
    ["delete", 12, "otp"],
    ["get", 500, "cfg"]
]

Output:
[
    ["ok"],
    ["ok"],
    ["ok", 777],
    ["ok", None],
    ["ok", True],
    ["ok", False],
    ["ok", 0]
]

Walk-through: 1. "cfg" is written with value 0 and ttl_ms = 0 (never expires). "otp" is written at t = 5 with ttl_ms = 5 (expires at t = 10). 2. At t = 8, "otp" is still valid, so "fetch" returns ["ok", 777] without failing on "error" and without extending "otp"'s expiry past 10. 3. At t = 10, "otp" is expired (None). At t = 12, the first "delete" removes the expired record (True) and the second "delete" finds nothing (False). 4. At t = 500, "cfg" still returns its cached integer 0.

Constraints

  • 0 <= len(operations) <= 200,000
  • time_ms and ttl_ms are non-negative integers (>= 0), and time_ms values are non-decreasing across operations.
  • key is a str, cached values are int (booleans such as True / False are not valid integers), loader_status is "ok" or "error", and loader_payload is an int when loader_status == "ok" or a str when loader_status == "error".
  • Raise ValueError if operations or any command is malformed, has the wrong argument count, uses an unrecognized command name, contains invalid field types, or has a timestamp smaller than the previous command's timestamp.

Step-by-step walkthrough

  1. Understand the cache rules: stored vs. currently valid

    A TTL (Time-To-Live) is a lifespan in milliseconds attached to a cached key-value entry. When an entry is written at put_time with ttl_ms > 0, it expires at expires_at = put_time + ttl_ms—meaning it is valid while now < expires_at, and already invalid at the exact moment now == expires_at. When ttl_ms == 0, the entry never expires.

    The most important rule in this problem is separating whether a record is stored from whether that record is currently valid:

    • Expired records are NOT auto-deleted. Once expired, a record stays in storage until a delete removes it or a put / successful fetch overwrites it.
    • get and fetch care about validity: an expired record behaves like a cache miss.
    • size and delete care about physical storage: size counts expired records too, and delete returns True when removing an expired record.
    Timeline for ["put", 10, "token", 42, 15]  (expires_at = 10 + 15 = 25):
    
      time:  10    15    20    24  | 25    30    35
              |<-- valid (< 25) -->|<- expired (now >= 25), but STILL STORED! ->
      get:   42    42    42    42  | None  None  None
      size:   1     1     1     1  |  1     1     1   (until deleted or replaced)
    
  2. Choose the data structure: hash map with absolute expiry times

    With up to 200,000 operations, storing entries in a plain list and scanning for a key on each command would take O(N^2) time (up to 4 * 10^10 checks). Instead, we store records in a hash map (dict in Python) for O(1) average-time lookups, updates, and deletions:

    self.records: Dict[str, Tuple[int, Optional[int]]]
      "token" -> (42, 25)    # value = 42, expires_at = 25
      "cfg"   -> (0, None)   # value = 0,  expires_at = None (ttl_ms == 0, never expires)
    

    Why store expires_at instead of (put_time, ttl_ms)? Computing now + ttl_ms once during put turns every future validity check into a single comparison (expires_at is not None and now >= expires_at), and overwriting self.records[key] = (value, expires_at) cleanly replaces both the value and its expiration metadata in one assignment.

  3. Validate every operation strictly before executing it

    Malformed inputs, unknown operation names, wrong types, or decreasing timestamps must raise ValueError. Validating each operation up front keeps the cache methods clean and avoids three classic Python traps:

    1. bool is a subclass of int in Python! isinstance(True, int) evaluates to True, even though JSON true is a boolean, not an integer. Our helper _is_strict_int(value) explicitly excludes bool.
    2. Check container type and length before indexing. Verify isinstance(op, list) and len(op) > 0 first, then verify isinstance(op[0], str) (so an unhashable element like [[]] raises ValueError instead of TypeError) and check len(op) == EXPECTED_LENGTHS[op_name] before reading op[1], op[2], etc.
    3. Allow equal timestamps, forbid decreasing ones. Track prev_time: Optional[int] = None and raise ValueError only when prev_time is not None and time_ms < prev_time.
    EXPECTED_LENGTHS: Dict[str, int] = {
        "put": 5,
        "get": 3,
        "delete": 3,
        "size": 2,
        "fetch": 6,
    }
    
    
    def _is_strict_int(value: object) -> bool:
        """Return True for integers, excluding booleans (bool subclasses int in Python)."""
        return isinstance(value, int) and not isinstance(value, bool)
    
    
    def _validate_ttl(ttl_ms: object) -> None:
        """Ensure ttl_ms is a non-negative integer (0 means never expires)."""
        if not _is_strict_int(ttl_ms) or ttl_ms < 0:
            raise ValueError(f"ttl_ms must be a non-negative integer, got {ttl_ms!r}")
    
    
    def _validate_operation(op: object, prev_time: Optional[int]) -> None:
        """Validate structure, types, and monotonic timestamp of a single operation."""
        # Step 1: Check outer container and operation name before indexing positional fields.
        if not isinstance(op, list) or len(op) == 0:
            raise ValueError(f"operation must be a non-empty list, got {op!r}")
    
        op_name = op[0]
        if not isinstance(op_name, str) or op_name not in EXPECTED_LENGTHS:
            raise ValueError(f"unknown operation name: {op_name!r}")
    
        expected_len = EXPECTED_LENGTHS[op_name]
        if len(op) != expected_len:
            raise ValueError(f"{op_name!r} expects {expected_len} elements, got {len(op)}")
    
        # Step 2: Validate timestamp (non-negative int, non-decreasing across operations).
        time_ms = op[1]
        if not _is_strict_int(time_ms) or time_ms < 0:
            raise ValueError(f"time_ms must be a non-negative integer, got {time_ms!r}")
        if prev_time is not None and time_ms < prev_time:
            raise ValueError(f"timestamps must be non-decreasing: {time_ms} < {prev_time}")
    
        # Step 3: Validate operation-specific arguments.
        if op_name != "size":
            key = op[2]
            if not isinstance(key, str):
                raise ValueError(f"key must be a string, got {key!r}")
    
        if op_name == "put":
            value = op[3]
            ttl_ms = op[4]
            if not _is_strict_int(value):
                raise ValueError(f"cached value must be an integer, got {value!r}")
            _validate_ttl(ttl_ms)
        elif op_name == "fetch":
            ttl_ms = op[3]
            loader_status = op[4]
            loader_payload = op[5]
            _validate_ttl(ttl_ms)
            if loader_status == "ok":
                if not _is_strict_int(loader_payload):
                    raise ValueError(f"loader_payload for 'ok' must be an int, got {loader_payload!r}")
            elif loader_status == "error":
                if not isinstance(loader_payload, str):
                    raise ValueError(f"loader_payload for 'error' must be a str, got {loader_payload!r}")
            else:
                raise ValueError(f"loader_status must be 'ok' or 'error', got {loader_status!r}")
    
  4. Build `TTLCache` with two-phase `fetch`

    Inside TTLCache, _get_valid_value(key, now) centralizes the expiration check: it returns the integer value when key exists and is unexpired, or None when missing or expired—without deleting expired entries from self.records.

    That makes fetch a clean two-phase operation:

    • Phase 1 (check phase): Call cached_value = self._get_valid_value(key, now). Be careful to check if cached_value is not None: rather than if cached_value:, because 0 is a valid cached integer! On a hit, return ["ok", cached_value] immediately without touching the TTL or acting on loader_status.
    • Phase 2 (loader phase, only on missing or expired key):
      • If loader_status == "ok", call self.put(now, key, loader_payload, ttl_ms) to write (or overwrite) the key with its new TTL, then return ["ok", loader_payload].
      • If loader_status == "error", leave self.records completely unchanged (any expired record stays stored!) and return ["error", loader_payload].
    class TTLCache:
        def __init__(self) -> None:
            # self.records: dict mapping key (str) -> (value: int, expires_at: Optional[int])
            # expires_at is None when ttl_ms == 0 (no expiration).
            # Expired entries remain stored here until explicitly deleted or overwritten!
            self.records: Dict[str, Tuple[int, Optional[int]]] = {}
    
        def _get_valid_value(self, key: str, now: int) -> Optional[int]:
            """Return the cached int if key exists and is unexpired at `now`, else None."""
            record = self.records.get(key)
            if record is None:
                return None
    
            value, expires_at = record
            # Boundary rule: a positive TTL expires at put_time + ttl_ms, so `now >= expires_at`
            # is already invalid. We do NOT delete the expired record from self.records.
            if expires_at is not None and now >= expires_at:
                return None
            return value
    
        def put(self, now: int, key: str, value: int, ttl_ms: int) -> None:
            # Compute absolute expiration timestamp once at write time (None if ttl_ms == 0).
            expires_at: Optional[int] = None
            if ttl_ms > 0:
                expires_at = now + ttl_ms
            # Overwriting replaces both the stored value and its expiration metadata.
            self.records[key] = (value, expires_at)
    
        def get(self, now: int, key: str) -> Optional[int]:
            return self._get_valid_value(key, now)
    
        def delete(self, key: str) -> bool:
            # Delete checks physical presence in self.records, returning True even if expired.
            if key in self.records:
                del self.records[key]
                return True
            return False
    
        def size(self) -> int:
            # Size counts all stored records, including expired ones that were not deleted yet.
            return len(self.records)
    
        def fetch(
            self,
            now: int,
            key: str,
            ttl_ms: int,
            loader_status: str,
            loader_payload: Any,
        ) -> List[object]:
            # Phase 1 (check phase): use `is not None` so cached 0 is treated as a valid hit!
            # On a hit, ignore loader fields completely and keep the existing expiration time.
            cached_value = self._get_valid_value(key, now)
            if cached_value is not None:
                return ["ok", cached_value]
    
            # Phase 2 (loader phase on missing or expired key):
            if loader_status == "ok":
                self.put(now, key, loader_payload, ttl_ms)
                return ["ok", loader_payload]
    
            # On loader "error", leave self.records untouched (preserving any expired record).
            return ["error", loader_payload]
    
  5. Replay the operation log and trace the sample

    Now execute_ttl_cache simply checks that operations is a list, loops over each operation, validates it against prev_time, dispatches to TTLCache, and formats the exact response list (None, True, False in Python correspond to JSON null, true, false).

    def execute_ttl_cache(operations: List[List[object]]) -> List[List[object]]:
        if not isinstance(operations, list):
            raise ValueError("operations must be a list")
    
        cache = TTLCache()
        results: List[List[object]] = []
        prev_time: Optional[int] = None
    
        # Validate and execute each operation in chronological order.
        for op in operations:
            _validate_operation(op, prev_time)
            op_name = op[0]
            now = op[1]
            prev_time = now
    
            if op_name == "put":
                cache.put(now, op[2], op[3], op[4])
                results.append(["ok"])
            elif op_name == "get":
                results.append(["ok", cache.get(now, op[2])])
            elif op_name == "delete":
                results.append(["ok", cache.delete(op[2])])
            elif op_name == "size":
                results.append(["ok", cache.size()])
            else:
                results.append(cache.fetch(now, op[2], op[3], op[4], op[5]))
    
        return results
    

    Let's trace every line of Example 1 to see self.records evolve:

    Operation                                           | self.records after            | Returned result
    ----------------------------------------------------+-------------------------------+---------------------
    ["put", 10, "token", 42, 15]                        | {"token": (42, 25)}           | ["ok"]
    ["get", 24, "token"]        (24 < 25 -> valid)      | {"token": (42, 25)}           | ["ok", 42]
    ["get", 25, "token"]        (25 >= 25 -> expired)   | {"token": (42, 25)}  (kept!)  | ["ok", None]
    ["size", 25]                (counts expired)        | {"token": (42, 25)}           | ["ok", 1]
    ["fetch", 30, "token", 20, "ok", 99]  (miss -> ok)  | {"token": (99, 50)} (30+20)   | ["ok", 99]
    ["fetch", 35, "profile", 10, "error", "timeout"]    | {"token": (99, 50)} (unchg.)  | ["error", "timeout"]
    ["size", 35]                                        | {"token": (99, 50)}           | ["ok", 1]
    ["delete", 40, "token"]                             | {}                            | ["ok", True]
    ["size", 40]                                        | {}                            | ["ok", 0]
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # EXPECTED_LENGTHS: maps each valid operation name to its exact list length (including op[0]).
    EXPECTED_LENGTHS: Dict[str, int] = {
        "put": 5,
        "get": 3,
        "delete": 3,
        "size": 2,
        "fetch": 6,
    }
    
    
    def _is_strict_int(value: object) -> bool:
        """Return True for integers, excluding booleans (bool subclasses int in Python)."""
        return isinstance(value, int) and not isinstance(value, bool)
    
    
    def _validate_ttl(ttl_ms: object) -> None:
        """Ensure ttl_ms is a non-negative integer (0 means never expires)."""
        if not _is_strict_int(ttl_ms) or ttl_ms < 0:
            raise ValueError(f"ttl_ms must be a non-negative integer, got {ttl_ms!r}")
    
    
    def _validate_operation(op: object, prev_time: Optional[int]) -> None:
        """Validate structure, types, and monotonic timestamp of a single operation."""
        # Step 1: Check outer container and operation name before indexing positional fields.
        if not isinstance(op, list) or len(op) == 0:
            raise ValueError(f"operation must be a non-empty list, got {op!r}")
    
        op_name = op[0]
        if not isinstance(op_name, str) or op_name not in EXPECTED_LENGTHS:
            raise ValueError(f"unknown operation name: {op_name!r}")
    
        expected_len = EXPECTED_LENGTHS[op_name]
        if len(op) != expected_len:
            raise ValueError(f"{op_name!r} expects {expected_len} elements, got {len(op)}")
    
        # Step 2: Validate timestamp (non-negative int, non-decreasing across operations).
        time_ms = op[1]
        if not _is_strict_int(time_ms) or time_ms < 0:
            raise ValueError(f"time_ms must be a non-negative integer, got {time_ms!r}")
        if prev_time is not None and time_ms < prev_time:
            raise ValueError(f"timestamps must be non-decreasing: {time_ms} < {prev_time}")
    
        # Step 3: Validate operation-specific arguments.
        if op_name != "size":
            key = op[2]
            if not isinstance(key, str):
                raise ValueError(f"key must be a string, got {key!r}")
    
        if op_name == "put":
            value = op[3]
            ttl_ms = op[4]
            if not _is_strict_int(value):
                raise ValueError(f"cached value must be an integer, got {value!r}")
            _validate_ttl(ttl_ms)
        elif op_name == "fetch":
            ttl_ms = op[3]
            loader_status = op[4]
            loader_payload = op[5]
            _validate_ttl(ttl_ms)
            if loader_status == "ok":
                if not _is_strict_int(loader_payload):
                    raise ValueError(f"loader_payload for 'ok' must be an int, got {loader_payload!r}")
            elif loader_status == "error":
                if not isinstance(loader_payload, str):
                    raise ValueError(f"loader_payload for 'error' must be a str, got {loader_payload!r}")
            else:
                raise ValueError(f"loader_status must be 'ok' or 'error', got {loader_status!r}")
    
    
    class TTLCache:
        def __init__(self) -> None:
            # self.records: dict mapping key (str) -> (value: int, expires_at: Optional[int])
            # expires_at is None when ttl_ms == 0 (no expiration).
            # Expired entries remain stored here until explicitly deleted or overwritten!
            self.records: Dict[str, Tuple[int, Optional[int]]] = {}
    
        def _get_valid_value(self, key: str, now: int) -> Optional[int]:
            """Return the cached int if key exists and is unexpired at `now`, else None."""
            record = self.records.get(key)
            if record is None:
                return None
    
            value, expires_at = record
            # Boundary rule: a positive TTL expires at put_time + ttl_ms, so `now >= expires_at`
            # is already invalid. We do NOT delete the expired record from self.records.
            if expires_at is not None and now >= expires_at:
                return None
            return value
    
        def put(self, now: int, key: str, value: int, ttl_ms: int) -> None:
            # Compute absolute expiration timestamp once at write time (None if ttl_ms == 0).
            expires_at: Optional[int] = None
            if ttl_ms > 0:
                expires_at = now + ttl_ms
            # Overwriting replaces both the stored value and its expiration metadata.
            self.records[key] = (value, expires_at)
    
        def get(self, now: int, key: str) -> Optional[int]:
            return self._get_valid_value(key, now)
    
        def delete(self, key: str) -> bool:
            # Delete checks physical presence in self.records, returning True even if expired.
            if key in self.records:
                del self.records[key]
                return True
            return False
    
        def size(self) -> int:
            # Size counts all stored records, including expired ones that were not deleted yet.
            return len(self.records)
    
        def fetch(
            self,
            now: int,
            key: str,
            ttl_ms: int,
            loader_status: str,
            loader_payload: Any,
        ) -> List[object]:
            # Phase 1 (check phase): use `is not None` so cached 0 is treated as a valid hit!
            # On a hit, ignore loader fields completely and keep the existing expiration time.
            cached_value = self._get_valid_value(key, now)
            if cached_value is not None:
                return ["ok", cached_value]
    
            # Phase 2 (loader phase on missing or expired key):
            if loader_status == "ok":
                self.put(now, key, loader_payload, ttl_ms)
                return ["ok", loader_payload]
    
            # On loader "error", leave self.records untouched (preserving any expired record).
            return ["error", loader_payload]
    
    
    def execute_ttl_cache(operations: List[List[object]]) -> List[List[object]]:
        if not isinstance(operations, list):
            raise ValueError("operations must be a list")
    
        cache = TTLCache()
        results: List[List[object]] = []
        prev_time: Optional[int] = None
    
        # Validate and execute each operation in chronological order.
        for op in operations:
            _validate_operation(op, prev_time)
            op_name = op[0]
            now = op[1]
            prev_time = now
    
            if op_name == "put":
                cache.put(now, op[2], op[3], op[4])
                results.append(["ok"])
            elif op_name == "get":
                results.append(["ok", cache.get(now, op[2])])
            elif op_name == "delete":
                results.append(["ok", cache.delete(op[2])])
            elif op_name == "size":
                results.append(["ok", cache.size()])
            else:
                results.append(cache.fetch(now, op[2], op[3], op[4], op[5]))
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture an office refrigerator where every labeled container gets a "use-by" timestamp sticker — its TTL (Time-To-Live), the lifespan in milliseconds before a cached entry goes stale (or "no expiration" when ttl_ms == 0). Nobody cleans out expired containers automatically: they sit on the shelf taking up slots (size still counts them, and delete throws one out and reports True) until someone explicitly deletes that label or replaces it with fresh food. Whenever someone tries to read a label (get or fetch), we use passive validity checking — comparing the current timestamp now against the stored expires_at sticker on read without deleting expired records — and for fetch, we only consult the backup kitchen (loader_status and loader_payload) when the label is missing or expired.

Why do naive implementations fail? If you eagerly delete expired entries inside get, then a later size or delete reports the wrong count or False, violating the specification that expired entries stay stored until deleted or replaced. If you store records in a list and scan linearly on every command, 200,000 operations degrade to O(N^2) time (billions of steps) instead of O(1) average time per command with a hash map (dict in Python, a key-value table with constant-time average lookup). And in Python specifically, careless checks like isinstance(x, int) or if cached_value: fail silently because True is a subclass of int and 0 is a valid cached value!

Let's walk through the first 5 operations of Example 1 to see how stored records and validity checks interact:

1. ["put", 10, "token", 42, 15]          -> store "token": (val=42, expires_at=25), return ["ok"]
2. ["get", 24, "token"]                  -> 24 < 25 (valid!), return ["ok", 42]
3. ["get", 25, "token"]                  -> 25 >= 25 (expired!), keep "token" stored, return ["ok", None]
4. ["size", 25]                          -> "token" is still in self.records, return ["ok", 1]
5. ["fetch", 30, "token", 20, "ok", 99]  -> "token" is expired (miss) -> loader "ok" overwrites
                                            "token": (val=99, expires_at=50), return ["ok", 99]

Complexity

Let N be the number of operations (len(operations)) and K be the number of distinct keys stored in the cache (K <= N).

  • Time: O(N) assuming bounded key string lengths. We iterate through the N operations once; for each operation, _validate_operation checks at most 6 fields in O(1) time, and TTLCache performs at most two O(1) average-time dictionary lookups, insertions, or deletions (plus O(len(key)) to hash the key string).
  • Space: O(N + K), which is O(N) overall. self.records holds at most K <= N key-to-tuple entries (including expired entries not yet deleted), and results stores N small response lists.

Edge cases

  • Exact expiration boundary (now == put_time + ttl_ms): An entry written at t = 10 with ttl_ms = 3 is valid at t = 12 (12 < 13) and already invalid at t = 13 (13 >= 13).
  • ttl_ms == 0 (no expiration): Stored with expires_at = None, so both put and a successful fetch keep the entry valid at arbitrarily large timestamps.
  • Cached 0 or negative integers: 0 and -4 are valid integer hits; checking cached_value is not None prevents 0 from being mistaken for a cache miss.
  • fetch on a valid cached key: Returns ["ok", cached_value] even if loader_status == "error", and does not extend or overwrite the existing expires_at.
  • fetch "error" on an expired key: Leaves the expired entry untouched in self.records, so size still includes it and a subsequent delete still returns True.
  • Overwriting an existing key: A new put (even with a shorter TTL or ttl_ms = 0) completely replaces both the old value and the old expires_at.
  • Equal consecutive timestamps: Non-decreasing order permits time_ms == prev_time; only time_ms < prev_time raises ValueError.
  • Malformed inputs: Non-list operations, empty operation [], unhashable operation names like [[1], 0], wrong argument counts, floats, booleans (True / False) passed where integers are required, negative time_ms or ttl_ms, or mismatched loader_status/loader_payload types all raise ValueError.

Common mistakes

  • Using > instead of >= on expiration: Writing now > expires_at keeps an entry alive for one extra millisecond at now == put_time + ttl_ms.
  • Deleting expired entries inside get or fetch "error": That breaks size and delete, which must continue seeing expired records until explicit deletion or replacement.
  • Truthiness check (if cached_value:): Treats a cached 0 as falsy, triggering a bogus cache miss and overwriting 0 with the loader outcome.
  • Refreshing TTL on a fetch hit: A cache hit does not call the loader, so neither the value nor expires_at should change.
  • Accepting bool as int: Because isinstance(True, int) is True in Python, omitting and not isinstance(value, bool) lets ["size", True] or ["put", 0, "a", True, 5] slip past validation.
  • Letting IndexError or TypeError escape on bad inputs: Indexing op[1] before checking len(op) or checking op[0] in EXPECTED_LENGTHS when op[0] is a list raises the wrong exception type instead of ValueError.

Alternative approaches

  • Store (value, put_time, ttl_ms) instead of (value, expires_at): Functionally identical, checking ttl_ms > 0 and now - put_time >= ttl_ms on every read. Precomputing expires_at once on write is slightly cleaner because None directly represents "never expires."
  • Lazy validation of fetch loader arguments: Deferring type checks on loader_status and loader_payload until fetch misses would accept malformed loader payloads on cache hits, whereas upfront validation guarantees that malformed commands always raise ValueError regardless of prior cache contents.

Follow-up questions

  • How would you bound memory usage in production if expired keys are never explicitly deleted? You can add active background eviction using a min-heap — a tree-based priority queue whose smallest element can be inspected in O(1) time and popped in O(log N) time — storing (expires_at, key) pairs on each write and popping entries with expires_at <= now before running operations (ignoring stale heap entries if the key was overwritten with a newer expiry). Alternatively, Redis-style periodic random sampling wakes up every 100 ms, checks 20 random keys with TTLs, and deletes expired ones in O(1) space overhead. Note that active cleanup changes size and delete semantics, since expired keys disappear automatically.
  • How could you add a fixed capacity limit with LRU eviction while keeping every operation O(1)? LRU (Least Recently Used) eviction is a policy that discards the entry that has gone untouched for the longest time whenever the cache is full. Store the records in Python's collections.OrderedDict (or a hash map paired with a doubly linked list, a chain of nodes with prev/next pointers supporting O(1) removal and insertion), call move_to_end(key) on every valid get, fetch hit, and put, and pop the oldest entry from the front whenever inserting a new key would exceed capacity (preferring to evict expired entries first if tracked).
  • How would you prevent a cache stampede when many concurrent callers fetch the same expired hot key? Every thread sees a miss at the same instant and hammers the database simultaneously — a failure mode called a cache stampede (or thundering herd). Fix it with single-flight (request coalescing) — tracking an in_flight[key] future/promise so only the first thread calls the database loader while all other callers for key await that single result. If the loader fails, you can also use short negative caching — caching the error state for 1–2 seconds — so a struggling database is not overwhelmed by immediate retries.

Follow-up questions

Similar questions

More Tubi interview questions

All 11 Tubi questions →