The Space Between Redis and Kafka: Why I Built a Document Cache with Per-Leaf Versioning

2026-11-24来源 dev.toEnglish

Picture a garage with two sensors. One reports temperature, the other humidity. A dashboard wants to show "the garage" as a single object with the latest reading of each, and it wants to be told when either one changes. Let's think of the dashboard as a device that presents a document you pass to it; what it shows is the latest version of the document, no deltas.

A traditional way of solving this is: something to validate what arrives, something to merge what several producers send into one document, something to remember how each value changed, and something to push the result to whoever is interested. The way I put all this together is called TamaDB. It is open source under Apache 2.0, and this post explains the three decisions that make it behave differently from the tools I used to assemble it from.

A caveat before the details. The text herein is limited to TamaDB Increment 1 capabilities. This is Increment 1: a TypeScript reference implementation built to prove the architecture, with a Rust rewrite planned for production. I list what it does not do yet near the end, and I would rather you read that section than find out by trying.

The gap

Redis, Kafka and MongoDB are all good at what they were built for. This is not a complaint about any of them. It is about what is left for you to build when your problem is "several producers, one document, current state for consumers".

  • Redis stores values. It does not validate a value against a schema, and it does not keep a per-field history. Pub/Sub does push, but only to clients that are connected at that moment, and nothing is stored. Streams keep messages, but delivery and retries are your code.
  • Kafka is a log of events. A compacted topic keeps the latest record per key, but it replaces the whole value rather than merging the fields two producers sent. Schema enforcement is typically added with a separate registry.
  • MongoDB stores documents and can update parts of them. Its change streams are something your application subscribes to, so a process you write opens the stream and does the delivery: the HTTP callbacks, the retries, and what each consumer is allowed to see. Atlas triggers run on the same mechanism, but what they run is a function you write.

