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 string key to string value with expiration timestamp time + 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]: resolves key in the current visibility scope (consulting pending transactional edits first when a transaction is open, and permanent storage otherwise). Returns the associated string if key is present and time < expire_at; returns None if key was never written, was deleted in the current scope, or has reached time >= expire_at (note that an expired write inside an open transaction shadows any older committed entry for key until rollback).
  • "DELETE" with [key]: erases key from the current scope (doing nothing if key is absent). Inside an open transaction, key reads as None until the transaction either commits or aborts.
  • "TICK" with []: advances the logical clock time by 1. No other command changes time.
  • "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 original expire_at timestamp) 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; ttl is a positive integer (ttl >= 1).
  • Logical time starts at 0 and only increases via "TICK".

Step-by-step walkthrough

  1. 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 of ttl ticks. GET(key) returns the stored string while time < expire_at, or None once expired or absent.
    • Logical clock: self.time starts at 0 and advances by 1 exclusively on TICK() calls.
    • Single open transaction: between BEGIN() and COMMIT() / ROLLBACK(), mutations (SET and DELETE) affect only the open transaction's view, becoming permanent on COMMIT() or disappearing on ROLLBACK(). 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", None for everything else).

  2. Why cloning the entire map at BEGIN is too slow

    A tempting shortcut for ROLLBACK is copying the entire committed dictionary whenever BEGIN() runs, mutating the copy, swapping it in on COMMIT(), and discarding it on ROLLBACK().

    While functionally right (our test suite uses it as a reference check), cloning costs O(n) time and memory on every BEGIN(), where n is the total number of stored keys. Updating two keys inside a million-key store should take two operations, not a million copies.

  3. Key idea: delta overlay with tombstones and deadline timestamps

    Two lightweight representation choices keep every single-key command O(1) on average:

    1. Record the deadline expire_at = self.time + ttl on write: compute the exact tick at which a key expires the moment SET executes. TICK then stays a single self.time += 1 increment without scanning entries, and COMMIT preserves the original deadline.
    2. Overlay self.staged atop self.data: keep committed entries in self.data and record only keys modified after BEGIN() inside self.staged. To represent a deletion inside a transaction, assign self.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")
    
  4. Code state, TICK, SET, and DELETE

    set and delete write into self.staged whenever self.in_transaction is True, and directly into self.data otherwise. Inside a transaction, delete unconditionally records self.staged[key] = None even when key is absent from self.data, in case an earlier SET in the same transaction staged key!

    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]
    
  5. Code GET: select the visible layer before testing expiry

    Two subtle details in get prevent stale committed values from leaking through:

    • Test membership with key in self.staged, never self.staged.get(key): when key has a None tombstone, .get(key) returns None—indistinguishable from a missing key—which would wrongly fall through to self.data!
    • Evaluate self.time >= expire_at after picking the layer: if "token" is committed with expire_at = 100, and an open transaction overwrites "token" with ttl = 1 (expire_at = 1) followed by TICK(), the transaction's overwrite is now expired and must return None rather than exposing the old expire_at = 100 entry!
    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
    
  6. Code BEGIN, COMMIT, and ROLLBACK

    • begin() opens a clean self.staged = {} workspace only when no transaction is already open.
    • commit() replays every entry of self.staged onto self.data: None tombstones delete keys from self.data, while (value, expire_at) tuples overwrite self.data[key] with their original expire_at.
    • rollback() resets self.staged = {} and self.in_transaction = False in O(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 = False
    
  7. Trace 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)} {}                                  None
    
  8. Complete 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, and ROLLBACK each perform O(1) average hash-table work. COMMIT iterates over the k distinct keys modified in staged (O(k)), and because each staged entry was produced by an earlier SET or DELETE, total work across all m commands is O(m) on average.
  • Space: O(n + k), where n is the number of committed keys in data and k is the number of keys touched in the active transaction's staged map.

Edge cases

  • Exact deadline tick: Writing an entry at time = 0 with ttl = 2 sets expire_at = 2; it remains readable at time = 1 and expires at time = 2 (time >= expire_at).
  • Expired staged write shadowing a live committed key: When data holds "token" expiring at 100 and an open transaction overwrites "token" with ttl = 1 and ticks once, GET("token") returns None rather than leaking the old committed value, yet ROLLBACK restores the expire_at = 100 entry.
  • Transactional delete followed by rollback: A None tombstone masks the committed key during the transaction, and ROLLBACK drops the tombstone so the key reappears (Example 1).
  • Expiration anchored at SET rather than COMMIT: Writing a key at time = 0 with ttl = 3 inside a transaction that commits at time = 1 still expires at time = 3, not time = 4 (Example 2).
  • Deleting an absent key: Safely ignored outside a transaction (key in self.data) and harmlessly skipped during COMMIT.
  • Repeated BEGIN or stray COMMIT / ROLLBACK: Ignoring nested BEGIN calls preserves uncommitted edits, and ignoring COMMIT or ROLLBACK when idle leaves data untouched.

Common mistakes

  • Writing self.staged.get(key) is not None instead of key in self.staged: Both an untouched key and a None delete tombstone evaluate to None, causing deleted keys inside a transaction to fall back to self.data!
  • Checking expiration before picking between staged and data: Falling back to data when a staged entry is expired resurrects overwritten data inside the transaction.
  • Using > instead of >= for expiration: self.time > expire_at leaves a key alive for ttl + 1 ticks instead of ttl ticks.
  • Recomputing self.time + ttl inside COMMIT: 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 data state the first time an active transaction touches it. Reads and writes then operate directly on data, COMMIT clears the undo log in O(1), and ROLLBACK restores saved entries in O(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 GET is already O(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 from self.data whenever GET sees self.time >= expire_at) with proactive sweeping via a min-heap (a priority queue keeping the earliest expire_at on top in O(log n) time) or a timing wheel (an array of tick-indexed buckets): on each TICK, pop and delete keys with expire_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.staged into a stack of overlay dictionaries. Each BEGIN pushes a fresh {} onto the stack; GET scans overlays from top to bottom before consulting self.data; ROLLBACK pops and discards only the top dictionary in O(1); and an inner COMMIT merges the top dictionary into its parent overlay below (only the outermost COMMIT flushes into self.data).
  • How could you add durable storage so committed entries and their remaining lifespans survive a crash or restart? Before COMMIT acknowledges 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 invoke fsync (an OS call flushing kernel buffers onto durable media). Periodically write a compacted snapshot of self.data so old WAL segments can be truncated; upon restart, load the latest snapshot, replay trailing WAL records, and persist either the logical time counter or wall-clock expire_at epochs so remaining lifespans stay accurate.

Follow-up questions

Similar questions

More Opendoor interview questions

All 2 Opendoor questions →