Skip to content
Preptima
hardCodingDesignMidSeniorStaff

Build an in-memory key-value store with per-key TTL, plus a snapshot operation that gives a consistent copy while writes keep coming in.

Expire keys lazily on read and actively with a background sweep, both through the write path. For a consistent snapshot of a key-value store, copying the live map is not enough: take a brief cut, have each writer save a key's old value before changing it, and merge those saved values into the scan.

6 min readUpdated 2026-10-10

Answer

Short answer

An in-memory key-value store with TTL keeps an absolute expiry deadline per key. It expires keys lazily when a read finds them stale, and actively with a background sweep so unread keys do not leak memory. A consistent snapshot cannot just iterate the live map, because a weakly consistent iterator mixes values from before and after concurrent writes. Take a brief cut, then have each writer save a key's old value before its first change during the snapshot. The scan reads the live map, prefers the saved copy where one exists, and so returns exactly the state at the cut.

Was this answer helpful?

Likely follow-ups

  • Why does the snapshot keep a key that was lazily expired halfway through the scan?
  • Snapshots here run one at a time. What would you change to let two run concurrently, and what does each extra one cost writers?
  • How does fork-based copy-on-write get the same guarantee without any code in the writers?
  • The snapshot is written to disk and reloaded after a restart. Do you store the remaining TTL or the deadline?

Related questions

Related Topics