Versioned In-Memory Key-Value Store with TTL

Hard · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Build an in-memory key-value file store that tracks full per-key version history, supports time-to-live (TTL) expirations, and answers both present-time and historical point-in-time queries.

Implement the entry point:

def process_file_store_operations(operations: List[List[Any]]) -> List[Any]:

Each element of operations is a command list whose first item is the operation name. Execute the commands sequentially against a fresh store and return a list of equal length containing each command's result:

  • ["set", key, value] -> returns None. Stores value under key at the current logical time now with no expiration.
  • ["set_ttl", key, value, timestamp, ttl] -> returns None. Advances the store's logical clock via now = max(now, timestamp) and records a version of key written at timestamp that is live over the half-open interval [timestamp, timestamp + ttl) (active for timestamp <= t < timestamp + ttl, and expired once t >= timestamp + ttl).
  • ["get", key] -> returns str. Returns the live value of key at now, or "" if key has no active value (never written, deleted, or expired).
  • ["get", key, timestamp] or ["get_at", key, timestamp] -> returns str. Returns the value of key that was live at timestamp without modifying now, or "" if no version was live at timestamp.
  • ["delete", key] -> returns bool. If key has a live value at now, marks key deleted at now (while keeping earlier versions intact for historical reads) and returns True; otherwise returns False.
  • ["scan"] -> returns List[str]. Lists "key=value" entries for every key currently live at now, sorted in ascending lexicographical order by key.
  • ["scan_prefix", prefix] -> returns List[str]. Lists "key=value" entries for every key currently live at now whose name starts with prefix, sorted in ascending lexicographical order by key.

Clock & Versioning Rules

  1. Monotonic logical clock: now starts at 0. Only set_ttl updates now, setting now = max(now, timestamp). An out-of-order set_ttl with timestamp < now inserts its version into historical order at timestamp without moving now backward, and timestamped reads (get with 3 arguments or get_at) never change now.
  2. Same-timestamp tie-breaking: When two or more writes (set, set_ttl, or delete) target the same key at the exact same timestamp, the command that appears later in operations supersedes earlier ones at that timestamp.
  3. No fallback to overwritten versions: A write at time t_w replaces whatever version held prior to t_w. If a set_ttl write overwrites an older permanent set value and subsequently expires, queries at or after its expiration time must return "" rather than reviving the older value.
  4. Raw-key sort order: scan and scan_prefix sort by the raw key string before formatting "key=value" (for example, "app" comes before "app-canary" even though ASCII '-' precedes '=').

Examples

Example 1

Input:
operations = [
    ["set", "app", "v1"],
    ["set", "app-canary", "v2"],
    ["scan_prefix", "app"],
    ["set_ttl", "session/u9", "tokA", 10, 6],
    ["get", "session/u9"],
    ["set_ttl", "cfg/region", "us-west", 20, 50],
    ["get", "session/u9"],
    ["get_at", "session/u9", 14],
    ["delete", "app-canary"],
    ["scan"]
]

Output:
[None, None, ["app=v1", "app-canary=v2"], None, "tokA", None, "", "tokA", True, ["app=v1", "cfg/region=us-west"]]

Walk-through: - At now = 0, "app" and "app-canary" are written permanently; scan_prefix("app") orders raw keys so "app=v1" precedes "app-canary=v2". - set_ttl("session/u9", "tokA", 10, 6) advances now to 10 with validity window [10, 16), so get("session/u9") at now = 10 returns "tokA". - set_ttl("cfg/region", "us-west", 20, 50) moves now to 20. At now = 20, "session/u9" has expired (20 >= 16), so get("session/u9") returns "", whereas historical get_at("session/u9", 14) inspects t = 14 inside [10, 16) and still returns "tokA". - delete("app-canary") removes the live key at now = 20 (True), leaving "app=v1" and "cfg/region=us-west" in the final scan().

Example 2

