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 integervalueunder stringkeywith lifespanttl_ms, overwriting any existing record (and its expiration metadata) forkey. Return["ok"].["get", time_ms, key]— Ifkeyholds an unexpired entry attime_ms, return["ok", value]; otherwise return["ok", None](["ok", null]in JSON) without removing any stored record.["delete", time_ms, key]— Removekeyfrom storage if present. Return["ok", True]wheneverkeywas physically stored (including if it had already expired), or["ok", False]ifkeywas absent.["size", time_ms]— Return["ok", count], wherecountis 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
keycurrently holds an unexpired value attime_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_payloadis an integer; storeloader_payloadunderkeywith lifespanttl_msstarting attime_ms(replacing any stale record forkey) and return["ok", loader_payload]. - When
loader_status == "error",loader_payloadis an error string; leave cache storage completely untouched (preserving any stale record forkey) and return["error", loader_payload].
- When
- Cache hit: If
Expiration & Storage Rules
- When an entry is written at timestamp
twithttl_ms > 0, it remains valid whiletime_ms < t + ttl_msand becomes expired at the exact timestampt + ttl_ms(sotime_ms >= t + ttl_msis 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 withloader_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,000time_msandttl_msare non-negative integers (>= 0), andtime_msvalues are non-decreasing acrossoperations.keyis astr, cached values areint(booleans such asTrue/Falseare not valid integers),loader_statusis"ok"or"error", andloader_payloadis anintwhenloader_status == "ok"or astrwhenloader_status == "error".- Raise
ValueErrorifoperationsor 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
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_timewithttl_ms > 0, it expires atexpires_at = put_time + ttl_ms—meaning it is valid whilenow < expires_at, and already invalid at the exact momentnow == expires_at. Whenttl_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
deleteremoves it or aput/ successfulfetchoverwrites it. getandfetchcare about validity: an expired record behaves like a cache miss.sizeanddeletecare about physical storage:sizecounts expired records too, anddeletereturnsTruewhen 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)- Expired records are NOT auto-deleted. Once expired, a record stays in storage until a
Choose the data structure: hash map with absolute expiry times
With up to
200,000operations, storing entries in a plain list and scanning for a key on each command would takeO(N^2)time (up to4 * 10^10checks). Instead, we store records in a hash map (dictin Python) forO(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_atinstead of(put_time, ttl_ms)? Computingnow + ttl_msonce duringputturns every future validity check into a single comparison (expires_at is not None and now >= expires_at), and overwritingself.records[key] = (value, expires_at)cleanly replaces both the value and its expiration metadata in one assignment.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:boolis a subclass ofintin Python!isinstance(True, int)evaluates toTrue, even though JSONtrueis a boolean, not an integer. Our helper_is_strict_int(value)explicitly excludesbool.- Check container type and length before indexing. Verify
isinstance(op, list)andlen(op) > 0first, then verifyisinstance(op[0], str)(so an unhashable element like[[]]raisesValueErrorinstead ofTypeError) and checklen(op) == EXPECTED_LENGTHS[op_name]before readingop[1],op[2], etc. - Allow equal timestamps, forbid decreasing ones. Track
prev_time: Optional[int] = Noneand raiseValueErroronly whenprev_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}")Build `TTLCache` with two-phase `fetch`
Inside
TTLCache,_get_valid_value(key, now)centralizes the expiration check: it returns the integer value whenkeyexists and is unexpired, orNonewhen missing or expired—without deleting expired entries fromself.records.That makes
fetcha clean two-phase operation:- Phase 1 (check phase): Call
cached_value = self._get_valid_value(key, now). Be careful to checkif cached_value is not None:rather thanif cached_value:, because0is a valid cached integer! On a hit, return["ok", cached_value]immediately without touching the TTL or acting onloader_status. - Phase 2 (loader phase, only on missing or expired key):
- If
loader_status == "ok", callself.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", leaveself.recordscompletely unchanged (any expired record stays stored!) and return["error", loader_payload].
- If
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]- Phase 1 (check phase): Call
Replay the operation log and trace the sample
Now
execute_ttl_cachesimply checks thatoperationsis alist, loops over each operation, validates it againstprev_time, dispatches toTTLCache, and formats the exact response list (None,True,Falsein Python correspond to JSONnull,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 resultsLet's trace every line of Example 1 to see
self.recordsevolve: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]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 theNoperations once; for each operation,_validate_operationchecks at most 6 fields inO(1)time, andTTLCacheperforms at most twoO(1)average-time dictionary lookups, insertions, or deletions (plusO(len(key))to hash the key string). - Space:
O(N + K), which isO(N)overall.self.recordsholds at mostK <= Nkey-to-tuple entries (including expired entries not yet deleted), andresultsstoresNsmall response lists.
Edge cases
- Exact expiration boundary (
now == put_time + ttl_ms): An entry written att = 10withttl_ms = 3is valid att = 12(12 < 13) and already invalid att = 13(13 >= 13). ttl_ms == 0(no expiration): Stored withexpires_at = None, so bothputand a successfulfetchkeep the entry valid at arbitrarily large timestamps.- Cached
0or negative integers:0and-4are valid integer hits; checkingcached_value is not Noneprevents0from being mistaken for a cache miss. fetchon a valid cached key: Returns["ok", cached_value]even ifloader_status == "error", and does not extend or overwrite the existingexpires_at.fetch"error"on an expired key: Leaves the expired entry untouched inself.records, sosizestill includes it and a subsequentdeletestill returnsTrue.- Overwriting an existing key: A new
put(even with a shorter TTL orttl_ms = 0) completely replaces both the old value and the oldexpires_at. - Equal consecutive timestamps: Non-decreasing order permits
time_ms == prev_time; onlytime_ms < prev_timeraisesValueError. - 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, negativetime_msorttl_ms, or mismatchedloader_status/loader_payloadtypes all raiseValueError.
Common mistakes
- Using
>instead of>=on expiration: Writingnow > expires_atkeeps an entry alive for one extra millisecond atnow == put_time + ttl_ms. - Deleting expired entries inside
getorfetch"error": That breakssizeanddelete, which must continue seeing expired records until explicit deletion or replacement. - Truthiness check (
if cached_value:): Treats a cached0as falsy, triggering a bogus cache miss and overwriting0with the loader outcome. - Refreshing TTL on a
fetchhit: A cache hit does not call the loader, so neither the value norexpires_atshould change. - Accepting
boolasint: Becauseisinstance(True, int)isTruein Python, omittingand not isinstance(value, bool)lets["size", True]or["put", 0, "a", True, 5]slip past validation. - Letting
IndexErrororTypeErrorescape on bad inputs: Indexingop[1]before checkinglen(op)or checkingop[0] in EXPECTED_LENGTHSwhenop[0]is alistraises the wrong exception type instead ofValueError.
Alternative approaches
- Store
(value, put_time, ttl_ms)instead of(value, expires_at): Functionally identical, checkingttl_ms > 0 and now - put_time >= ttl_mson every read. Precomputingexpires_atonce on write is slightly cleaner becauseNonedirectly represents "never expires." - Lazy validation of
fetchloader arguments: Deferring type checks onloader_statusandloader_payloaduntilfetchmisses would accept malformed loader payloads on cache hits, whereas upfront validation guarantees that malformed commands always raiseValueErrorregardless 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 inO(log N)time — storing(expires_at, key)pairs on each write and popping entries withexpires_at <= nowbefore 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 inO(1)space overhead. Note that active cleanup changessizeanddeletesemantics, 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 supportingO(1)removal and insertion), callmove_to_end(key)on every validget,fetchhit, andput, 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 forkeyawait 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
- How would you bound memory usage in production if expired keys are never explicitly deleted?
- How could you add a fixed capacity limit with LRU eviction while keeping every operation O(1)?
- How would you prevent a cache stampede when many concurrent callers fetch the same expired hot key?
Similar questions
- From-Scratch K-Means Clustering vs. Gaussian Mixture Models
- Proportional Random Index Sampler
- Daily User Growth and Churn Rollup
- Statistical Sample Size and Power Drivers
- ML Foundations, Production Tuning, and Recommender Systems
- Multi-Metric Experiment Design and Launch Trade-Off Communication
More Tubi interview questions
- Thread-Safe TTL Cache with Single-Flight Loading Medium
- Daily User Growth and Churn Rollup Medium
- Statistical Sample Size and Power Drivers Hard Pro
- ML Foundations, Production Tuning, and Recommender Systems Medium Pro
- Multi-Metric Experiment Design and Launch Trade-Off Communication Hard Pro
- From-Scratch K-Means Clustering vs. Gaussian Mixture Models Medium Pro
- Streaming Movie Recommendation Pipeline and Model (AI-Assisted) Medium Pro
- Designing Artwork Selection for a Video Streaming Library Medium Pro
- Core ML Screen: Decision Trees, Optimization, Metrics, and Attention Medium Pro
- Proportional Random Index Sampler Medium Pro