None of this is hard in isolation. The cost is that the rules (what counts as valid, what a second producer's write means, who finds out) end up spread across a validator, a consumer and some glue code, written differently each time.

TamaDB puts those rules in one place. It sits between producers and consumers in what is sometimes called a smart-endpoints, dumb-pipes architecture. Producers and consumers hold the logic. The thing in the middle only receives, validates, merges, versions and delivers. It does not compute, aggregate or interpret what the data means, and it does not keep anything forever: documents expire. It is a cache, not an archive.

One run, start to finish

Here is the garage where we want to measure some basic indoor environmental quality metrics (EIQ) making use of two sensors, one providing temperature and another one humidity; both sensors sends the updated attribute and its value; the temperature sensor adds unit of measurement (UoM). We are to make use of the concerned TamaDB APIs. I ran every command below against a local instance and pasted the actual responses (long ones are trimmed).

First a schema that represents what to be shared with consumers. The identityKind annotation marks which field identifies the document:

curl -X POST http://localhost:3000/api/v1/schemas -H "Content-Type: application/json" -d '{ "ref": "garageEiq-v1", "schema": { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "location": { "type": "string", "identityKind": "primary-key" }, "temperature": { "type": "number" }, "tempUoM": { "type": "string" }, "humidity": { "type": "number" }, "humidityUoM": { "type": "string" } }, "required": ["location"] } }' 

Then we create a document type that uses it in the strict, closed model, and one ingestion channel per producer. A channel can enrich what arrives, because the humidity sensor can only send the humidity:

curl -X POST http://localhost:3000/api/v1/config/document-types -H "Content-Type: application/json" \ -d '{ "name": "garageEiq-doc", "masterSchema": "garageEiq-v1", "model": "closed", "ttl": 3600 }' curl -X POST http://localhost:3000/api/v1/config/channels -H "Content-Type: application/json" \ -d '{ "channelId": "garage-humidity", "documentType": "garageEiq-doc" }' curl -X PUT http://localhost:3000/api/v1/config/channels/garage-humidity/enrichment -H "Content-Type: application/json" \ -d '{ "bindings": [ { "fieldPath": "location", "staticValue": "Garage" }, { "fieldPath": "humidityUoM", "staticValue": " % RH" } ] }' 

(A second channel, garage-temp, is set up in a similar way for the temperature sensor enriching with location only.) Finally, a consumer subscribes to the whole document with a callback URL:

curl -X POST http://localhost:3000/api/v1/subscriptions -H "Content-Type: application/json" -d '{ "scope": "document_type", "documentType": "garageEiq-doc", "callbackUrl": "http://127.0.0.1:3992/hook", "options": { "deliveryMode": "retry" } }' 

Now the producers write. Each one sends only what it knows:

# producer A (temperature) curl -X POST http://localhost:3000/api/v1/ingest/temperature-readings/garage-temp \ -H "Content-Type: application/json" -d '{ "temperature": 18.2, "tempUoM": "C" }' # {"dId":"Garage","versionNo":1,"created":true} # producer B (humidity) curl -X POST http://localhost:3000/api/v1/ingest/temperature-readings/garage-humidity \ -H "Content-Type: application/json" -d '{ "humidity": 61 }' # {"dId":"Garage","versionNo":2,"created":false} # producer A again curl -X POST http://localhost:3000/api/v1/ingest/temperature-readings/garage-temp \ -H "Content-Type: application/json" -d '{ "temperature": 19.1, "tempUoM": "C" }' # {"dId":"Garage","versionNo":3,"created":false} 

There is one document, Garage, and its version went from 1 to 3. Reading it back:

curl http://localhost:3000/api/v1/documents/temperature-readings/Garage 
{ "temperature": 19.1, "tempUoM": "C", "location": "Garage", "humidity": 61, "humidityUoM": "% RH" } 

Producer A's second write did not erase producer B's humidity. This aspect is the most relevant of the design, so the next three sections take it apart.

NOTE: TamaDB channels are optional; TamaDB accepts direct ingestion (Document_Type-level).

Decision 1: a store can only merge

In TamaDB there is exactly one operation that writes document content, and it means "create this document if it is new, otherwise merge what I sent into it". There is no replace. Fields you send are updated, fields you do not send are left alone, and nothing is ever removed by a store.

I made it structural instead of a convention because of the multi-producer case. If producers can replace documents, they have to coordinate, or one of them will eventually overwrite another's fields with a stale copy. When a store can only merge, producers that own different fields cannot damage each other, and they do not need to know the others exist.

The trade-offs are real. You cannot delete a field through a write. Arrays are replaced whole, because element-level updates are not in Increment 1. And if two producers concurrently write the same field, the last write wins, unless one of them sends the version it expects in a TamaDB-Version header, in which case a stale write is rejected with a VERSION_CONFLICT instead of silently applied.

Decision 2: every leaf has its own version

TamaDB treats a document as a tree, and every terminal value (a leaf) carries its own version number and its own bounded history of previous values. The document has a version too, which is what the versionNo in the responses above is. The leaves are separate.

After the runs above I wrote eight more temperature readings and looked at what is stored. This is read from the on-disk file, not from an API, and it is only here to show the model:

field current value field version previous values kept
temperature 23.5 10 21, 21.5, 22, 22.5, 23
tempUoM C 10 5 values
humidity 61 1 none
humidityUoM % RH 1 none

The document is at version 11, but humidity is still at version 1, because only the humidity sensor ever stored it. The temperature has been stored ten times and keeps the last five previous values, then evicts the oldest. The default depth is five.

I wanted the unit of change to be the field because that is what producers actually own. A document-level version tells you that something changed. A field-level one tells you which producer's data moved.

I should be plain about the current state of this. Increment 1 records the per-field history but its REST API returns only current values, so you cannot read the history back yet, and the depth is fixed at five rather than configurable. The storage model is in place and the access to it is not. I think it is better to ship the model honestly than to claim a feature I cannot show you.

Decision 3: push the current state, captured when it happened

When a write lands, TamaDB sends the subscribed consumer a webhook. Here is the second delivery from the run, the one triggered by the humidity-only write:

POST /hook Content-Type: application/json TamaDB-Subscription-Id: sub-mwpkvodb-0001 TamaDB-Document-Type: garageEiq-doc TamaDB-D-Id: Garage TamaDB-Enqueued-At: 2026-11-20T22:56:09.532Z {"temperature":18.2,"tempUoM":"C","location":"Garage","humidity":61,"humidityUoM":"% RH"} 

Three things in that delivery are deliberate.

The body is the whole current document, not the change. The humidity sensor sent one field. The consumer received the merged state, with the temperature in it. In other words, the consumer receives the latest state of the document and so able to discard any preivous version. A consumer never has to rebuild state from a stream of events, and a consumer that joins late is not at a disadvantage on the next write.

NOTE: TamaDB Increment 2 is to support discrete leaf updates to consumers.

The body is only the document. TamaDB's own context (which subscription, which document, when) travels in TamaDB-* headers, so the consumer does not have to know TamaDB exists to read its data. A subscription can ask for an envelope instead, for consumers that prefer a self-contained body.

The payload is captured when the write happens. TamaDB formats the delivery at enqueue time. If the document is updated again, or expires, before the delivery goes out, the delivery that was already queued is unchanged.

Delivery is best-effort, and I want that stated here and not discovered later. A subscription chooses fire-and-forget (one attempt) or retry (up to five attempts with exponential backoff, then the notification is dropped and a warning is logged). The delivery queue lives in memory, so a delivery that is queued or mid-retry when TamaDB restarts is lost and is not replayed. Your subscriptions themselves are persisted. TamaDB is a transmission cache and not a durable broker. A broker downstream, e.g. PamaDB, would provide guaranteed delivery if needed.

There is one more consequence of keeping TamaDB out of the business of interpreting data. I sent the same temperature a second time, 19.1 again, and a webhook still fired. TamaDB does not compare old and new values and decide whether a write "really" changed anything. Deciding what counts as a change is the consumer's job.

Saying no

Producers send bad data. With the closed model, a document that does not match the schema is rejected, and unknown fields are rejected too:

curl -X POST http://localhost:3000/api/v1/ingest/temperature-readings/garage-temp \ -H "Content-Type: application/json" -d '{ "temperature": "warm" }' 
{ "code": "SCHEMA_VALIDATION_FAILED", "message": "/temperature: must be number", "quarantineRef": "qr-mwpkvog4-0001" } 

Sending {"temperature": 20.0, "voltage": 3.3} fails the same way, with Field 'voltage' is not defined in the schema (DCM: no extensions allowed). Neither rejected write produced a webhook: four accepted writes, four deliveries. Consumers only ever see valid documents.

The rejected payload is not thrown away. It goes to a quarantine that you can list, with the reason and where it came from:

{ "ref": "qr-mwpkvog4-0001", "payload": { "temperature": "warm" }, "context": { "receivedAt": "2026-11-20T22:56:09.604Z", "sourceIdentifier": "garage-temp", "schemaRef": "garageEiq-v1", "rejectionReason": "/temperature: must be number", "rejectionType": "validation-failure", "controlHeaders": {} } } 

When a producer starts sending something unexpected, you can see exactly what it sent.

What happens inside one write

Every ingest runs the same nine steps: parse, enrich, extract the document identity, validate, merge, version, register the TTL, match subscriptions, and snapshot and enqueue the deliveries. I think of them in three groups, which the overview video also uses.

  • The Receiving Bay is inbound and driven by the producer: parse, enrich, extract the identity, validate.
  • The Hold is state, kept in custody and never interpreted: merge, version, history, TTL, lifecycle.
  • The Dispatch Bay is outbound and driven by the consumer: match subscriptions, format and shape the payload, enqueue the delivery.

Documents expire. A TTL can be set for the whole instance, per document type, or per document, and the most specific one wins. The clock is a sliding window anchored to the last update, so a document that keeps receiving writes stays alive and one that goes quiet expires. Reading it does not extend its life, because a cache that every read keeps alive turns into a database.

Not a broker

A broker says "here is what happened". TamaDB says "here is what the document currently look like".

That is the real distinction, and it is why the two are complementary. A broker can sit upstream, carrying messages from your devices into TamaDB, and TamaDB sits between it and your consumers: validated, merged, versioned, delivered. I would not use TamaDB where I need an event history or guaranteed delivery. I would use it where consumers need the current state of something several producers contribute to or where discrete parts of a major document is consumed by multiple consumers, each one dedciding its own subpart.

How it is tested

The suite has 596 tests. Most are ordinary example-based tests, and I want to be accurate about the rest: there are ten property-based assertions, written with fast-check, covering round-trips (parse a document, print it, parse it again, and expect the same tree; the same for schemas) and invariants such as "version numbers stay consistent with the number of updates" and "the timestamp list only grows". I would not call the merge or TTL behaviour property-tested.

TypeScript was a deliberate choice for this phase. The goal of Increment 1 is to prove that the pipeline model, the merge semantics and the API contract are right, and TypeScript made that fast. The design is defined at the interface level, so it does not depend on the language, and a Rust rewrite is planned for production.

What it does not do yet

  • No authentication or TLS. Every endpoint, including the admin shutdown, is open to anyone who can reach the port, and the server listens on all interfaces by default. Run it on localhost or behind a reverse proxy. The security policy lists the known limits.
  • Best-effort delivery. Described above: in-memory queue, bounded retries, nothing replayed after a restart.
  • Field history is not readable over the API, and its depth is not configurable yet.
  • Only the strict model. A hybrid model (validated core, extensions allowed) and a fully open model are planned for later increments.
  • Arrays are replaced whole, and a re-sent value still counts as a write.

Try it

docker run --rm -p 127.0.0.1:3000:3000 teneriscc/tamadb:0.7.1 curl http://localhost:3000/health 

The user manual walks through everything above step by step. The repository is at github.com/teneriscc/TamaDB, the project site is tamadb.cc, and the API reference covers every endpoint.

If you run pipelines where several producers contribute to the same thing, I would like to know where this would break for you. What is the first limit you would hit, and what would you need to see before trying it on a real workload? Tell me in the discussions.

This was a very simple scenario to capture the basic idea. More complex and real-case scenarios are to come, e.g. UN/CEFACT Recommendation No. 24 (Rec. 24), purchase invoices, etc.

The more deeper we get into matters the more important is to understand how to mentally operate at document level.

Disclosure: I drafted this article with AI assistance from the project's repository and from real runs of TamaDB 0.7.1 (the output pasted above), then edited and checked it myself.

原文:https://www.a8q9.cn/en/article/the-space-between-redis-and-kafka-why-i-built-a-document-cache-with-per-leaf-ver-81c775.html

相关文章