AlgoViz

Design a key-value store with transactions

medium 75 min

Build an in-memory store with SET, GET, DELETE, COUNT and nested transactions: layers that hold only changes, a mark for wiped keys, counts that roll back, and then several sessions, snapshots and a log.

Watch lesson4:54

Where it shows up

The same pattern appears across everyday software.

  • Redis MULTI and WATCH

    Commands are queued and run together. `WATCH` makes `EXEC` fail if a watched key was changed: the check at commit. Redis does not support rollback of commands that ran, and its documentation says why: simplicity and speed.

  • SQLite savepoints

    `SAVEPOINT` starts a named transaction that may be nested. `ROLLBACK TO` goes back to a name, `RELEASE` of an inner one only removes it from the stack. Layers with names.

  • PostgreSQL subtransactions

    Subtransactions start inside a transaction and break large work into smaller parts that can be rolled back alone.

  • LevelDB WriteBatch and snapshots

    A batch holds a sequence of edits and applies them as one. A snapshot gives a consistent read-only view of the whole store.

  • RocksDB transactions

    Offers pessimistic and optimistic transactions with begin, commit and rollback, and save points for partial rollback.

  • Python ChainMap

    `collections.ChainMap` links several maps into one view. The list is searched from first to last, and writes go to the first map: our read, in the standard library. It has no mark for wiped keys.

  • Clojure refs

    Software transactional memory with several versions: inside a transaction all reads of refs see a consistent snapshot.

  • etcd

    Every key has a `mod_revision`, the revision of its last change. Transactions can compare such numbers before they write: versions, not values.

  • IndexedDB in the browser

    Reads and writes happen in transactions. A request that fails aborts its transaction by default, and the changes are reverted.