← Questions

Persistent key-value store with binary snapshots

0
OpenAICodingLast asked Oct 2026

Implement an in-memory key-value store whose whole state can be saved to, and restored from, a storage medium that holds a single binary blob.

You are given:

class Medium:
    def save(self, blob: bytes) -> None: ...
    def load(self) -> bytes | None: ...   # None if nothing was saved yet

class InMemoryMedium(Medium): ...        # a working implementation for tests

Implement PersistentKVStore(medium) with:

  • put(key: str, value: str) -> None inserts or overwrites.
  • get(key: str) -> str | None
  • delete(key: str) -> bool returns whether the key existed.
  • save() -> None writes the entire current state to the medium as one bytes blob.
  • restore() -> None replaces the in-memory state with what the medium holds.

Rules:

  • Keys and values are arbitrary strings: they may be empty and may contain any character, including =, ,, :, newlines, NUL and non-ASCII text.
  • Design your own byte format. Do not use json, pickle, or similar libraries.
  • A store created on the same medium after a "restart" must see exactly the data from the last save().
  • If the blob is malformed or truncated, restore() must raise and must not leave the store half-loaded.

Example 1

m = InMemoryMedium()
a = PersistentKVStore(m)
a.put("user:1", "Ada")
a.put("note", "line one\nline two")
a.save()
b = PersistentKVStore(m)
b.restore()
b.get("note")    -> "line one\nline two"
b.get("user:2")  -> None

Example 2

a.put("", "empty key is fine")
a.put("city", "Zürich")
a.save()
a.put("draft", "not saved")
a.restore()
a.get("")       -> "empty key is fine"
a.get("draft")  -> None

Expect follow-ups such as a medium with a maximum blob size, writing an append-only log instead of a full snapshot, and thread safety.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding