Transactional Key-Value Store with Expiring Keys
Hard · Coding & Algorithms · Backend Engineer · Technical Screen
Problem Statement
Implement an in-memory key-value engine driven by an integer logical clock time (initialized to 0) that supports expiring entries and at most one open transaction at any moment.
Given two parallel lists operations and arguments of equal length, execute_ttl_key_value_store(operations, arguments) executes each command sequentially on a fresh store and returns a list of outputs (one entry per command: the looked-up str or None for "GET", and None for every other command):
"SET"with[key, value, ttl]: binds stringkeyto stringvaluewith expiration timestamptime + ttl, measured relative to the clock value at the moment"SET"executes. Outside a transaction, this updates permanent storage immediately; inside an active transaction, it updates only the pending transactional workspace."GET"with[key]: resolveskeyin the current visibility scope (consulting pending transactional edits first when a transaction is open, and permanent storage otherwise). Returns the associated string ifkeyis present andtime < expire_at; returnsNoneifkeywas never written, was deleted in the current scope, or has reachedtime >= expire_at(note that an expired write inside an open transaction shadows any older committed entry forkeyuntil rollback)."DELETE"with[key]: eraseskeyfrom the current scope (doing nothing ifkeyis absent). Inside an open transaction,keyreads asNoneuntil the transaction either commits or aborts."TICK"with[]: advances the logical clocktimeby1. No other command changestime."BEGIN"with[]: opens a new transaction if none is currently active. Calling"BEGIN"while a transaction is already open is a no-op that keeps all pending edits intact."COMMIT"with[]: flushes all pending writes and deletions from the open transaction into permanent storage (preserving each entry's originalexpire_attimestamp) and closes the transaction. Does nothing if no transaction is open."ROLLBACK"with[]: discards every pending write and deletion made since"BEGIN"and closes the transaction, leaving permanent storage unchanged. Does nothing if no transaction is open.
Examples
Example 1
Input:
operations = ["SET", "SET", "TICK", "BEGIN", "SET", "DELETE", "GET", "GET", "ROLLBACK", "GET", "TICK", "GET"]
arguments = [["token", "v1", 2], ["role", "admin", 5], [], [], ["token", "v2", 4], ["role"], ["token"], ["role"], [], ["role"], [], ["token"]]
Output:
[None, None, None, None, None, None, "v2", None, None, "admin", None, None]
At time = 0, "token" is stored with expire_at = 2 and "role" with expire_at = 5. After "TICK" (time = 1), a transaction overwrites "token" with "v2" (expire_at = 5) and deletes "role", so "GET" returns "v2" and None. "ROLLBACK" discards both edits, restoring "role" ("admin"). One more "TICK" advances time to 2, where "token" hits time >= expire_at (2 >= 2) and returns None.
Example 2
Input:
operations = ["BEGIN", "SET", "TICK", "COMMIT", "GET", "TICK", "GET", "TICK", "GET"]
arguments = [[], ["session", "s9", 3], [], [], ["session"], [], ["session"], [], ["session"]]
Output:
[None, None, None, None, "s9", None, "s9", None, None]
"session" is written at time = 0 with ttl = 3 (expire_at = 3) inside a transaction that commits at time = 1. Because expiration is anchored when "SET" runs rather than when "COMMIT" runs, "session" remains readable at time = 1 and time = 2, then expires at time = 3.
Constraints
0 <= len(operations) == len(arguments) <= 10^5- Every
operations[i]is one of"SET","GET","DELETE","TICK","BEGIN","COMMIT","ROLLBACK". - Keys and values are non-empty strings;
ttlis a positive integer (ttl >= 1). - Logical
timestarts at0and only increases via"TICK".
Step-by-step walkthrough
Understand the commands and visibility rules
We are building an in-memory key-value engine combining three mechanisms:
- Time-To-Live (TTL): each
SET(key, value, ttl)gives the entry a lifespan ofttlticks.GET(key)returns the stored string whiletime < expire_at, orNoneonce expired or absent. - Logical clock:
self.timestarts at0and advances by1exclusively onTICK()calls. - Single open transaction: between
BEGIN()andCOMMIT()/ROLLBACK(), mutations (SETandDELETE) affect only the open transaction's view, becoming permanent onCOMMIT()or disappearing onROLLBACK(). Outside a transaction, mutations apply straight to permanent storage.
The entry point
execute_ttl_key_value_store(operations, arguments)runs each command in sequence and collects one output per command (store.get(key)for"GET",Nonefor everything else).- Time-To-Live (TTL): each
Why cloning the entire map at BEGIN is too slow
A tempting shortcut for
ROLLBACKis copying the entire committed dictionary wheneverBEGIN()runs, mutating the copy, swapping it in onCOMMIT(), and discarding it onROLLBACK().While functionally right (our test suite uses it as a reference check), cloning costs
O(n)time and memory on everyBEGIN(), wherenis the total number of stored keys. Updating two keys inside a million-key store should take two operations, not a million copies.Key idea: delta overlay with tombstones and deadline timestamps
Two lightweight representation choices keep every single-key command
O(1)on average:- Record the deadline
expire_at = self.time + ttlon write: compute the exact tick at which a key expires the momentSETexecutes.TICKthen stays a singleself.time += 1increment without scanning entries, andCOMMITpreserves the original deadline. - Overlay
self.stagedatopself.data: keep committed entries inself.dataand record only keys modified afterBEGIN()insideself.staged. To represent a deletion inside a transaction, assignself.staged[key] = None—a tombstone (an explicit marker distinguishing "deleted during this transaction" from "untouched during this transaction"):
Lookup priority while a transaction is active: GET("token") ---> "token" in staged: ("v2", 5) ---> check 5 vs self.time GET("role") ---> "role" in staged: None ---> return None (tombstone masks data!) GET("other") ---> "other" not in staged ---> check self.data.get("other")- Record the deadline
Code state, TICK, SET, and DELETE
setanddeletewrite intoself.stagedwheneverself.in_transactionisTrue, and directly intoself.dataotherwise. Inside a transaction,deleteunconditionally recordsself.staged[key] = Noneeven whenkeyis absent fromself.data, in case an earlierSETin the same transaction stagedkey!class KVStore: def __init__(self): # Logical clock that advances by 1 only when tick() is called. self.time = 0 # data: committed entries mapping key -> (value, expire_at), e.g. {"a": ("1", 10)}. self.data: Dict[str, Tuple[str, int]] = {} # staged: uncommitted writes mapping key -> (value, expire_at), # or key -> None as a tombstone marking a pending DELETE. self.staged: Dict[str, Optional[Tuple[str, int]]] = {} self.in_transaction = False def tick(self) -> None: self.time += 1 def set(self, key: str, value: str, ttl: int) -> None: # Stamp the absolute expiration time right when SET executes so advancing # the clock never requires updating existing entries. entry = (value, self.time + ttl) if self.in_transaction: self.staged[key] = entry else: self.data[key] = entry def delete(self, key: str) -> None: if self.in_transaction: # Store None as a tombstone so GET knows the key was deleted in this # transaction rather than left untouched. self.staged[key] = None elif key in self.data: del self.data[key]Code GET: select the visible layer before testing expiry
Two subtle details in
getprevent stale committed values from leaking through:- Test membership with
key in self.staged, neverself.staged.get(key): whenkeyhas aNonetombstone,.get(key)returnsNone—indistinguishable from a missing key—which would wrongly fall through toself.data! - Evaluate
self.time >= expire_atafter picking the layer: if"token"is committed withexpire_at = 100, and an open transaction overwrites"token"withttl = 1(expire_at = 1) followed byTICK(), the transaction's overwrite is now expired and must returnNonerather than exposing the oldexpire_at = 100entry!
data: {"token": ("old", expire_at=100)} staged: {"token": ("new", expire_at=1)} at time = 1: Step 1: "token" in staged -> visible entry is ("new", 1) Step 2: time (1) >= expire_at (1) -> expired! Return None (never fall back to "old").def get(self, key: str) -> Optional[str]: # Check `key in self.staged` (not `.get()`) so a None tombstone or an expired # staged write hides any older committed value in `self.data`. if self.in_transaction and key in self.staged: entry = self.staged[key] else: entry = self.data.get(key) if entry is None: return None value, expire_at = entry # A key set at t with ttl expires at t + ttl, so time >= expire_at means expired. if self.time >= expire_at: return None return value- Test membership with
Code BEGIN, COMMIT, and ROLLBACK
begin()opens a cleanself.staged = {}workspace only when no transaction is already open.commit()replays every entry ofself.stagedontoself.data:Nonetombstones delete keys fromself.data, while(value, expire_at)tuples overwriteself.data[key]with their originalexpire_at.rollback()resetsself.staged = {}andself.in_transaction = FalseinO(1).
def begin(self) -> None: # Only one transaction may be active at a time; ignore nested BEGIN calls # so pending staged writes are not wiped out. if not self.in_transaction: self.in_transaction = True self.staged = {} def commit(self) -> None: if not self.in_transaction: return # Replay every staged write or tombstone onto committed storage. for key, entry in self.staged.items(): if entry is None: if key in self.data: del self.data[key] else: self.data[key] = entry self.staged = {} self.in_transaction = False def rollback(self) -> None: # Drop all uncommitted changes at once; `self.data` was never modified. self.staged = {} self.in_transaction = FalseTrace Example 1 step by step
Command time in_tx data staged Output ----------------------- ---- ----- ------------------------------------ ---------------------------------- ------- SET("token","v1",2) 0 False {"token":("v1",2)} {} None SET("role","admin",5) 0 False {"token":("v1",2),"role":("admin",5)} {} None TICK() 1 False {"token":("v1",2),"role":("admin",5)} {} None BEGIN() 1 True {"token":("v1",2),"role":("admin",5)} {} None SET("token","v2",4) 1 True {"token":("v1",2),"role":("admin",5)} {"token":("v2",5)} None DELETE("role") 1 True {"token":("v1",2),"role":("admin",5)} {"token":("v2",5),"role":None} None GET("token") 1 True {"token":("v1",2),"role":("admin",5)} {"token":("v2",5),"role":None} "v2" GET("role") 1 True {"token":("v1",2),"role":("admin",5)} {"token":("v2",5),"role":None} None ROLLBACK() 1 False {"token":("v1",2),"role":("admin",5)} {} None GET("role") 1 False {"token":("v1",2),"role":("admin",5)} {} "admin" TICK() 2 False {"token":("v1",2),"role":("admin",5)} {} None GET("token") 2 False {"token":("v1",2),"role":("admin",5)} {} NoneComplete solution
from typing import Any, Dict, List, Optional, Set, Tuple class KVStore: def __init__(self): # Logical clock that advances by 1 only when tick() is called. self.time = 0 # data: committed entries mapping key -> (value, expire_at), e.g. {"a": ("1", 10)}. self.data: Dict[str, Tuple[str, int]] = {} # staged: uncommitted writes mapping key -> (value, expire_at), # or key -> None as a tombstone marking a pending DELETE. self.staged: Dict[str, Optional[Tuple[str, int]]] = {} self.in_transaction = False def tick(self) -> None: self.time += 1 def set(self, key: str, value: str, ttl: int) -> None: # Stamp the absolute expiration time right when SET executes so advancing # the clock never requires updating existing entries. entry = (value, self.time + ttl) if self.in_transaction: self.staged[key] = entry else: self.data[key] = entry def delete(self, key: str) -> None: if self.in_transaction: # Store None as a tombstone so GET knows the key was deleted in this # transaction rather than left untouched. self.staged[key] = None elif key in self.data: del self.data[key] def get(self, key: str) -> Optional[str]: # Check `key in self.staged` (not `.get()`) so a None tombstone or an expired # staged write hides any older committed value in `self.data`. if self.in_transaction and key in self.staged: entry = self.staged[key] else: entry = self.data.get(key) if entry is None: return None value, expire_at = entry # A key set at t with ttl expires at t + ttl, so time >= expire_at means expired. if self.time >= expire_at: return None return value def begin(self) -> None: # Only one transaction may be active at a time; ignore nested BEGIN calls # so pending staged writes are not wiped out. if not self.in_transaction: self.in_transaction = True self.staged = {} def commit(self) -> None: if not self.in_transaction: return # Replay every staged write or tombstone onto committed storage. for key, entry in self.staged.items(): if entry is None: if key in self.data: del self.data[key] else: self.data[key] = entry self.staged = {} self.in_transaction = False def rollback(self) -> None: # Drop all uncommitted changes at once; `self.data` was never modified. self.staged = {} self.in_transaction = False def execute_ttl_key_value_store(operations: List[str], arguments: List[List[object]]) -> List[Optional[str]]: store = KVStore() # results: one output per command (the string/None from GET, or None for mutations). results: List[Optional[str]] = [] for op, args in zip(operations, arguments): if op == "SET": key, value, ttl = args[0], args[1], args[2] store.set(key, value, ttl) results.append(None) elif op == "GET": key = args[0] results.append(store.get(key)) elif op == "DELETE": key = args[0] store.delete(key) results.append(None) elif op == "TICK": store.tick() results.append(None) elif op == "BEGIN": store.begin() results.append(None) elif op == "COMMIT": store.commit() results.append(None) elif op == "ROLLBACK": store.rollback() results.append(None) else: raise ValueError("unknown operation: " + op) return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine keeping a permanent ledger book (data) on your desk and placing a transparent acetate sheet (staged) over it whenever a transaction opens via BEGIN(). While that transaction is active, every new value—or a "DELETED" marker called a tombstone (an explicit placeholder, here None, recording that a key was erased)—is written onto the transparent sheet while the permanent page underneath stays untouched. Whenever GET(key) looks up a key, it inspects the transparent sheet first and looks through to the permanent ledger only when that key has no entry on the sheet. ROLLBACK() throws the sheet away in one motion, whereas COMMIT() copies only the marks on the sheet onto the ledger. For TTL (Time-To-Live) (an automatic lifespan after which an entry stops being valid), SET stamps a fixed deadline time + ttl onto the entry so TICK() merely increments one integer logical clock (a step counter standing in for elapsed time).
Simpler attempts break on performance or correctness. Cloning the entire data map at BEGIN() requires O(n) time and memory even for a two-key transaction. Mutating data directly makes ROLLBACK() impossible without tracking prior state. And storing remaining countdowns instead of fixed deadlines would force every TICK() to iterate over the entire keyspace.
Trace a short sequence from Example 1 to watch the overlay work:
1. At time = 0, SET("token", "v1", 2) and SET("role", "admin", 5) record deadlines 2 and 5 in data; TICK() moves time to 1.
2. BEGIN() opens staged = {}; SET("token", "v2", 4) writes ("v2", 5) to staged and DELETE("role") writes staged["role"] = None.
3. GET("token") sees "v2" (1 < 5) from staged, while GET("role") hits the None tombstone and returns None.
4. ROLLBACK() discards staged, so GET("role") reads "admin" (1 < 5) from data again.
5. One more TICK() advances time to 2, where GET("token") sees 2 >= 2 and returns None.
Complexity
- Time: O(m) total across m commands (
O(1)average per single-key operation).SET,GET,DELETE,TICK,BEGIN, andROLLBACKeach performO(1)average hash-table work.COMMITiterates over thekdistinct keys modified instaged(O(k)), and because each staged entry was produced by an earlierSETorDELETE, total work across allmcommands isO(m)on average. - Space: O(n + k), where
nis the number of committed keys indataandkis the number of keys touched in the active transaction'sstagedmap.
Edge cases
- Exact deadline tick: Writing an entry at
time = 0withttl = 2setsexpire_at = 2; it remains readable attime = 1and expires attime = 2(time >= expire_at). - Expired staged write shadowing a live committed key: When
dataholds"token"expiring at100and an open transaction overwrites"token"withttl = 1and ticks once,GET("token")returnsNonerather than leaking the old committed value, yetROLLBACKrestores theexpire_at = 100entry. - Transactional delete followed by rollback: A
Nonetombstone masks the committed key during the transaction, andROLLBACKdrops the tombstone so the key reappears (Example 1). - Expiration anchored at
SETrather thanCOMMIT: Writing a key attime = 0withttl = 3inside a transaction that commits attime = 1still expires attime = 3, nottime = 4(Example 2). - Deleting an absent key: Safely ignored outside a transaction (
key in self.data) and harmlessly skipped duringCOMMIT. - Repeated
BEGINor strayCOMMIT/ROLLBACK: Ignoring nestedBEGINcalls preserves uncommitted edits, and ignoringCOMMITorROLLBACKwhen idle leavesdatauntouched.
Common mistakes
- Writing
self.staged.get(key) is not Noneinstead ofkey in self.staged: Both an untouched key and aNonedelete tombstone evaluate toNone, causing deleted keys inside a transaction to fall back toself.data! - Checking expiration before picking between
stagedanddata: Falling back todatawhen a staged entry is expired resurrects overwritten data inside the transaction. - Using
>instead of>=for expiration:self.time > expire_atleaves a key alive forttl + 1ticks instead ofttlticks. - Recomputing
self.time + ttlinsideCOMMIT: That artificially extends every staged key's lifespan by the duration of the transaction.
Alternative approaches
- In-place mutation with an undo log: An undo log saves each key's prior
datastate the first time an active transaction touches it. Reads and writes then operate directly ondata,COMMITclears the undo log inO(1), andROLLBACKrestores saved entries inO(k)—a clean fit whenever a single thread owns the store.
Follow-up questions
- If millions of entries carry different expiration times, how would you keep lookups fast and prevent expired keys from exhausting memory? Single-key
GETis alreadyO(1)on average, so the real risk at scale is memory bloat from expired keys that are never queried again. Pair lazy expiration (evicting a key fromself.datawheneverGETseesself.time >= expire_at) with proactive sweeping via a min-heap (a priority queue keeping the earliestexpire_aton top inO(log n)time) or a timing wheel (an array of tick-indexed buckets): on eachTICK, pop and delete keys withexpire_at <= self.time, ignoring stale heap records when a key has since been overwritten with a later deadline. - How would you extend the design so transactions can be nested inside one another and rolled back independently? Nested checkpoints—often called savepoints (named markers inside a transaction to which work can be partially undone)—generalize
self.stagedinto a stack of overlay dictionaries. EachBEGINpushes a fresh{}onto the stack;GETscans overlays from top to bottom before consultingself.data;ROLLBACKpops and discards only the top dictionary inO(1); and an innerCOMMITmerges the top dictionary into its parent overlay below (only the outermostCOMMITflushes intoself.data). - How could you add durable storage so committed entries and their remaining lifespans survive a crash or restart? Before
COMMITacknowledges success, serialize the transaction's staged writes and tombstones as one atomic record into an append-only write-ahead log (WAL) (a sequential disk log written ahead of in-memory acknowledgment) and invokefsync(an OS call flushing kernel buffers onto durable media). Periodically write a compacted snapshot ofself.dataso old WAL segments can be truncated; upon restart, load the latest snapshot, replay trailing WAL records, and persist either the logicaltimecounter or wall-clockexpire_atepochs so remaining lifespans stay accurate.
Follow-up questions
- If millions of entries carry different expiration times, how would you keep lookups fast and prevent expired keys from exhausting memory?
- How would you extend the design so transactions can be nested inside one another and rolled back independently?
- How could you add durable storage so committed entries and their remaining lifespans survive a crash or restart?
Similar questions
- Interactive Geospatial Property Search Service
- 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