Blog

Stateful CRUD Is Just a Redis Hash, and That's the Point

September 5, 2026Xerat022 min read
Share

MockBase can behave like a real backend — POST to create, GET to list, PATCH to update, DELETE to remove — persisting state across requests instead of returning the same canned JSON every time. Under the hood, that entire feature is a Redis hash. No queue, no separate state machine, no ORM.

The whole implementation, roughly

Every stateful collection lives at one Redis key: state:{mock_id}:{path}. Each item in that collection is a field in the hash, keyed by its id, with the item's JSON serialized as the value:

  • CreateHSET state:{mock_id}:{path} {item_id} {json}
  • Read oneHGET state:{mock_id}:{path} {item_id}
  • List allHGETALL state:{mock_id}:{path}, then deserialize every value
  • Update → read the existing item, merge the new fields into it, HSET it back
  • DeleteHDEL state:{mock_id}:{path} {item_id}

That's four Redis commands covering the entire CRUD surface. Update is a read-modify-write rather than a partial-field Redis operation — MockBase pulls the current JSON out, merges your patch into it in Python, and writes the whole object back. That's what lets PATCH behave like a real partial update (only the fields you send change) without needing per-field Redis keys.

Why a hash, not a set of keys per item

Storing each item at its own Redis key (state:{mock_id}:{path}:{item_id}) would work too, but listing the collection would mean a SCAN with a prefix match — slower and non-atomic. A single hash makes "list everything in this collection" a single HGETALL, and it keeps the whole collection's memory footprint under one key, which matters when you're running many mocks' worth of state through the same Redis instance.

What this design does not give you

There's no schema, no validation, no relations between collections, and no query language beyond "all items" or "one item by id" — you don't get filtering, sorting, or pagination on the stateful store itself. It's deliberately the simplest thing that makes a mock feel stateful across a request sequence: create a resource, read it back, update it, watch it disappear after delete. For scripting a realistic multi-step flow against a mock — sign up, then fetch the profile you just created — that's the whole job.

X

Xerat02

Building MockBase.