Interview conceptCoding & Algorithms

In-Memory Key-Value Stores With TTL

Asked of: Software Engineer

Last updated

Editorial node diagram showing nested key-field maps, absolute TTL expiry, timestamped version history, lazy reads, and deep-copy snapshot restore.

What's being tested

These problems test designing an in-memory key–field–value store with deterministic TTL expiration, historical reads, ordered/prefix scans, and snapshot/restore semantics. You must choose data structures that separate current state from version history while preserving clear time-complexity guarantees and atomic compare-and-set/delete behavior.

Patterns & templates

  • Nested hash maps — db[key][field] gives expected O(1) current reads and writes; store value, write timestamp, and absolute expiry together.
  • Absolute expiration timestamps — compute expires_at = now + ttl; treat an entry as expired when read_time >= expires_at, including boundary behavior explicitly.
  • Lazy expiration — remove expired records during get, scan, and history; avoid background cleanup unless requirements demand memory reclamation guarantees.
  • Version history — maintain timestamp-ordered records per key-field; binary search the latest version with timestamp <= read_time, typically O(log V).
  • Ordered and prefix scans — sort visible fields lexicographically, filter prefixes, and define whether expired entries are excluded before or after ordering.
  • Snapshot/restore — deep-copy mutable state or serialize immutable records; preserve TTL as remaining duration or recompute from absolute timestamps consistently.
  • Atomic conditional mutation — evaluate existence, value, and expiration in one operation; compare-and-set must not observe stale expired data.

Common pitfalls

Pitfall: Treating TTL as a periodic deletion requirement; unless specified, lazy expiration is simpler, but every read path must enforce it.

Pitfall: Returning the newest version instead of the newest version valid at the requested timestamp, especially when a later delete or expiry exists.

Pitfall: Shallow-copying nested maps during backup, allowing later writes to mutate the snapshot and making restore incorrect.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts