Design an In-Memory Key-Value Database with TTL Expiry and Prefix Scan

Quick Overview

Implement an in-memory key-value database with a per-key time-to-live and a prefix scan that returns live keys in sorted order. It tests careful handling of the expiry boundary, lazy versus eager cleanup of expired entries, and the choice of data structure for fast prefix queries.

Design an In-Memory Key-Value Database with TTL Expiry and Prefix Scan

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design an in-memory key-value database that stores entries with an optional time-to-live (TTL) in seconds. Every operation receives a `timestamp` giving the current time at which it runs. A key is expired once the current `timestamp` is strictly greater than its expiration time, where the expiration time is the set timestamp plus the TTL. Expired keys must be invisible to `get`, `delete` and `scan`. The database must also support efficient prefix scanning: return every non-expired key that starts with a given prefix, together with its value, sorted lexicographically by key. Implement these methods: - `set(key: str, value: str, ttl: int, timestamp: int) -> None`: store a `key -> value` pair. If `ttl > 0`, the entry expires at `timestamp + ttl`. A `ttl` of `0` means the entry never expires. Overwrites any existing entry for the same key. - `get(key: str, timestamp: int) -> Optional[str]`: return the value for `key` if it exists and has not expired at the current `timestamp`. Otherwise return `None`. - `delete(key: str, timestamp: int) -> bool`: delete an active (non-expired) `key`. Return `True` if a key was deleted, or `False` if the key was absent or already expired. - `scan(prefix: str, timestamp: int) -> List[List[str]]`: return all non-expired `[key, value]` pairs whose key starts with `prefix`, sorted lexicographically by key. ```hint Never-expiring keys Choose what to store for `ttl = 0` so that a single comparison decides expiry for every key. ``` ```hint When to clean up Expired entries can stay in memory until an operation touches them, as long as no method ever returns them. Think about what that choice costs `scan` and memory. ``` ### Examples Example 1: ```text set("apple", "red", 5, 1) -> None get("apple", 6) -> "red" get("apple", 7) -> None delete("apple", 7) -> False set("apple", "green", 0, 8) -> None get("apple", 1000000) -> "green" ``` The first `set` gives an expiration time of 1 + 5 = 6. At timestamp 6 the key is still visible because 6 is not greater than 6. At 7 it has expired, so `get` returns `None` and `delete` has nothing to remove. The second `set` uses `ttl = 0`, so the new value never expires. Example 2: ```text set("app", "1", 0, 0) -> None set("apple", "2", 3, 0) -> None set("apricot", "3", 10, 1) -> None set("banana", "4", 0, 1) -> None scan("ap", 2) -> [["app", "1"], ["apple", "2"], ["apricot", "3"]] scan("ap", 4) -> [["app", "1"], ["apricot", "3"]] delete("app", 5) -> True scan("app", 5) -> [] ``` "apple" expires at 3, so it appears in the scan at timestamp 2 and is gone at 4. "app" sorts before "apple" because it is a prefix of it. After "app" is deleted, no live key starts with "app": "apricot" starts with "apr", and "apple" has expired. ### Constraints & Assumptions - `1 <= len(key), len(prefix) <= 100` - `key` and `prefix` consist of lowercase English letters and digits. - `1 <= len(value) <= 100` - `0 <= timestamp <= 10⁹` - `1 <= ttl <= 10⁹`, or `ttl = 0` to indicate no expiration. - Timestamps across operations are non-decreasing. - At most `10⁴` operations are performed. ### What a Strong Answer Covers - The storage layout for each entry's value and absolute expiration time, including how `ttl = 0` is represented. - The exact expiry boundary, applied the same way in `get`, `delete` and `scan`. - Return values for missing or expired keys, and what an overwriting `set` does to the old TTL. - A `scan` that filters by prefix, skips expired entries and returns pairs in sorted key order, with its time complexity stated. - When expired entries are physically removed from memory, and what that choice costs. ### Follow-up Questions - How would you make `scan` run in about $O(\log n + k)$ time when it returns $k$ keys? - Many keys are written with short TTLs and never read again. How do you keep memory bounded? - What breaks if timestamps can arrive out of order? - How would you make the database safe to call from several threads at once?

Overview: Implement an in-memory key-value database with a per-key time-to-live and a prefix scan that returns live keys in sorted order. It tests careful handling of the expiry boundary, lazy versus eager cleanup of expired entries, and the choice of data structure for fast prefix queries.

Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design an in-memory key-value database that stores entries with an optional time-to-live (TTL) in seconds. Every operation receives a timestamp giving the current time at which it runs.

A key is expired once the current timestamp is strictly greater than its expiration time, where the expiration time is the set timestamp plus the TTL. Expired keys must be invisible to get, delete and scan.

The database must also support efficient prefix scanning: return every non-expired key that starts with a given prefix, together with its value, sorted lexicographically by key.

Implement these methods:

  • set(key: str, value: str, ttl: int, timestamp: int) -> None : store a key -> value pair. If ttl > 0 , the entry expires at timestamp + ttl . A ttl of 0 means the entry never expires. Overwrites any existing entry for the same key.
  • get(key: str, timestamp: int) -> Optional[str] : return the value for key if it exists and has not expired at the current timestamp . Otherwise return None .
  • delete(key: str, timestamp: int) -> bool : delete an active (non-expired) key . Return True if a key was deleted, or False if the key was absent or already expired.
  • scan(prefix: str, timestamp: int) -> List[List[str]] : return all non-expired [key, value] pairs whose key starts with prefix , sorted lexicographically by key.

Examples

Example 1:

set("apple", "red", 5, 1)       -> None
get("apple", 6)                 -> "red"
get("apple", 7)                 -> None
delete("apple", 7)              -> False
set("apple", "green", 0, 8)     -> None
get("apple", 1000000)           -> "green"

The first set gives an expiration time of 1 + 5 = 6. At timestamp 6 the key is still visible because 6 is not greater than 6. At 7 it has expired, so get returns None and delete has nothing to remove. The second set uses ttl = 0, so the new value never expires.

Example 2:

set("app", "1", 0, 0)           -> None
set("apple", "2", 3, 0)         -> None
set("apricot", "3", 10, 1)      -> None
set("banana", "4", 0, 1)        -> None
scan("ap", 2)                   -> [["app", "1"], ["apple", "2"], ["apricot", "3"]]
scan("ap", 4)                   -> [["app", "1"], ["apricot", "3"]]
delete("app", 5)                -> True
scan("app", 5)                  -> []

"apple" expires at 3, so it appears in the scan at timestamp 2 and is gone at 4. "app" sorts before "apple" because it is a prefix of it. After "app" is deleted, no live key starts with "app": "apricot" starts with "apr", and "apple" has expired.

Constraints & Assumptions

  • 1 <= len(key), len(prefix) <= 100
  • key and prefix consist of lowercase English letters and digits.
  • 1 <= len(value) <= 100
  • 0 <= timestamp <= 10⁹
  • 1 <= ttl <= 10⁹ , or ttl = 0 to indicate no expiration.
  • Timestamps across operations are non-decreasing.
  • At most 10⁴ operations are performed.

What a Strong Answer Covers Guidance

  • The storage layout for each entry's value and absolute expiration time, including how ttl = 0 is represented.
  • The exact expiry boundary, applied the same way in get , delete and scan .
  • Return values for missing or expired keys, and what an overwriting set does to the old TTL.
  • A scan that filters by prefix, skips expired entries and returns pairs in sorted key order, with its time complexity stated.
  • When expired entries are physically removed from memory, and what that choice costs.

Follow-up Questions Guidance

  • How would you make scan run in about O(log⁡n+k)O(\log n + k) time when it returns kk keys?
  • Many keys are written with short TTLs and never read again. How do you keep memory bounded?
  • What breaks if timestamps can arrive out of order?
  • How would you make the database safe to call from several threads at once?