Implement an in-memory key-value store with TTL expiration and nested transactions
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design and implement an in-memory key-value store that supports basic `put`, `get` and `delete` operations, where keys may optionally carry a time-to-live (TTL) after which they automatically expire.
The store must also support a transactional layer with `begin`, `commit` and `rollback`. Transactions can be nested: each `begin` opens a new transaction scope, and uncommitted changes made inside a scope are isolated from outer scopes until committed. On `rollback`, all changes made since the most recent `begin` must be reverted.
To make time deterministic for testing, the store exposes a `tick` method that advances a logical clock by a given number of units. Any key whose expiration time is less than or equal to the current logical time is treated as expired and behaves as if it does not exist.
Implement these methods:
- `put(key: str, value: str, ttl: int = 0)` sets the value for `key`. If `ttl > 0`, the key expires `ttl` logical time units after the current clock. A `ttl` of 0 means no expiration. Writes go into the innermost active transaction if one exists.
- `get(key: str) -> Optional[str]` returns the current value of `key`, accounting for pending transactional changes and TTL expiration. It returns `None` if the key does not exist or has expired.
- `delete(key: str) -> bool` deletes `key`. It returns `True` if the key existed and was not expired at the time of deletion, otherwise `False`. It honors the active transaction layer.
- `begin()` opens a new transaction scope. Transactions may be nested.
- `commit() -> bool` commits the innermost active transaction, merging its pending changes into the enclosing scope, or into the base store when it is the outermost transaction. It returns `True` if a transaction was committed and `False` if no transaction was active.
- `rollback() -> bool` discards all pending changes in the innermost active transaction. It returns `True` if a transaction was rolled back and `False` if no transaction was active.
- `tick(units: int)` advances the logical clock by `units`. Keys whose expiration time is less than or equal to the new current time are treated as expired.
A TTL walkthrough:
```text
store = KeyValueStore()
store.put("a", "1", ttl=5) # expires at time 5
store.put("b", "2") # never expires
store.tick(4) # time is 4
store.get("a") -> "1"
store.tick(1) # time is 5
store.get("a") -> None (expiration time 5 <= current time 5)
store.delete("a") -> False (the key had already expired)
store.get("b") -> "2"
```
A nested transaction walkthrough:
```text
store = KeyValueStore()
store.put("x", "10")
store.begin()
store.put("x", "20")
store.begin()
store.delete("x") -> True
store.get("x") -> None
store.rollback() -> True (undoes the delete)
store.get("x") -> "20"
store.commit() -> True (the outer transaction writes "20" to the base store)
store.get("x") -> "20"
store.rollback() -> False (no transaction is active)
```
```hint Cheap rollback
Think about what a rollback has to throw away, and choose a per-transaction representation that makes throwing it away cheap.
```
```hint Deletes inside a transaction
A delete inside a transaction must hide the key from reads even while an outer scope or the base store still holds a value for it. Removing the key from a map cannot express that on its own.
```
```hint Where to store expiration
Decide whether to keep the TTL as given or as a point on the logical clock, and check which choice keeps `tick` cheap.
```
### Constraints & Assumptions
- All keys and values are non-empty strings of length at most 100.
- `0 <= ttl <= 10^9`. A `ttl` of 0 means the key never expires.
- Logical time starts at 0 and only advances through `tick`.
- At most 10,000 operations in total across all methods.
- `commit` and `rollback` change nothing and return `False` when no transaction is active; otherwise they return `True`.
- Transaction nesting depth never exceeds 100.
### Clarifying Questions to Ask
- When a key is written with a TTL inside a transaction, does the TTL start counting at the `put` or at the final commit?
- Is the store used by one caller at a time, or do several clients need their own independent transactions?
- Must expired keys be removed from memory, or is it enough that they read as missing?
- What should `tick` do with zero or negative units?
### What a Strong Answer Covers
- How a read resolves a key across open transaction scopes and the base store, including a key deleted inside a transaction.
- How `commit` and `rollback` behave at every nesting level, and what each costs.
- How expiration is stored and checked so that `tick` stays cheap, including the case where the expiration time equals the current time.
- The return values of `delete`, `commit` and `rollback` for expired keys, missing keys and calls with no active transaction.
- The memory held by expired entries and how to reclaim it without changing what reads return.
### Follow-up Questions
- How would you reclaim memory from expired keys without scanning the whole store on every `tick`?
- How would the design change if several clients ran independent transactions at the same time?
- How would you make committed data survive a process crash?
- Layered pending writes and an undo log are two ways to implement rollback. What does each cost for reads, commits and rollbacks?
Overview: Implement an in-memory key-value store with put, get and delete, per-key time-to-live on a logical clock, and nested begin, commit and rollback. It tests layered transaction state, delete markers that hide older values, expiration checks at the boundary, and the cost of each operation.