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]-> returnsNone. Storesvalueunderkeyat the current logical timenowwith no expiration.["set_ttl", key, value, timestamp, ttl]-> returnsNone. Advances the store's logical clock vianow = max(now, timestamp)and records a version ofkeywritten attimestampthat is live over the half-open interval[timestamp, timestamp + ttl)(active fortimestamp <= t < timestamp + ttl, and expired oncet >= timestamp + ttl).["get", key]-> returnsstr. Returns the live value ofkeyatnow, or""ifkeyhas no active value (never written, deleted, or expired).["get", key, timestamp]or["get_at", key, timestamp]-> returnsstr. Returns the value ofkeythat was live attimestampwithout modifyingnow, or""if no version was live attimestamp.["delete", key]-> returnsbool. Ifkeyhas a live value atnow, markskeydeleted atnow(while keeping earlier versions intact for historical reads) and returnsTrue; otherwise returnsFalse.["scan"]-> returnsList[str]. Lists"key=value"entries for every key currently live atnow, sorted in ascending lexicographical order bykey.["scan_prefix", prefix]-> returnsList[str]. Lists"key=value"entries for every key currently live atnowwhose name starts withprefix, sorted in ascending lexicographical order bykey.
Clock & Versioning Rules
- Monotonic logical clock:
nowstarts at0. Onlyset_ttlupdatesnow, settingnow = max(now, timestamp). An out-of-orderset_ttlwithtimestamp < nowinserts its version into historical order attimestampwithout movingnowbackward, and timestamped reads (getwith 3 arguments orget_at) never changenow. - Same-timestamp tie-breaking: When two or more writes (
set,set_ttl, ordelete) target the samekeyat the exact same timestamp, the command that appears later inoperationssupersedes earlier ones at that timestamp. - No fallback to overwritten versions: A write at time
t_wreplaces whatever version held prior tot_w. If aset_ttlwrite overwrites an older permanentsetvalue and subsequently expires, queries at or after its expiration time must return""rather than reviving the older value. - Raw-key sort order:
scanandscan_prefixsort by the rawkeystring 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^5keyis a non-empty ASCII string;valueis a string;prefixis a possibly empty ASCII string.timestampandttlare integers (ttl <= 0means the entry's[timestamp, timestamp + ttl)interval is empty, so it is never live).- Point-in-time queries (
get_ator 3-argumentget) may pass negative, zero, or arbitrarily large integer timestamps.
Step-by-step walkthrough
Pin down the operations and clock rules
Each command in
operationsis a list whose first item names the action and appends one entry to the returned results list:Operation Return value Behavior ["set", key, value]NoneWrites valueatnowwith no expiration["set_ttl", key, value, timestamp, ttl]NoneAdvances now = max(now, timestamp); live ontimestamp <= t < timestamp + ttl["get", key]strLive value at now, or""if missing, deleted, or expired["get", key, t]or["get_at", key, t]strLive value as of time twithout changingnow, or""["delete", key]boolIf live at now, deleteskeyatnowand returnsTrue; elseFalse["scan"]List[str]["key=value", ...]for all keys live atnow, sorted bykey["scan_prefix", prefix]List[str]Same as scan, restricted to keys starting withprefixThree boundary rules remove all ambiguity:
- Monotonic clock:
nowstarts at0and advances tomax(now, timestamp)wheneverset_ttlruns. Neitherget_atnor an out-of-orderset_ttlwith a smaller timestamp ever rewindsnow. - 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 att = 0, overwritten by a temporaryset_ttlatt = 8expiring att = 12, then att = 12key"flag"is empty ("")—the overwrittent = 0version does not come back to life.
- Monotonic clock:
Why a plain dictionary or flat log falls short
A standard dictionary
store[key] = (value, expires_at)handles present-timeget,delete, andscaneasily, 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 att = 20.At the opposite extreme, appending
(timestamp, seq_num, key, value, expires_at)to a single flat list preserves every historical version, but everygetmust scan the entire list ofNoperations to find the latest entry forkeywithtimestamp <= t. OverN = 100,000operations,O(N)per read balloons toO(N^2)(10^10steps).Key idea: per-key sorted timelines + binary search
Because a
getasks about one specifickeyat one specificquery_time, group writes bykeyand 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 fort < 20still see the earlier history.To read
"flag"atquery_time = 10, we run binary search (bisect_right(times["flag"], 10) - 1), which halves the search range at each step inO(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_rightduring_writealso gives the same-timestamp tie-breaker for free: inserting atbisect_right(key_times, timestamp)places a newer write to the right of any existing writes with that exact timestamp, andbisect_right(key_times, query_time) - 1duringreadalways picks the rightmost one.Implement versioned writes and point-in-time reads
Let's code the core
FileStorestate,_write, andreadfirst. Notice thatreadinspects onlyversions[key][version_idx]—if that version is a tombstone or has expired (query_time >= expires_at),readreturnsNoneimmediately 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 valueLayer `set`, `set_ttl`, `delete`, and `scan_prefix` on top
With
_writeandreadin place, every high-level store method is short and clean. Watch out for a classic string-sorting trap inscan_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 theread(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_entriesNotice that
scan()is simplyscan_prefix(""), because every string in Python starts with the empty prefix"".Dispatch operations and trace a full example
process_file_store_operationsinstantiatesFileStore, dispatches each operation list in order, translates internalNonemisses onget/get_atto"", 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 resultsTrace the 10-step workload from Example 1 to verify every interaction between
now, raw-key sorting, TTL expiry, tombstones, andget_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 expiredComplete solution
Putting
FileStoreandprocess_file_store_operationstogether 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":
["set", "flag", "base"]atnow = 0recordstimes["flag"] = [0],versions["flag"] = [("base", None)].["set_ttl", "flag", "promo", 8, 4]advancesnow = 8and appends(8, ("promo", 12)).["set_ttl", "cfg/region", "us-west", 20, 50]advancesnow = 20.["get", "flag"]checks"flag"atnow = 20:bisect_right([0, 8], 20) - 1 = 1selects("promo", 12), sees20 >= 12(expired), and returns""without resurrecting"base".["get_at", "flag", 10]checks"flag"at10:bisect_right([0, 8], 10) - 1 = 1selects("promo", 12), sees10 < 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 oneO(1)dictionary lookup to fetchself.times[key]and one binary search (bisect_right) across that key'svsorted timestamps, followed byO(1)tombstone and expiry checks.setanddelete:O(log v)time. Becauseself.nowis always greater than or equal to every timestamp already inself.times[key],bisect_righttakesO(log v)to locate the end of the list andlist.insertappends inO(1)amortized time (deletealso runs oneO(log v)readcheck first).set_ttl:O(log v)when timestamps arrive in order, orO(v)worst-case for out-of-order past writes. Finding the insertion slot takesO(log v), and inserting into the middle of a Python list shifts up tovlater 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 theKkeys inself.times, run oneO(log v)readon prefix matches, and sort themlive matching keys inO(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 soget_atcan 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) - 1evaluates to-1, returning"". - Half-open TTL boundary (
[timestamp, timestamp + ttl)): A key written at10withttl = 5hasexpires_at = 15, so it is live att = 10andt = 14, and expired att = 15. Ifttl <= 0,expires_at <= timestamp, so it is already expired at its own write timestamp. - Expired overwrite never resurrects an older permanent value:
readchecks only the latest version withtimestamp <= query_time; if that version has expired,readreturnsNone("") rather than walking backward to an earlier permanent version. - Same-timestamp writes (including out-of-order historical writes):
bisect_rightinserts after equal timestamps and reads the rightmost equal timestamp, guaranteeing the later operation inoperationsalways wins. - Deleting a missing, already-deleted, or expired key:
self.read(key, self.now)isNone, sodeletereturnsFalsewithout writing an extra tombstone. - Out-of-order
set_ttland futureget_atvs.self.now:self.now = max(self.now, timestamp)prevents olderset_ttlcalls from rewinding the clock, andget_atnever modifiesself.now.
Common mistakes
- Using
bisect_leftinstead ofbisect_rightwhen inserting or reading: Withbisect_left, a second write at the same timestamp (such as twosetcalls whilenow == 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 toself.now, breakingget_at(key, past_time). - Using
>instead of>=for TTL expiration: Checkingquery_time > expires_atkeeps attl = 5entry written at10alive at15(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 toversion_idx - 1whenversions[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 thannow - Wcan be garbage-collected except the single newest version at or beforenow - W, which is still needed to answerget_at(key, now - W). If that sole surviving anchor version is a tombstone or expired at or beforenow - W, the entire key can be deleted fromself.timesandself.versionsduring 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 asself.nowadvances. Thenscan_prefix(prefix)seeks directly to the first live key>= prefixinO(log K)(orO(len(prefix))in a trie) and streams only themlive 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 andfsynced 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)), passtimestampinstead ofself.nowintoFileStore.read(key, timestamp)insidescan_prefix: keys created strictly aftertimestampreturnNone, while keys deleted or expired later still return the exact value they held attimestamp.
Follow-up questions
- How can you cap memory consumption when millions of historical versions accumulate over weeks of uptime?
- How would you speed up prefix scans when the keyspace holds millions of keys, most of which are already deleted or expired?
- What changes are needed to support crash recovery on disk and point-in-time prefix scans at an arbitrary past timestamp?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array