Implement an in-memory key-field-value DB with TTL
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
## In-Memory DB with TTL + Scan + Backup/Restore
Implement an in-memory database storing records by `(key, field) -> value` with optional TTL.
### Data model / rules
- `key` and `field` are strings.
- `value` is a string (or integer; choose one and be consistent).
- Each stored `(key, field)` has an expiration time `expire_at`.
- If a value is set without TTL, `expire_at = +∞`.
- A value is **visible** at query time `t` iff `t < expire_at`.
### API
1. `set(key, field, value, timestamp) -> void`
- Store `(value, +∞)`.
2. `set_with_ttl(key, field, value, timestamp, ttl) -> void`
- Store `(value, timestamp + ttl)`.
3. `get(key, field, timestamp) -> value | null`
- Return `null` if missing or expired at `timestamp`.
4. `delete(key, field, timestamp) -> bool`
- Delete the field (regardless of TTL).
- Return `false` if `(key, field)` does not exist; otherwise `true`.
5. `scan(key, timestamp) -> list<(field, value)>`
- Return all non-expired fields for `key` at `timestamp`.
- Sort results by `field` ascending.
6. `scan_with_prefix(key, prefix, timestamp) -> list<(field, value)>`
- Like `scan`, but only include `field`s that start with `prefix`.
7. `backup(timestamp) -> void`
- Persist a full snapshot of the DB state at `timestamp`.
8. `restore(timestamp, restore_to_time) -> void`
- Restore DB state from the **most recent** backup with `backup_time <= restore_to_time`.
- If no such backup exists, restore to an empty DB.
### Notes
- Assume timestamps are integers.
- Assume up to ~1e5 operations; aim for efficient scans and correct TTL handling.
Quick Answer: This question evaluates implementation skills in efficient in-memory data structures, time-to-live (TTL) expiration semantics, ordered and prefix scans, and snapshot backup/restore mechanisms.