Two-Level In-Memory Store with Field Expiration
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Design an in-memory two-tier data store TimestampedDB where every top-level key maps to named field entries, and each field optionally carries an integer time-to-live (ttl). Missing fields and expired fields must behave identically on reads and scans.
Class and Method Signatures
from typing import Any, List, Optional, Tuple
class TimestampedDB:
def __init__(self) -> None: ...
def SET(self, key: str, field: str, value: Any, ttl: int, now: int = 0) -> None: ...
def GET(self, key: str, field: str, now: int) -> Optional[Any]: ...
def DELETE(self, key: str, field: str) -> None: ...
def SCAN(self, key: str, now: int) -> List[Tuple[str, Any]]: ...
def SCAN_PREFIX(self, key: str, field_prefix: str, now: int) -> List[Tuple[str, Any]]: ...
Operation Rules
SET(key, field, value, ttl, now=0):- Writes
valueunder(key, field)at integer clock timestampnow(defaulting to0), replacing any previous value and expiration setting on that field. - If
ttl > 0, the entry stays live during[now, now + ttl)—meaning it is live whilet < now + ttland expired at every timestampt >= now + ttl. - If
ttl == 0, the entry never expires. - If
ttl < 0, raiseValueErrorwithout modifying the store.
- Writes
GET(key, field, now):- Returns the stored value if
(key, field)is present and live at timestampnow; otherwise returnsNone.
- Returns the stored value if
DELETE(key, field):- Removes
(key, field)if present; ifkeyorfielddoes not exist, performs no action.
- Removes
SCAN(key, now):- Returns a list of
(field, value)tuples for every live field underkeyat timestampnow, sorted in ascending lexicographic (Unicode code-point) order byfield. Returns[]ifkeyis absent or has no live fields.
- Returns a list of
SCAN_PREFIX(key, field_prefix, now):- Returns a list of
(field, value)tuples for every live field underkeyat timestampnowwhosefieldname begins withfield_prefix, sorted in ascending lexicographic order byfield. Returns[]when nothing matches.
- Returns a list of
Examples
Example 1
db = TimestampedDB()
db.SET("acct:42", "token", "xyz9", 60) # written at default now=0; expires at t=60
db.SET("acct:42", "plan", "pro", 0) # ttl=0 -> never expires
db.GET("acct:42", "token", 25) # -> "xyz9"
db.SCAN("acct:42", 25) # -> [("plan", "pro"), ("token", "xyz9")]
db.GET("acct:42", "token", 60) # -> None
db.SCAN("acct:42", 75) # -> [("plan", "pro")]
Explanation: At t = 25, both "plan" and "token" are live (25 < 60), and SCAN orders "plan" before "token" alphabetically. At t = 60, "token" reaches 0 + 60 and expires, so GET returns None and later scans emit only "plan".
Example 2
db = TimestampedDB()
db.SET("cfg:web", "db_host", "10.0.0.5", 0, now=10)
db.SET("cfg:web", "db_port", 5432, 20, now=10) # expires at 10 + 20 = 30
db.SET("cfg:web", "cache_url", "10.0.0.9", 0, now=10)
db.SCAN_PREFIX("cfg:web", "db_", 25) # -> [("db_host", "10.0.0.5"), ("db_port", 5432)]
db.SCAN_PREFIX("cfg:web", "db_", 30) # -> [("db_host", "10.0.0.5")]
db.DELETE("cfg:web", "cache_url")
db.SCAN("cfg:web", 30) # -> [("db_host", "10.0.0.5")]
Explanation: SCAN_PREFIX inspects only fields starting with "db_". At t = 25 both "db_host" and "db_port" are live; by t = 30, "db_port" has expired (30 >= 30), and deleting "cache_url" leaves "db_host" as the sole live entry under "cfg:web".
Constraints
- At most
100,000operations per test run. keyandfieldare non-empty strings;field_prefixis a string (possibly"").nowis an integer system timestamp that never decreases across consecutive calls on the sameTimestampedDBinstance.
Step-by-step walkthrough
Restate the problem and pin down the TTL rules
We need an in-memory database that stores values under a two-level hierarchy
key -> field -> value, where each field can optionally expire after a Time-To-Live (TTL) — a lifespan measured in integer time units. It supports five operations (SET,GET,DELETE,SCAN, andSCAN_PREFIX) for up to 100,000 calls.Before coding, clarify three subtle details in the problem statement:
- Write timestamp on
SET. Computingnow + ttlrequires knowing the write timenow, yet callers starting att = 0may omit the write timestamp (as indb.SET("acct:42", "token", "xyz9", 60)expiring att = 60). Addingnow: int = 0with default0supports both four-argument calls att = 0and writes at later timestamps. - Exact expiration boundary. Consistent with
"token"expiring att = 60, an entry written atnowwithttl > 0is live while current time< now + ttland expired starting atnow + ttl(the half-open interval[now, now + ttl)). Settingttl == 0means the entry never expires;ttl < 0raisesValueError. - Non-decreasing system clock. Because
nowrepresents system time moving forward, once an entry has expired at timet, it remains expired at all future times.
SET("k", "f", "v", ttl=10, now=5) --> expires_at = 15 time: 5 6 ... 13 14 | 15 16 ... state: [------- LIVE --------) [--- EXPIRED ---- Write timestamp on
Why a flat dictionary is too slow for scans
The simplest design stores one flat dictionary mapping
(key, field) -> (value, expires_at). That makesSET,GET, andDELETEO(1), but everySCAN(key, now)must inspect every entry in the entire database just to find the ones belonging tokey, and then sort them.Suppose 50,000
SETcalls create 5,000 keys with 10 fields each, followed by 50,000SCANcalls. A flat dictionary checks50,000 * 50,000 = 2.5 * 10^9entries, timing out easily even though all 50,000 scans output only500,000field-value pairs in total.What if we nest dictionaries (
key -> {field: (value, expires_at)}) and sortfields.keys()on every scan? That isolates keys from each other, but if a single key holds 50,000 fields andSCAN_PREFIXmatches only 2 of them, sorting all 50,000 field names on every prefix scan still wastesO(f log f)work per call.Store a dictionary plus a sorted field list per key
To make point lookups fast and prefix scans proportional to the matching slice, we give each key a small
_Fieldscontainer holding two synchronized structures:cells: a dictionaryfield -> (value, expires_at)forO(1)average point lookups and updates.names: a Python list of the exact same field names, kept in lexicographic order (dictionary order comparing characters by Unicode code point, so"plan" < "token"and"B" < "a10" < "a2" < "b").
Notice that we store the absolute expiration timestamp
expires_at = now + ttl(orNonewhenttl == 0), not the rawttl. That turns every future expiration check into one simple comparisonnow < expires_at.from typing import Any, Dict, List, Optional, Tuple def _is_live(expires_at: Optional[int], now: int) -> bool: """Return True if the entry never expires (None) or has not yet reached expires_at.""" # Half-open window [write_time, write_time + ttl): live while now < expires_at, expired at now == expires_at return expires_at is None or now < expires_at class _Fields: """Per-key container keeping O(1) field lookups in sync with sorted field names.""" def __init__(self) -> None: # cells: {field_name: (value, expires_at)}, e.g. {"plan": ("pro", None), "token": ("xyz9", 60)} self.cells: Dict[str, Tuple[Any, Optional[int]]] = {} # names: sorted list of the exact same field names in cells, e.g. ["plan", "token"] self.names: List[str] = []Implement SET, GET, and DELETE with lazy expiry
Every write or cleanup must keep
cellsandnamesholding the exact same set of field names:SET: Computeexpires_at. Iffieldis not incellsyet, insert it intonamesin sorted position usingbisect.insort. (Skippinginsortwhenfieldalready exists prevents duplicate names on updates!) Then write(value, expires_at)intocells[field], which cleanly replaces any previous value and TTL.GET: Look up(value, expires_at)incells. If it has expired, remove it on the spot (lazy deletion — cleaning up expired items when a read encounters them rather than running background timers) and returnNone.DELETEand_remove: Delete fromcells, locate the field innamesvia binary search (bisect_left— halving the sorted search range at each step inO(log f)comparisons) and pop it, and deletekeyfromself._keysonce no fields remain so empty keys occupy zero memory.
from typing import Any, Dict, Optional import bisect class TimestampedDB: def __init__(self) -> None: # _keys: {key: _Fields}, storing only keys that currently hold at least one field self._keys: Dict[str, _Fields] = {} def SET(self, key: str, field: str, value: Any, ttl: int, now: int = 0) -> None: if ttl < 0: raise ValueError("ttl must be >= 0") # ttl == 0 means no expiration; ttl > 0 converts to an absolute expiration timestamp expires_at: Optional[int] = None if ttl > 0: expires_at = now + ttl fields = self._keys.get(key) if fields is None: fields = _Fields() self._keys[key] = fields # Insert into the sorted list ONLY when the field is new so updates never create duplicate names if field not in fields.cells: bisect.insort(fields.names, field) # Overwrite both the value and the expiration timestamp fields.cells[field] = (value, expires_at) def GET(self, key: str, field: str, now: int) -> Optional[Any]: fields = self._keys.get(key) if fields is None or field not in fields.cells: return None value, expires_at = fields.cells[field] if not _is_live(expires_at, now): # Lazy deletion: system time never moves backward, so an expired entry stays expired forever self._remove(key, field) return None return value def DELETE(self, key: str, field: str) -> None: fields = self._keys.get(key) if fields is not None and field in fields.cells: self._remove(key, field) def _remove(self, key: str, field: str) -> None: """Delete one field from both cells and names, dropping the key if it becomes empty.""" fields = self._keys[key] del fields.cells[field] index = bisect.bisect_left(fields.names, field) fields.names.pop(index) if not fields.cells: del self._keys[key]Implement SCAN and SCAN_PREFIX with binary search
SCAN(key, now): Walkfields.namesfrom left to right. Becausenamesis already sorted, appending live pairs produces a sorted output with zero sorting work! At the same time, delete expired entries fromfields.cellsand rebuildfields.namesfromlive_namesin one linear pass (avoiding bothO(f^2)repeated listpops and Python'sRuntimeErrorfrom deleting dictionary keys while iterating over that dictionary).SCAN_PREFIX(key, field_prefix, now): In sorted order, every string that starts withfield_prefixis>= field_prefix, and all such strings sit right next to each other in one contiguous block:
fields.names: ["a", "aa", "ab", "abc", "ac", "b"] index: 0 1 2 3 4 5 ▲ ▲ bisect_left("ab") = 2 ──┘ └── "ac".startswith("ab") is False: stop!So
bisect_left(fields.names, field_prefix)jumps straight to the start of the matching run inO(log f)steps, and awhileloop walks forward only whilestartswith(field_prefix)holds, collecting live pairs.from typing import Any, List, Tuple import bisect class TimestampedDB: def SCAN(self, key: str, now: int) -> List[Tuple[str, Any]]: fields = self._keys.get(key) if fields is None: return [] result: List[Tuple[str, Any]] = [] live_names: List[str] = [] # Walk names in sorted order; purge expired entries from cells while keeping live names sorted for name in fields.names: value, expires_at = fields.cells[name] if _is_live(expires_at, now): result.append((name, value)) live_names.append(name) else: del fields.cells[name] fields.names = live_names if not fields.cells: del self._keys[key] return result def SCAN_PREFIX(self, key: str, field_prefix: str, now: int) -> List[Tuple[str, Any]]: fields = self._keys.get(key) if fields is None: return [] result: List[Tuple[str, Any]] = [] # In lexicographic order, all strings starting with field_prefix form one contiguous slice # starting at the first element >= field_prefix index = bisect.bisect_left(fields.names, field_prefix) while index < len(fields.names) and fields.names[index].startswith(field_prefix): name = fields.names[index] value, expires_at = fields.cells[name] if _is_live(expires_at, now): result.append((name, value)) index += 1 return resultTrace the samples step by step
Let's trace Example 1 from the statement step by step:
1. SET("acct:42", "token", "xyz9", ttl=60, now=0) cells = {"token": ("xyz9", 60)} names = ["token"] 2. SET("acct:42", "plan", "pro", ttl=0, now=0) insort("plan") places "plan" before "token" cells = {"token": ("xyz9", 60), "plan": ("pro", None)} names = ["plan", "token"] 3. GET("acct:42", "token", now=25) 25 < 60 -> live -> returns "xyz9" 4. SCAN("acct:42", now=25) walks ["plan", "token"]: both live -> returns [("plan", "pro"), ("token", "xyz9")] 5. GET("acct:42", "token", now=60) 60 < 60 is False -> expired! lazily removes "token" from cells and names -> names = ["plan"] returns None 6. SCAN("acct:42", now=75) walks ["plan"]: live -> returns [("plan", "pro")]Complete solution
from typing import Any, Dict, List, Optional, Tuple import bisect def _is_live(expires_at: Optional[int], now: int) -> bool: """Return True if the entry never expires (None) or has not yet reached expires_at.""" # Half-open window [write_time, write_time + ttl): live while now < expires_at, expired at now == expires_at return expires_at is None or now < expires_at class _Fields: """Per-key container keeping O(1) field lookups in sync with sorted field names.""" def __init__(self) -> None: # cells: {field_name: (value, expires_at)}, e.g. {"plan": ("pro", None), "token": ("xyz9", 60)} self.cells: Dict[str, Tuple[Any, Optional[int]]] = {} # names: sorted list of the exact same field names in cells, e.g. ["plan", "token"] self.names: List[str] = [] class TimestampedDB: """Two-level in-memory key -> field -> value store with optional per-field TTL.""" def __init__(self) -> None: # _keys: {key: _Fields}, storing only keys that currently hold at least one field self._keys: Dict[str, _Fields] = {} def SET(self, key: str, field: str, value: Any, ttl: int, now: int = 0) -> None: if ttl < 0: raise ValueError("ttl must be >= 0") # ttl == 0 means no expiration; ttl > 0 converts to an absolute expiration timestamp expires_at: Optional[int] = None if ttl > 0: expires_at = now + ttl fields = self._keys.get(key) if fields is None: fields = _Fields() self._keys[key] = fields # Insert into the sorted list ONLY when the field is new so updates never create duplicate names if field not in fields.cells: bisect.insort(fields.names, field) # Overwrite both the value and the expiration timestamp fields.cells[field] = (value, expires_at) def GET(self, key: str, field: str, now: int) -> Optional[Any]: fields = self._keys.get(key) if fields is None or field not in fields.cells: return None value, expires_at = fields.cells[field] if not _is_live(expires_at, now): # Lazy deletion: system time never moves backward, so an expired entry stays expired forever self._remove(key, field) return None return value def DELETE(self, key: str, field: str) -> None: fields = self._keys.get(key) if fields is not None and field in fields.cells: self._remove(key, field) def SCAN(self, key: str, now: int) -> List[Tuple[str, Any]]: fields = self._keys.get(key) if fields is None: return [] result: List[Tuple[str, Any]] = [] live_names: List[str] = [] # Walk names in sorted order; purge expired entries from cells while keeping live names sorted for name in fields.names: value, expires_at = fields.cells[name] if _is_live(expires_at, now): result.append((name, value)) live_names.append(name) else: del fields.cells[name] fields.names = live_names if not fields.cells: del self._keys[key] return result def SCAN_PREFIX(self, key: str, field_prefix: str, now: int) -> List[Tuple[str, Any]]: fields = self._keys.get(key) if fields is None: return [] result: List[Tuple[str, Any]] = [] # In lexicographic order, all strings starting with field_prefix form one contiguous slice # starting at the first element >= field_prefix index = bisect.bisect_left(fields.names, field_prefix) while index < len(fields.names) and fields.names[index].startswith(field_prefix): name = fields.names[index] value, expires_at = fields.cells[name] if _is_live(expires_at, now): result.append((name, value)) index += 1 return result def _remove(self, key: str, field: str) -> None: """Delete one field from both cells and names, dropping the key if it becomes empty.""" fields = self._keys[key] del fields.cells[field] index = bisect.bisect_left(fields.names, field) fields.names.pop(index) if not fields.cells: del self._keys[key]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a filing cabinet where each drawer folder is a key (like "acct:42"). Inside each folder, you keep two things together: index cards for each field stamped with an expiration time so you can grab any single field immediately, plus an alphabetical checklist of field names on the inside cover so you can read off all fields—or jump straight to fields starting with "db_"—without touching any other folder or re-alphabetizing the whole drawer.
A naive store that puts (key, field) pairs into one giant flat dictionary fails because every SCAN(key, now) has to inspect every entry across all keys—turning 50,000 scans over 50,000 entries into 2.5 billion checks. Even if you group fields by key in nested dictionaries, sorting all fields of key from scratch on every SCAN_PREFIX wastes O(f log f) time when a key has 50,000 fields and only 2 match the prefix.
Walk through a small example on key = "acct:42":
1. SET("acct:42", "token", "xyz9", ttl=60, now=0) converts the Time-To-Live (TTL) (how long an entry stays valid) into an absolute expiration timestamp 0 + 60 = 60, stores ("xyz9", 60) in cells["token"], and puts "token" into the sorted list names = ["token"].
2. SET("acct:42", "plan", "pro", ttl=0, now=0) stores ("pro", None) (None means no expiry) and uses binary search (repeatedly halving the sorted list to find the insertion spot) to keep names = ["plan", "token"] in lexicographic order (dictionary order by character code).
3. At now = 25, SCAN("acct:42", 25) walks ["plan", "token"] in order, sees None for "plan" and 25 < 60 for "token", and returns [("plan", "pro"), ("token", "xyz9")].
4. At now = 60, GET("acct:42", "token", 60) sees 60 >= 60, removes "token" from both cells and names via lazy deletion (cleaning up expired data when a read touches it), and returns None.
Complexity
Let f be the number of fields currently stored under the target key (live fields plus any expired fields not yet purged), r be the number of stored fields under key that start with field_prefix, and N be the total number of live or unpurged (key, field) pairs across the whole database (treating string lengths as small constants).
SETon an existing field: O(1) average time. We do one hash-map lookup forkey, checkfield in fields.cellsinO(1), and overwritefields.cells[field]without touching the sorted list.SETon a new field: O(f) worst-case time.bisect.insortlocates the sorted position inO(log f)comparisons and shifts at mostflist references by one slot in C memory (fast for up to 100,000 operations; replaceable by a balanced tree for strictO(log f)).GET: O(1) average time on a live hit or miss; O(f) when lazily removing an expired field because popping fromfields.namesshifts the tail of that key's list.DELETE: O(f) time to binary-searchfields.namesinO(log f)and shift the remaining list elements onpop.SCAN: O(f) time. We make one linear pass overfields.names, emitting live pairs already in sorted order and rebuildinglive_namesin place without re-sorting.SCAN_PREFIX: O(log f + r) time.bisect_leftjumps to the first field>= field_prefixinO(log f)steps, and thewhileloop inspects only therfields that actually start withfield_prefix.- Space: O(N) total memory. Every stored
(key, field)pair appears once in its key'scellsdictionary and once in its key'snameslist, and empty keys are deleted immediately.
Edge cases
- Accessing or deleting a missing key or field:
GETreturnsNone,SCANandSCAN_PREFIXreturn[], andDELETEsafely does nothing. - Exact expiration boundary (
now == write_time + ttl): treated as expired (now < expires_atis required to be live), so an entry written atnow = 5withttl = 10is live att = 14and expired att = 15. - Overwriting an existing field's TTL:
SETreplaces bothvalueandexpires_at, allowing callers to extend a TTL, shorten it, make an expiring field permanent (ttl = 0), or add a TTL to a permanent field, without duplicating the field name innames. - All fields under a key expire:
SCANreturns[]and removes the empty key fromself._keys; subsequentSETcalls cleanly recreate it. - Prefix boundary cases:
field_prefix = ""returns the same result asSCAN; a prefix equal to an exact field name ("ab") includes"ab"itself; a prefix with no matches returns[]. - ASCII / Unicode code-point sorting: uppercase letters sort before lowercase (
"B" < "a10" < "a2" < "b").
Common mistakes
- Storing relative
ttlinstead of absolutenow + ttl: without recording when the entry expires on the timeline, later reads cannot tell how much time has elapsed. - Calling
bisect.insortunconditionally on everySET: updating an existing field adds a second copy of its name tofields.names, causing duplicate rows inSCANandKeyErrorcrashes afterDELETE. - Mutating
fields.cellswhile iterating overfields.cells: raisesRuntimeError: dictionary changed size during iterationin Python; iterating overfields.nameswhile deleting fromfields.cellsavoids this cleanly. - Computing a prefix upper bound with
prefix + "\uffff"orchr(ord(prefix[-1]) + 1): breaks on empty prefixes""or characters aboveU+FFFF. Walking forward withstartswith(field_prefix)frombisect_left(names, field_prefix)is exact for every string. - Using lazy deletion when timestamps can move backward: if queries could ask about past points in time (
now = 25afternow = 75), physically deleting at75would lose historical state. Lazy deletion relies onnowbeing non-decreasing system time.
Alternative approaches
- Sort on read (nested dictionaries only): keep only
key -> {field: (value, expires_at)}and sort matching fields insideSCANandSCAN_PREFIX.SETandDELETEbecomeO(1)average always, at the cost ofO(f + m log m)per scan (mmatching fields)—a good trade-off when writes far outnumber scans. - Balanced search tree or skip list per key: guarantees
O(log f)worst-case inserts and deletes even if one key receives 100,000 new fields in reverse sorted order, at the cost of significantly more code if third-party libraries likesortedcontainersare unavailable.
Follow-up questions
- How would you scale this store across machines and disk tiers if the dataset grew to billions of keys beyond a single host's RAM? Partition data across a cluster of nodes by
keyusing consistent hashing (mapping keys and servers onto a hash ring so adding or removing a node moves only ~1/Mof the keys). Keeping every field of a singlekeyon one shard preserves single-nodeGET,SCAN, andSCAN_PREFIXwithout cross-node scatter-gather queries (unless a single "hot" key holds millions of fields and requires sub-sharding by field range). For cold keys that exceed RAM capacity, spill data onto disk using an LSM-tree storage engine (Log-Structured Merge-tree — an engine like RocksDB that writes sequentially to sorted disk files, keeping prefix scans fast) while caching hot keys in memory. - Which auxiliary structure lets a background sweeper reclaim expired fields without iterating through every live key? Maintain a min-heap (a binary tree priority queue that always keeps the smallest element at the top in
O(log N)time) of(expires_at, key, field)entries pushed wheneverSETassignsttl > 0. A background worker periodically pops entries from the heap whiletop.expires_at <= now; before deleting(key, field)from the store, it verifies thatcells[field]still carries that exactexpires_atso stale heap entries from overwritten or deleted fields are harmlessly skipped. Alternatively, Redis-style probabilistic sampling (periodically checking 20 random keys with TTLs and repeating while >25% are expired) avoids extra heap memory altogether. - How would you synchronize concurrent reader and writer threads without serializing operations on unrelated keys? Because every method (
SET,GET,DELETE,SCAN,SCAN_PREFIX) acts on a singlekey, use lock striping (splittingself._keysinto a fixed number of buckets—such as 256 shards indexed byhash(key) % 256—each guarded by its ownthreading.Lock) so threads operating on different keys proceed concurrently without unbounded per-key lock memory. BecauseGETandSCANperform lazy deletions, they mutate state and must acquire the shard's exclusive lock (or, under a readers-writer lock, skip physical removal during read-locked queries and defer cleanup to writes and a background sweeper). Always return a freshly allocated list fromSCANandSCAN_PREFIXbefore releasing the lock so callers never iterate over shared internal lists.
Follow-up questions
- How would you scale this store across machines and disk tiers if the dataset grew to billions of keys beyond a single host's RAM?
- Which auxiliary structure lets a background sweeper reclaim expired fields without iterating through every live key?
- How would you synchronize concurrent reader and writer threads without serializing operations on unrelated keys?
Similar questions
- Debugging Out-of-Order Fetch Results in React
- Resilient Caching Client for Daily Equity Prices
- In-Memory Publish-Subscribe Event Bus
- Multi-Car Elevator Dispatch Simulator
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger