Implement an in-memory key-field-value DB with TTL
MetaSoftware Engineer · Online AssessmentLast updated
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.
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
keyandfieldare strings.valueis a string (or integer; choose one and be consistent).- Each stored
(key, field)has an expiration timeexpire_at. - If a value is set without TTL,
expire_at = +∞. - A value is visible at query time
tifft < expire_at.
API
set(key, field, value, timestamp) -> void
- Store
(value, +∞).
set_with_ttl(key, field, value, timestamp, ttl) -> void
- Store
(value, timestamp + ttl).
get(key, field, timestamp) -> value | null
- Return
nullif missing or expired attimestamp.
delete(key, field, timestamp) -> bool
- Delete the field (regardless of TTL).
- Return
falseif(key, field)does not exist; otherwisetrue.
scan(key, timestamp) -> list<(field, value)>
- Return all non-expired fields for
keyattimestamp. - Sort results by
fieldascending.
scan_with_prefix(key, prefix, timestamp) -> list<(field, value)>
- Like
scan, but only includefields that start withprefix.
backup(timestamp) -> void
- Persist a full snapshot of the DB state at
timestamp.
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.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.