Katkat

Implement an in-memory key-field-value DB with TTL

MetaSoftware Engineer · Online Assessment

Last 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

  • 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, +∞).
  1. set_with_ttl(key, field, value, timestamp, ttl) -> void
  • Store (value, timestamp + ttl).
  1. get(key, field, timestamp) -> value | null
  • Return null if missing or expired at timestamp.
  1. delete(key, field, timestamp) -> bool
  • Delete the field (regardless of TTL).
  • Return false if (key, field) does not exist; otherwise true.
  1. scan(key, timestamp) -> list<(field, value)>
  • Return all non-expired fields for key at timestamp.
  • Sort results by field ascending.
  1. scan_with_prefix(key, prefix, timestamp) -> list<(field, value)>
  • Like scan, but only include fields that start with prefix.
  1. backup(timestamp) -> void
  • Persist a full snapshot of the DB state at timestamp.
  1. 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.