Input:
operations = [
    ["set", "flag", "base"],
    ["set_ttl", "flag", "promo", 8, 4],
    ["get", "flag", 6],
    ["get_at", "flag", 12],
    ["set_ttl", "quota", "100", 8, 20],
    ["set_ttl", "quota", "250", 8, 3],
    ["get", "quota"],
    ["get_at", "quota", 12],
    ["delete", "missing"]
]

Output:
[None, None, "base", "", None, None, "250", "", False]

Walk-through: - "flag" holds "base" starting at t = 0 and is overwritten at t = 8 by "promo" with TTL 4 (live on [8, 12)). Reading at t = 6 returns "base", while reading at t = 12 sees "promo" expired (12 >= 12) and returns "" without resurrecting "base". - Two set_ttl calls write "quota" at t = 8; the second command ("250", live on [8, 11)) wins the tie, returning "250" at now = 8 and "" once expired at t = 12. - Deleting "missing" returns False because no live value exists.

Constraints

  • 0 <= len(operations) <= 10^5
  • key is a non-empty ASCII string; value is a string; prefix is a possibly empty ASCII string.
  • timestamp and ttl are integers (ttl <= 0 means the entry's [timestamp, timestamp + ttl) interval is empty, so it is never live).
  • Point-in-time queries (get_at or 3-argument get) may pass negative, zero, or arbitrarily large integer timestamps.

Step-by-step walkthrough

  1. Pin down the operations and clock rules

    Each command in operations is a list whose first item names the action and appends one entry to the returned results list:

    Operation Return value Behavior
    ["set", key, value] None Writes value at now with no expiration
    ["set_ttl", key, value, timestamp, ttl] None Advances now = max(now, timestamp); live on timestamp <= t < timestamp + ttl
    ["get", key] str Live value at now, or "" if missing, deleted, or expired
    ["get", key, t] or ["get_at", key, t] str Live value as of time t without changing now, or ""
    ["delete", key] bool If live at now, deletes key at now and returns True; else False
    ["scan"] List[str] ["key=value", ...] for all keys live at now, sorted by key
    ["scan_prefix", prefix] List[str] Same as scan, restricted to keys starting with prefix

    Three boundary rules remove all ambiguity:

    • Monotonic clock: now starts at 0 and advances to max(now, timestamp) whenever set_ttl runs. Neither get_at nor an out-of-order set_ttl with a smaller timestamp ever rewinds now.
    • Same-timestamp tie-breaker: If two writes hit the same key at the exact same timestamp, the operation that ran later in the input list wins.
    • No resurrection after expiry: If key "flag" is set permanently at t = 0, overwritten by a temporary set_ttl at t = 8 expiring at t = 12, then at t = 12 key "flag" is empty ("")—the overwritten t = 0 version does not come back to life.
  2. Why a plain dictionary or flat log falls short

    A standard dictionary store[key] = (value, expires_at) handles present-time get, delete, and scan easily, because those only care about the latest write. However, overwriting or deleting a dictionary entry destroys past versions, making ["get_at", "doc", 12] impossible once "doc" is updated or deleted at t = 20.

    At the opposite extreme, appending (timestamp, seq_num, key, value, expires_at) to a single flat list preserves every historical version, but every get must scan the entire list of N operations to find the latest entry for key with timestamp <= t. Over N = 100,000 operations, O(N) per read balloons to O(N^2) (10^10 steps).

  3. Key idea: per-key sorted timelines + binary search

    Because a get asks about one specific key at one specific query_time, group writes by key and keep each key's write timestamps in sorted order across two parallel lists:

    Operations on "flag":
      1. t = 0:  set("flag", "base")            -> permanent
      2. t = 8:  set_ttl("flag", "promo", 8, 4) -> expires at 12
      3. t = 20: delete("flag")                 -> tombstone (value = None)
    
    Stored arrays for "flag":
      index:             0               1                2
      times["flag"]    = [0,             8,               20          ]
      versions["flag"] = [("base", None), ("promo", 12),  (None, None)]
    

    Instead of erasing versions on delete, we append a tombstone—a marker tuple (None, None) recording that the key became empty at that timestamp—so queries for t < 20 still see the earlier history.

    To read "flag" at query_time = 10, we run binary search (bisect_right(times["flag"], 10) - 1), which halves the search range at each step in O(log v) time (v = number of writes to "flag"):

    times["flag"] = [0, 8, 20]
    bisect_right([0, 8, 20], 10) -> insertion index 2 (just right of 8)
    version_idx = 2 - 1 = 1      -> versions["flag"][1] = ("promo", 12)
    Check live at 10: value "promo" is not None, and 10 < 12 -> returns "promo"!
    Check live at 12: version_idx is still 1, but 12 >= 12 -> expired, returns None!
    

    Using bisect_right during _write also gives the same-timestamp tie-breaker for free: inserting at bisect_right(key_times, timestamp) places a newer write to the right of any existing writes with that exact timestamp, and bisect_right(key_times, query_time) - 1 during read always picks the rightmost one.

  4. Implement versioned writes and point-in-time reads

    Let's code the core FileStore state, _write, and read first. Notice that read inspects only versions[key][version_idx]—if that version is a tombstone or has expired (query_time >= expires_at), read returns None immediately without scanning backward to overwritten versions:

    from typing import Any, Dict, List, Optional, Tuple
    from bisect import bisect_right
    
    
    class FileStore:
        """In-memory versioned key-value store supporting TTLs and historical reads."""
    
        def __init__(self) -> None:
            # Logical clock; starts at 0 and advances monotonically to the max set_ttl timestamp seen
            self.now: int = 0
            # Per-key write timestamps in non-decreasing order, e.g. {"doc": [0, 10, 20]}
            self.times: Dict[str, List[int]] = {}
            # Matching per-key (value, expires_at) pairs, e.g. {"doc": [("v1", None), ("v2", 15), (None, None)]}
            # value=None marks a delete tombstone; expires_at=None means the version never expires
            self.versions: Dict[str, List[Tuple[Optional[Any], Optional[int]]]] = {}
    
        def _write(
            self,
            key: str,
            value: Optional[Any],
            timestamp: int,
            expires_at: Optional[int],
        ) -> None:
            if key not in self.times:
                self.times[key] = []
                self.versions[key] = []
    
            key_times = self.times[key]
            # bisect_right inserts AFTER any existing writes with the exact same timestamp,
            # ensuring the later operation wins when two writes share a timestamp.
            insert_idx = bisect_right(key_times, timestamp)
            key_times.insert(insert_idx, timestamp)
            self.versions[key].insert(insert_idx, (value, expires_at))
    
        def read(self, key: str, query_time: int) -> Optional[Any]:
            """Return key's live value at query_time, or None if missing, deleted, or expired."""
            key_times = self.times.get(key)
            if not key_times:
                return None
    
            # Find the rightmost write with timestamp <= query_time
            version_idx = bisect_right(key_times, query_time) - 1
            if version_idx < 0:
                # Every write to this key happened strictly after query_time
                return None
    
            value, expires_at = self.versions[key][version_idx]
            if value is None:
                # Latest version at or before query_time is a delete tombstone
                return None
    
            # TTL window [timestamp, expires_at) is half-open: expired at query_time >= expires_at.
            # Do NOT fall back to older versions once an overwriting version expires.
            if expires_at is not None and query_time >= expires_at:
                return None
    
            return value
    
  5. Layer `set`, `set_ttl`, `delete`, and `scan_prefix` on top

    With _write and read in place, every high-level store method is short and clean. Watch out for a classic string-sorting trap in scan_prefix:

    Suppose live keys are "app" -> "v1" and "app-canary" -> "v2":
      Raw key order:          "app" < "app-canary"            -> ["app=v1", "app-canary=v2"]  (CORRECT)
      Formatted string order: "app-canary=v2" < "app=v1"      -> ["app-canary=v2", "app=v1"]  (WRONG: ASCII '-' is 45, '=' is 61!)
    

    Always sort the raw keys before joining "key=value", and cache the read(key, self.now) lookup in a small dictionary so we don't binary-search each matching key twice:

    class FileStore:  # remaining methods of FileStore
        def set(self, key: str, value: Any) -> None:
            # Permanent write at the current logical clock
            self._write(key, value, self.now, None)
    
        def set_ttl(self, key: str, value: Any, timestamp: int, ttl: int) -> None:
            # Advance the clock forward only; an out-of-order past write never rewinds self.now
            self.now = max(self.now, timestamp)
            self._write(key, value, timestamp, timestamp + ttl)
    
        def delete(self, key: str) -> bool:
            # Only a currently live key can be deleted
            if self.read(key, self.now) is None:
                return False
            # Append a tombstone rather than erasing history so past get_at queries still work
            self._write(key, None, self.now, None)
            return True
    
        def scan_prefix(self, prefix: str) -> List[str]:
            # Collect live values once per matching key at self.now
            live_values: Dict[str, Any] = {}
            for key in self.times:
                if key.startswith(prefix):
                    current_val = self.read(key, self.now)
                    if current_val is not None:
                        live_values[key] = current_val
    
            # Sort raw keys BEFORE formatting "key=value": ASCII '-' (45) < '=' (61),
            # so sorting formatted strings would wrongly place "a-b=2" before "a=1".
            sorted_keys = sorted(live_values.keys())
            formatted_entries: List[str] = []
            for key in sorted_keys:
                formatted_entries.append(f"{key}={live_values[key]}")
            return formatted_entries
    

    Notice that scan() is simply scan_prefix(""), because every string in Python starts with the empty prefix "".

  6. Dispatch operations and trace a full example

    process_file_store_operations instantiates FileStore, dispatches each operation list in order, translates internal None misses on get / get_at to "", and collects one output element per command:

    def process_file_store_operations(operations: List[List[Any]]) -> List[Any]:
        """Run every operation in order and return one result per operation."""
        store = FileStore()
        results: List[Any] = []
    
        # Dispatch each operation and record its return value (None for writes)
        for op in operations:
            op_name = op[0]
            if op_name == "set":
                store.set(op[1], op[2])
                results.append(None)
            elif op_name == "set_ttl":
                store.set_ttl(op[1], op[2], op[3], op[4])
                results.append(None)
            elif op_name == "get" or op_name == "get_at":
                # A 3-element get/get_at queries a specific timestamp without moving store.now
                if len(op) >= 3:
                    target_time = op[2]
                else:
                    target_time = store.now
                value = store.read(op[1], target_time)
                results.append("" if value is None else value)
            elif op_name == "delete":
                results.append(store.delete(op[1]))
            elif op_name == "scan":
                results.append(store.scan_prefix(""))
            elif op_name == "scan_prefix":
                results.append(store.scan_prefix(op[1]))
            else:
                raise ValueError(f"unknown operation: {op_name}")
    
        return results
    

    Trace the 10-step workload from Example 1 to verify every interaction between now, raw-key sorting, TTL expiry, tombstones, and get_at:

    Step  Operation                                     now  Result                          Why
    1     ["set", "app", "v1"]                            0   None                            app -> [(0, "v1", None)]
    2     ["set", "app-canary", "v2"]                     0   None                            app-canary -> [(0, "v2", None)]
    3     ["scan_prefix", "app"]                          0   ["app=v1", "app-canary=v2"]     raw key "app" < "app-canary"
    4     ["set_ttl", "session/u9", "tokA", 10, 6]       10   None                            clock -> 10; live on [10, 16)
    5     ["get", "session/u9"]                          10   "tokA"                          10 < 16 (still live)
    6     ["set_ttl", "cfg/region", "us-west", 20, 50]   20   None                            clock -> 20; live on [20, 70)
    7     ["get", "session/u9"]                          20   ""                              20 >= 16 (expired at now=20)
    8     ["get_at", "session/u9", 14]                   20   "tokA"                          10 <= 14 < 16 in history!
    9     ["delete", "app-canary"]                       20   True                            appends tombstone at t=20
    10    ["scan"]                                       20   ["app=v1", "cfg/region=us-west"] app-canary deleted, session/u9 expired
    
  7. Complete solution

    Putting FileStore and process_file_store_operations together gives the complete solution:

    from typing import Any, Dict, List, Optional, Tuple
    from bisect import bisect_right
    
    
    class FileStore:
        """In-memory versioned key-value store supporting TTLs and historical reads."""
    
        def __init__(self) -> None:
            # Logical clock; starts at 0 and advances monotonically to the max set_ttl timestamp seen
            self.now: int = 0
            # Per-key write timestamps in non-decreasing order, e.g. {"doc": [0, 10, 20]}
            self.times: Dict[str, List[int]] = {}
            # Matching per-key (value, expires_at) pairs, e.g. {"doc": [("v1", None), ("v2", 15), (None, None)]}
            # value=None marks a delete tombstone; expires_at=None means the version never expires
            self.versions: Dict[str, List[Tuple[Optional[Any], Optional[int]]]] = {}
    
        def _write(
            self,
            key: str,
            value: Optional[Any],
            timestamp: int,
            expires_at: Optional[int],
        ) -> None:
            if key not in self.times:
                self.times[key] = []
                self.versions[key] = []
    
            key_times = self.times[key]
            # bisect_right inserts AFTER any existing writes with the exact same timestamp,
            # ensuring the later operation wins when two writes share a timestamp.
            insert_idx = bisect_right(key_times, timestamp)
            key_times.insert(insert_idx, timestamp)
            self.versions[key].insert(insert_idx, (value, expires_at))
    
        def read(self, key: str, query_time: int) -> Optional[Any]:
            """Return key's live value at query_time, or None if missing, deleted, or expired."""
            key_times = self.times.get(key)
            if not key_times:
                return None
    
            # Find the rightmost write with timestamp <= query_time
            version_idx = bisect_right(key_times, query_time) - 1
            if version_idx < 0:
                # Every write to this key happened strictly after query_time
                return None
    
            value, expires_at = self.versions[key][version_idx]
            if value is None:
                # Latest version at or before query_time is a delete tombstone
                return None
    
            # TTL window [timestamp, expires_at) is half-open: expired at query_time >= expires_at.
            # Do NOT fall back to older versions once an overwriting version expires.
            if expires_at is not None and query_time >= expires_at:
                return None
    
            return value
    
        def set(self, key: str, value: Any) -> None:
            # Permanent write at the current logical clock
            self._write(key, value, self.now, None)
    
        def set_ttl(self, key: str, value: Any, timestamp: int, ttl: int) -> None:
            # Advance the clock forward only; an out-of-order past write never rewinds self.now
            self.now = max(self.now, timestamp)
            self._write(key, value, timestamp, timestamp + ttl)
    
        def delete(self, key: str) -> bool:
            # Only a currently live key can be deleted
            if self.read(key, self.now) is None:
                return False
            # Append a tombstone rather than erasing history so past get_at queries still work
            self._write(key, None, self.now, None)
            return True
    
        def scan_prefix(self, prefix: str) -> List[str]:
            # Collect live values once per matching key at self.now
            live_values: Dict[str, Any] = {}
            for key in self.times:
                if key.startswith(prefix):
                    current_val = self.read(key, self.now)
                    if current_val is not None:
                        live_values[key] = current_val
    
            # Sort raw keys BEFORE formatting "key=value": ASCII '-' (45) < '=' (61),
            # so sorting formatted strings would wrongly place "a-b=2" before "a=1".
            sorted_keys = sorted(live_values.keys())
            formatted_entries: List[str] = []
            for key in sorted_keys:
                formatted_entries.append(f"{key}={live_values[key]}")
            return formatted_entries
    
    
    def process_file_store_operations(operations: List[List[Any]]) -> List[Any]:
        """Run every operation in order and return one result per operation."""
        store = FileStore()
        results: List[Any] = []
    
        # Dispatch each operation and record its return value (None for writes)
        for op in operations:
            op_name = op[0]
            if op_name == "set":
                store.set(op[1], op[2])
                results.append(None)
            elif op_name == "set_ttl":
                store.set_ttl(op[1], op[2], op[3], op[4])
                results.append(None)
            elif op_name == "get" or op_name == "get_at":
                # A 3-element get/get_at queries a specific timestamp without moving store.now
                if len(op) >= 3:
                    target_time = op[2]
                else:
                    target_time = store.now
                value = store.read(op[1], target_time)
                results.append("" if value is None else value)
            elif op_name == "delete":
                results.append(store.delete(op[1]))
            elif op_name == "scan":
                results.append(store.scan_prefix(""))
            elif op_name == "scan_prefix":
                results.append(store.scan_prefix(op[1]))
            else:
                raise ValueError(f"unknown operation: {op_name}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of this versioned file store like a notebook where every file (key) gets its own chronological ledger page. Instead of erasing old text when a file changes or is deleted, you add a new dated line at the bottom—including a tombstone (an explicit (None, None) marker recording "deleted at time t") when a file is removed.

Two naive approaches fail for opposite reasons: storing only the latest value per key in a plain dictionary makes historical get_at(key, timestamp) queries impossible once a key is overwritten or deleted, while keeping one giant flat list of every operation forces every single get to scan all previous writes in O(N) time.

By storing a sorted list of timestamps times[key] alongside versions[key] for each key, binary search (bisect_right, which repeatedly halves the search interval) jumps straight to the active version at any query_time in logarithmic time. Trace a quick 5-step example on key "flag":

  1. ["set", "flag", "base"] at now = 0 records times["flag"] = [0], versions["flag"] = [("base", None)].
  2. ["set_ttl", "flag", "promo", 8, 4] advances now = 8 and appends (8, ("promo", 12)).
  3. ["set_ttl", "cfg/region", "us-west", 20, 50] advances now = 20.
  4. ["get", "flag"] checks "flag" at now = 20: bisect_right([0, 8], 20) - 1 = 1 selects ("promo", 12), sees 20 >= 12 (expired), and returns "" without resurrecting "base".
  5. ["get_at", "flag", 10] checks "flag" at 10: bisect_right([0, 8], 10) - 1 = 1 selects ("promo", 12), sees 10 < 12, and returns "promo".

Complexity

Let W be the total number of write operations (set, set_ttl, and successful delete), v be the number of versions stored for a single key, K be the number of distinct keys ever written, P be the length of prefix, and m be the number of live keys matching a scan.

  • get / get_at: O(log v) time. We perform one O(1) dictionary lookup to fetch self.times[key] and one binary search (bisect_right) across that key's v sorted timestamps, followed by O(1) tombstone and expiry checks.
  • set and delete: O(log v) time. Because self.now is always greater than or equal to every timestamp already in self.times[key], bisect_right takes O(log v) to locate the end of the list and list.insert appends in O(1) amortized time (delete also runs one O(log v) read check first).
  • set_ttl: O(log v) when timestamps arrive in order, or O(v) worst-case for out-of-order past writes. Finding the insertion slot takes O(log v), and inserting into the middle of a Python list shifts up to v later elements for that key.
  • scan / scan_prefix: O(K * (P + log v) + m log m) time. We check prefix membership (O(P)) for each of the K keys in self.times, run one O(log v) read on prefix matches, and sort the m live matching keys in O(m log m) time.
  • Space: O(W) memory. Every write and delete tombstone appends at most one timestamp and one (value, expires_at) tuple, and historical versions are retained so get_at can query any past timestamp.

Edge cases

  • Empty input ([]): Returns [] cleanly without initializing any key lists.
  • Query before a key's first write: bisect_right(key_times, query_time) - 1 evaluates to -1, returning "".
  • Half-open TTL boundary ([timestamp, timestamp + ttl)): A key written at 10 with ttl = 5 has expires_at = 15, so it is live at t = 10 and t = 14, and expired at t = 15. If ttl <= 0, expires_at <= timestamp, so it is already expired at its own write timestamp.
  • Expired overwrite never resurrects an older permanent value: read checks only the latest version with timestamp <= query_time; if that version has expired, read returns None ("") rather than walking backward to an earlier permanent version.
  • Same-timestamp writes (including out-of-order historical writes): bisect_right inserts after equal timestamps and reads the rightmost equal timestamp, guaranteeing the later operation in operations always wins.
  • Deleting a missing, already-deleted, or expired key: self.read(key, self.now) is None, so delete returns False without writing an extra tombstone.
  • Out-of-order set_ttl and future get_at vs. self.now: self.now = max(self.now, timestamp) prevents older set_ttl calls from rewinding the clock, and get_at never modifies self.now.

Common mistakes

  • Using bisect_left instead of bisect_right when inserting or reading: With bisect_left, a second write at the same timestamp (such as two set calls while now == 0) lands before the first write, causing the older value to win instead of the newer one.
  • Deleting by popping or clearing self.versions[key]: Erasing the list destroys historical versions prior to self.now, breaking get_at(key, past_time).
  • Using > instead of >= for TTL expiration: Checking query_time > expires_at keeps a ttl = 5 entry written at 10 alive at 15 (6 ticks instead of 5).
  • Sorting the formatted "key=value" strings instead of sorting raw keys first: Because ASCII '-' (45) is smaller than '=' (61), sorting formatted strings puts "app-canary=v2" ahead of "app=v1", whereas key order requires "app" before "app-canary".
  • Walking backward past an expired version in read: Falling back to version_idx - 1 when versions[key][version_idx] is expired wrongly resurrects stale overwritten data.

Follow-up questions

  • How can you cap memory consumption when millions of historical versions accumulate over weeks of uptime? Introduce a configurable history retention window W (for example, keeping the last 24 hours of point-in-time queries). Any version strictly older than now - W can be garbage-collected except the single newest version at or before now - W, which is still needed to answer get_at(key, now - W). If that sole surviving anchor version is a tombstone or expired at or before now - W, the entire key can be deleted from self.times and self.versions during lazy per-key compaction or a periodic background sweep.
  • How would you speed up prefix scans when the keyspace holds millions of keys, most of which are already deleted or expired? Maintain an ordered index of currently live keys using a balanced search tree, skip list, or trie (a prefix tree where keys sharing a prefix share path nodes), paired with a min-heap of (expires_at, key) to evict keys lazily as self.now advances. Then scan_prefix(prefix) seeks directly to the first live key >= prefix in O(log K) (or O(len(prefix)) in a trie) and streams only the m live matches already in sorted order, completely avoiding dead keys and post-scan sorting.
  • What changes are needed to support crash recovery on disk and point-in-time prefix scans at an arbitrary past timestamp? For crash durability, append every mutating command (set, set_ttl, delete) as a checksummed record to an append-only write-ahead log (WAL)—a sequential disk file written and fsynced before acknowledging each write—and replay the log on startup alongside periodic background snapshots that allow older WAL segments to be truncated. For historical prefix scans (scan_prefix_at(prefix, timestamp)), pass timestamp instead of self.now into FileStore.read(key, timestamp) inside scan_prefix: keys created strictly after timestamp return None, while keys deleted or expired later still return the exact value they held at timestamp.

Follow-up questions

Similar questions

More Persona interview questions

All 1 Persona questions →