Data layer
Reaktor's data layer covers everything an app stores and moves: local objects, databases, files, graph data, queries, caches, sync, events, live sessions, and what happens to data when it is backed up, archived or deleted. Part of it is code you can use today: one object storage API on every target, browser SQLite, a guard that keeps graph queries inside one tenant, and adapters for Postgres and Cloudflare. The rest is Tidemark, the design for how those pieces become one layer. This page covers both and says which one each part is.
The page starts with the whole picture and a playground for the tenant guard. It then describes the code that exists today, the design part by part, what the design improves on and where it falls short. Background work has its own page, Work, and Hangar's tools for reading every store are described in Data inspection.
Overview#
The organising idea is logical data and its guarantees first, qualified implementations underneath. An app declares what its data is: the entities, which store holds the authoritative copy of each, which copies are derived from it, and what each operation reads or writes. Stores, brokers and live transports are bindings chosen per dataset, each with stated limits. The design follows the concerns of Designing Data-Intensive Applications: reliability, scalability, maintainability, data models, storage, replication, partitioning, transactions, batch and stream processing, and the consequences of partial failure.
The data vocabulary lives in the same graph that holds an app's screens, services and actors. A logical Document can be a Postgres row, an R2 object, Memgraph relationships, a search entry, a vector and a copy on a phone. The data graph ties those representations to the code that reads, writes and derives them. Plans for queries, caches, sync, migrations and deletion come from those declarations, while the mechanisms that carry them out still supply each guarantee.
| Part | What it is | Where it stands |
|---|---|---|
| Object storage | ObjectDatabase and ObjectStore: typed objects under a store and a key, an observable state per key, and a change journal for chosen stores | Built, on Android, iOS, the JVM, the browser and Cloudflare D1 |
| Tenant guard | GraphDb.tenant(id): checks each Cypher query for the tenant and binds it before the query reaches Memgraph | Built, on the JVM |
| Provider adapters | Postgres for JVM services, Cloudflare D1, KV, R2 and Durable Object bindings, Memgraph over Bolt | Built, each as a separate binding |
| Data inspection | Hangar's Data pane reads every provider through JVM adapters and the Workers that own each store | Built |
| Data graph | Entities, datasets, representations, access patterns and lifecycle rules as graph definitions | Designed. The Kotlin specimen compiles |
| Planners and runtimes | The query planner, the sync engine, lifecycle plans and adapter conformance suites | Designed, not built |
Try it#
Every graph query a JVM handler sends for a tenant goes through GraphDb.tenant(id), and the guard reads the Cypher before anything is sent. In every MATCH, each node pattern must carry {tenant_id: $tenant_id}. A read may not contain a write or procedure clause. A transaction must put the tenant on every node it creates or merges, may not set the tenant to anything else, and may not carry another tenant's id inside its parameters. A query that passes runs with $tenant_id bound to the handler's tenant.
The box below is a handler for the tenant acme. Each call starts with read, records or transaction, optionally followed by its parameters as one line of JSON, with the Cypher indented below it. The right side shows each call, the node patterns the guard checked, and either the error the handler would get or the parameters the query would run with. The rules are a port of GraphDbPolicy.kt and the checks GraphDb runs for each call.
Some changes to try:
- Add
{tenant_id: $tenant_id}to(a:Person)in the second call. Both patterns now pass, and the call runs. - Add
"tenant_id": "globex"to the third call's parameters. The call still runs, foracme: the guard binds the handler's tenant over any value at the top level. - In the first call, replace the
RETURNline withSET d.seen = true. The guard refuses it, because a read may not write. - In the third call, remove
tenant_id: $tenant_id,from the pattern. The write is refused, because a new node must carry the tenant.
# The tenant this handler serves
tenant acme
# 1. Reads this tenant's documents
read
MATCH (d:Document {tenant_id: $tenant_id})
RETURN d.title ORDER BY d.title
# 2. Joins authors but forgets their tenant
read
MATCH (d:Document {tenant_id: $tenant_id})<-[:WROTE]-(a:Person)
RETURN d.title, a.name
# 3. Creates a document in this tenant
transaction {"id": "d7", "title": "Roadmap"}
CREATE (d:Document {tenant_id: $tenant_id, id: $id, title: $title})
# 4. Imports rows that name another tenant
transaction {"rows": [{"id": "d8", "tenant_id": "globex"}]}
UNWIND $rows AS row
CREATE (d:Document {tenant_id: $tenant_id, id: row.id})
The guard checks the shapes of Cypher it understands. It does not prove isolation for any query: a procedure, a pattern it cannot parse, or code that uses the driver directly is outside it. Graph access and tenancy lists the exact rules.
What exists today#
This section describes the code as it is. Tidemark, further down, is the design it grows into. Code being present does not mean every target has shipped it or passed the same persistence tests.
Object storage on every target#
reaktor-db provides ObjectDatabase, namespaced ObjectStore, observable ObjectState<T>, StoredObject<T> and encoded RawObject. SqliteObjectDatabase stores JSON payloads under (store_name, key). The same class runs on Android, iOS, the JVM and the browser, each with its own SQLite driver, and D1ObjectDatabase in reaktor-cloudflare provides the same API on D1. Raw export and import can preserve an object without loading its application type. These APIs are the persistence that exists today; they do not implement the proposed cross-store planner.
An ObjectStore owns typed reads, writes, updates, deletes and singleton state handles. It rejects incompatible state types for the same key. Its memory cache and persisted retention policy have different effects: LRU eviction removes a memory entry; expiration can delete persisted data. Choose retention deliberately for user records and pending commands.
The keyed update gate serializes access within that store instance. It is not distributed compare-and-swap, a cross-process lock or an atomic read-modify-write protocol across devices. Concurrent authorities need a provider transaction or version check, or an explicit ownership protocol. Database events identify local, external, sync and migration origins, but emitting an event does not constitute durable cross-device delivery.
Unreadable encoded data must remain distinguishable from a missing object. UnreadableObjectException preserves that distinction so a decoder failure cannot silently turn into a default value and overwrite recoverable bytes. Account switching, retention, reset, migration and backups must preserve this rule.
The change journal#
A database opened with a journal prefix records every insert, update and delete in the stores whose names start with that prefix. SQLite triggers write each change to a <table>_changes table, with an increasing sequence number, inside the transaction that made the change. Raw imports and administrative changes are therefore recorded too, without an outbox in memory. readChanges(store, afterSequence, limit) returns the changes after a sequence, in order. SqliteObjectDatabase and D1ObjectDatabase keep one. Other databases throw UnsupportedOperationException, reading a store outside the prefix fails, and changing the prefix of an existing database needs an explicit storage migration.
WorkStore in reaktor-work builds on it. Each event consumer keeps a cursor, reads the changes after it, and moves the cursor forward with a compare-and-set once it has handled them. inspectHistory reads the same changes as a record's history. The journal records what changed in one database, in order. Merging changes from several writers and resolving conflicts are left to the protocol that reads it, and the sync design describes what such a protocol has to provide.
Where it runs#
| Target | Present source | Qualification boundary |
|---|---|---|
| JVM | SqliteObjectDatabase over JDBC SQLite, which Hangar's runtime opens | File and process ownership, cancellation, transaction behaviour and recovery need tests for each deployment |
| Android | SqliteObjectDatabase over the platform SQLDelight driver, which the BestBuds app opens at start-up | Device lifecycle, migration, process death and account isolation need device evidence |
| iOS | The same class over the native driver, which the BestBuds app opens at start-up | Native lifecycle, migration, protected storage and interruption need device evidence |
| Browser | openWebSqliteObjectDatabase: SQLite in a module Worker on OPFS | Publish the worker and Wasm assets, and qualify supported browsers, reload, tab concurrency, quota, eviction and upgrades before claiming parity |
| Cloudflare | D1ObjectDatabase, with the same journal, and the D1, KV, R2 and Durable Object bindings in reaktor-cloudflare | These are separate bindings; importing reaktor-db does not provide one universal transaction or sync engine |
| JVM services | ExposedAdapter and CrudRepository for Postgres, and GraphDb for Memgraph over Bolt | Separate adapters, each with its own transactions |
The older AndroidSqlAdapter and DarwinSqlAdapter are a different surface from the object database. A driver dependency alone is not evidence that a product uses the whole object-store path.
Browser persistence and legacy migration#
The browser implementation replaces the earlier IndexedDB object backend with SQLite through a dedicated module Worker. The worker uses SQLite's OPFS synchronous-access-handle pool and Web Locks to coordinate access to a database name. It rejects unsupported storage and lock APIs; it does not silently substitute an ephemeral store. Serve the worker and SQLite assets at the URLs used by the factory, and verify that the deployed origin and browser allow these APIs.
The migration imports encoded records from reaktor-objects-<name>, keeps existing SQLite records when keys collide, verifies copied values and records completion in reaktor_web_migrations. That marker is outside the object tables cleared by clearAll, which prevents a later reset from importing the old database again. Legacy IndexedDB bytes remain for recovery. Plan their eventual removal separately, after verifying the upgrade; leaving them indefinitely also has privacy and retention consequences.
OPFS is origin-local browser storage. A successful transaction is not a guarantee against browser eviction or user deletion, and local persistence is not remote backup. Request persistent storage where available, report quota failures, retain acknowledged server versions, and qualify private mode and offline and reconnect behaviour. The sync design describes the proposed authority and convergence requirements.
Graph access and tenancy#
GraphDb.tenant(id) returns a TenantGraphDb for one tenant. Each of its four calls runs a different set of checks before it reaches Memgraph:
| Call | Use it for | Checks before sending |
|---|---|---|
read(cypher, parameters) | Queries that only read. They run in a read session | ReadOnlyGraphQuery, then MandatoryTenantParameterization |
records(cypher, parameters) | Queries whose records you need | MandatoryTenantParameterization |
execute(cypher, parameters) | Statements where only the summary matters | MandatoryTenantParameterization |
transaction(statements) | Several writes that commit together | TenantScopedWrites and its parameter check, then MandatoryTenantParameterization |
MandatoryTenantParameterizationrequires$tenant_idin the query and{tenant_id: $tenant_id}in every node pattern of everyMATCHandOPTIONAL MATCH. It then adds the tenant to the parameters, replacing anytenant_idthe caller passed at the top level.ReadOnlyGraphQueryrefusesCREATE,MERGE,SET,DELETE,REMOVE,DROP,FOREACH,CALLandLOAD CSVoutside strings and comments.TenantScopedWritesrefuses schema statements and procedure calls, and refuses settingtenant_idto anything but$tenant_idor removing it. It requires the tenant on every node that aCREATEorMERGEnames with a label, properties or a parameter. Its parameter check refuses any nested map that carries a differenttenant_id.
A failed check throws InvalidTenantGraphQuery, with the message the playground shows, before a session opens. Registered MemgraphInspection recipes give Hangar bounded operator reads through a separate, authorised inspector path.
These checks are guardrails over the admitted query vocabulary, not a proof of isolation for arbitrary Cypher, procedures or direct driver access. Keep the raw driver out of untrusted handlers, enforce authority at the executor, and test adversarial read and write shapes. A product may make Memgraph its record authority, as Manna does; graph storage is not always a derived cache. Auth describes how the tenant reaches a handler.
Snapshot transfer is not synchronization#
The existing SyncAdapter backs up a SQL database, uploads snapshot bytes over HTTP, downloads bytes and restores a database. It has no general operation journal, conflict resolver, resumable incremental replication, projection watermark or multi-device convergence protocol. Treat it as snapshot transfer and qualify each adapter's backup and restore behaviour. Do not advertise it as Tidemark's offline sync engine.
Product sync implementations can be stronger without establishing a framework-wide guarantee. Manna's record stream and workspace command handling belong to its own authority and revision protocol until they are extracted and qualified as reusable bindings.
Inspecting every store#

Hangar's Data pane reads every provider through native JVM adapters and the Workers that own each store. Every read is bounded, and each result records its scope, so an empty page is never taken as proof that a table is empty. Data inspection describes the pane, its catalogs and the evidence each read returns.
Tidemark: how the design fits together#
Tidemark is the target architecture for Reaktor's data layer, not a platform that ships today. The parts below are proposals unless a sentence says otherwise. The Kotlin contract specimen states the proposed interfaces; it compiles, which checks that the types fit together, not that they behave correctly on every platform. A single journal with one rebase loop and one Durable Object as the authority is one useful deployment profile here, not the limit of the design.
The data graph is the data vocabulary and projection of the main Reaktor graph. It connects logical entities, schemas, datasets, access patterns, operations, derived representations, and lifecycle obligations to actual stores and running components. Data contracts are graph-native definitions with typed descriptors and bindings. Their semantic meaning remains independent of UI and process activation; the same identities drive composition, analysis and tooling. This does not require a second graph-neutral kernel or a separate identity system.
These are selectable components, not a mandatory deployment. A local app can have one SQLite file. A small connected app can use Postgres for relational data, documents, vectors, search, and an outbox. Specialized infrastructure appears when an access pattern, guarantee, placement constraint, or measured bottleneck justifies it.
| Component | Responsibility | Boundary |
|---|---|---|
| Semantic kernel and data vocabulary | Stable identity, schemas, relationships, requirements, revisions | Pure descriptions; declaring data opens no connections |
| Service contracts | Typed operations, interaction protocols, errors, effects | Separate from implementations and transports |
| Data access and planning | Typed queries, mutations, dependency analysis, capability checking, pushdown | Produces an explainable plan; executors perform effects |
| Store adapters | Native transactions, indexes, scans, change capture, physical schema evolution | Preserve or explicitly reject requested semantics |
| Consistency and coordination runtimes | Transaction domains, ownership, conflict handling, fencing, reconciliation | Use database, actor or replication mechanisms appropriate to the workload |
| Sync and materialization | Offline state, replicas, indexes, views, cache updates, checkpoints | Make direction, lag, authority, and rebuildability explicit |
| Bus, work, and workflow runtimes | Durable events, work distribution, retries, timers, multi-step effects | Own durable execution and delivery semantics |
| Mesh and live sessions | Presence, media, ephemeral state, live data transport | Persistence happens through an explicit recording or commit operation |
| Lifecycle and operations | Backup, restore, archive, deletion, encryption, capacity, telemetry | Plans with scoped evidence and execution receipts |
What is unified, and what remains specialized#
Reaktor unifies identity, contracts, composition, policy, planning, and evidence. It does not implement a replacement storage engine, distributed consensus algorithm, universal transaction manager, or media server as part of its semantic kernel. B-trees, LSM trees, MVCC, compaction, WAL, replication protocols, and physical indexes remain backend responsibilities. Their observable consequences, such as range-scan support, isolation, write amplification, recovery behavior and limits, enter adapter profiles and planning.
The kernel is small and immutable. Feature modules contribute an open vocabulary. A data-only consumer must not acquire UI, DI, actor scheduling, or a live graph runtime just to open a local store. The Reaktor Graph paper explored that shared graph as a design study. It will not be built as written; the shared graph follows a later design.
The data graph#
The data graph is the data vocabulary and scoped projection of the main Reaktor graph. It binds different forms of data and their access patterns semantically, and connects them to the logic that reads, changes, derives and distributes them. It is a proposed design: a complete data catalogue, planner, reflector and lifecycle executor do not ship today. It does not introduce another graph or identity authority.
The graph describes both what data means and how the system uses it. A logical Document can have a SQL record, an R2 body, Memgraph relationships, an embedding, a search index entry, an offline projection, and an archival representation. Those objects are connected by explicit mappings and derivations. They are not assumed to be interchangeable copies.
Document.Save, Reindex and Embed are ordinary operation definitions in the main graph, whether implemented in Kotlin, TypeScript, C++, SQL, or an external service. The data view uses their existing IDs. A data lineage edge can therefore connect a UI requirement to a service, an FFI model invocation, and the database fields that determine its output.
The catalogue is a portable projection of definitions, not a requirement to copy every application row into a central graph database. Runtime entity references, sampled lineage, partition instances, and execution evidence are scoped, paginated overlays. Large product graphs can live in Memgraph or another graph store and be queried through the same contracts. Offline clients carry only the definitions and policy scope they need.
What is represented#
A document can be a relational record with JSON fields, a blob, a set of graph relationships, a search entry, a vector, an offline copy and an archive. Its logical identity binds these representations together. Typed edges state whether a representation is authoritative, a partial view, a derived index, a replica, or retained history, and identify the logic and policy that maintain it.
The graph also connects the document to an editor, a Service mutation, a workflow, and an FFI embedding operation. This is how data becomes part of application composition rather than a separate database inventory. It supports planning consistency, querying, caching, sync, migrations and lifecycle flows, provided executable mechanisms enforce the declared contracts.
One semantic graph, modular runtime dependencies#
The pure semantic kernel provides immutable definitions, stable IDs and revisions, typed ports, open vocabularies, references and patches. Data modules contribute descriptors without depending on an activated UI, DI or actor runtime. Data and Service contracts are graph-native semantic definitions. Store and runtime bindings preserve those identities without requiring an activated UI, DI container or actor process to inspect them. This is definition/activation separation, not a requirement to maintain a second graph-neutral kernel.
The data graph belongs to the main graph. The old runtime graph coupled definition to activation, and the shared pure kernel has to remove that coupling; it is not a reason for a separate data graph. No data consumer should inherit the old runtime's dependency weight just to inspect a schema.
Memgraph is a possible store for product graph data and optionally a server-side index of graph projections. It is not a mandatory remote dependency for loading definitions. A phone can open SQLite while offline using a local projection. A large workspace can page and filter its graph; not every runtime downloads the entire catalogue or every data row.
Topology, product data and observations#
The main graph carries three related representations with different owners and access patterns:
| Representation | Contains | Boundary |
|---|---|---|
| Data topology | Dataset, schema, query and operation definitions, authority, bindings, derivation and lifecycle policy | Metadata describes a store; it is not the product rows |
| Product data | Entities, documents and domain relationships in their authoritative and derived stores | Page scoped records through the data API; do not load them all into the graph registry |
| Runtime observations | Query and job runs, attempts, checkpoints, applied positions, failures and execution receipts | Bounded evidence references; observations do not silently rewrite desired definitions |
Executable connections join typed ports according to a protocol, including multi-party hyperedges. Semantic relations assert facts such as reads, derives, owns or replicates. Local facets annotate a subject with retention, residency, authority or execution requirements. A lineage relation does not by itself execute a transform; a connected port does not grant credentials.
Tag assertions by role: normative requirements and desired state, descriptive source and catalog facts, domain product facts, and observational runtime evidence. Each has source and provenance, subject revision, scope, extraction method and freshness. Preserve conflicts for inspection rather than merging all four through last-writer-wins. Definition revisions and observed activation epochs remain separate.
Transform and Work definitions describe behavior; individual runs identify the exact definition and input snapshot or revisions, outputs, attempts and checkpoints. Link these identities for lineage, with W3C PROV and OpenLineage interoperability where useful. The durable execution profile specifies provider admission and effect receipts.
Identity, revisions and evidence#
Use stable dataset, field, query, operation, and entity identities independent of engine, hostname, table name, or cloud account. An entity reference includes its logical dataset, tenant or security namespace, and key. A physical locator such as postgres://cluster/schema/table is a binding, not the entity's identity. Provider credentials remain outside graph snapshots.
Definitions have revisions; deployed bindings have revisions; activations have epochs; data has versions scoped to a consistency domain. Do not collapse these into one version counter. UUIDs identify objects; timestamps help describe time; neither establishes transaction order. A sequence is ordered only within its declared log or partition and epoch. Hybrid logical clocks can assist causal tracking, but do not independently establish cross-database atomicity or a consistent recovery point.
| Identity | Example | Lifetime |
|---|---|---|
| Logical dataset | app.documents | Stable across table renames, engines and clouds |
| Logical field, query or operation | document.owner, documents.visible, Document.Save | Stable definition identity; contract changes carry revisions |
| Entity reference | dataset + tenant namespace + entity key | Same entity across permitted representations |
| Physical binding | deployment + provider + physical locator + revision | Changes when placement or implementation changes |
| Activation | runtime instance + epoch | One running instance or ownership generation |
| Data version | consistency domain + epoch + position or token | Ordered only according to that domain's protocol |
| Evidence | subject + revision + scope + provenance + observation time | Can become stale or invalid after change |
Physical URNs and locators such as SQL table addresses, graph labels or R2 object prefixes are binding attributes. They cannot be logical entity identity: replacing Postgres with TiDB must not rename every document and service dependency. Credentials and authority-bearing tokens are resolved outside portable snapshots. An opaque entity key does not grant access.
Schema IDs include revisioned generic structure, field identities and compatibility rules; language class names and HTTP route strings are insufficient. Canonical graph fingerprints use the kernel's specified normalized representation, including ordering, numeric encoding and schema version. Arbitrary serializer output or unordered JSON maps cannot stand in for canonicalization.
Observed physical schemas, authored desired schemas and inferred relationships remain separate claims. Reflection cannot infer business authority, ownership, merge laws or deletion intent from a foreign key alone. Conflicts, unknown coverage and stale evidence must remain visible.
Coverage and causal progress#
Evidence reports the exact query or window, authority and permissions, returned scope, completeness, source revision or position and observation time. A bounded or permission-filtered query with no rows is not evidence that no rows exist. Confidence or a successful connection does not establish authorization.
A projection proves progress with its source domain, epoch and applied position, or a position vector across sources. A timestamp or HLC alone cannot prove read-your-writes. Federated reads retain each source's position and isolation scope; they do not invent one atomic global cut. Desired bindings, observed placement and evidence can disagree without being silently collapsed.
Nodes and typed ports#
These are extensible vocabulary families, not a permanently sealed list of all possible data systems.
| Definition | Meaning and key facets |
|---|---|
EntityType / Schema / Field | Logical shape, field identity, validation, confidentiality and compatibility |
Dataset / Representation | Collection of logical records and its authoritative, derived or replica role |
AccessPattern / Query / Mutation | Typed inputs and results, predicate, ordering, operators, consistency and cost limits |
StoreBinding | Provider, deployment, locator, family and facets, capabilities, qualification and limits |
ConsistencyDomain | Invariants, write authority, transaction or merge protocol, fencing and read guarantees |
PartitionClass / PlacementPolicy | Routing keys, shards, topology, residency and scaling constraints; not automatically a transaction domain |
SyncView / Materialization | Selection and mapping, source checkpoint, transform revision, refresh and conflict policy |
Topic / Queue / Log / Subscription | Schemas, retention, ordering scope, replay, consumer policy and checkpoints |
LiveSession / MediaTrack | Ephemeral room or stream semantics, participant policy and optional recording dependency |
LifecyclePolicy / SnapshotSet / ArchiveManifest | Required coverage, retention, deletion and recovery conditions, checksums and evidence |
EncryptionDomain / KeyReference | Protection boundary, key provider and version references and permitted compute locations |
Services, actors, workflows, FFI functions, principals, runtimes and deployments use the definitions already present in the main graph. Data does not mint duplicate Process nodes for them. Their read, write, subscribe and publish ports connect to typed data and resource ports. Port payload schemas, interaction protocol and effects participate in compatibility; transport labels are only binding information.
Nested graphs express scope and composition. Multiplex edge families express distinct relationships between the same endpoints: a workflow may read, own, archive and authorize access to a dataset, with different laws on each edge. Data relationships are not reduced to one generic arrow.
Edges carry semantics#
| Edge | Required semantics |
|---|---|
Contains / FieldOf | Structural containment, schema revision; does not automatically imply deletion ownership |
Represents / StoredAs | Logical-to-physical mapping, keys, coverage and representation role |
References / RelatedTo | Key expression, cardinality, direction, integrity and missing-target behavior |
Reads / Writes | Operation, dataset and fields, predicate or conservative scope, authorization, effect and transaction domain |
Derives / Indexes | Transform, model or analyzer revision, input dependency, determinism assumptions, freshness and rebuild policy |
Replicates / Syncs | Source authority, selection, direction, checkpoints, conflict law and resnapshot rules |
Publishes / Subscribes | Event schema, delivery, ordering and retention contract, effect and ack boundary |
Owns / Retains / Archives | Lifecycle rule: restrict, cascade, detach, tombstone or retain, with scope and conditions |
ProtectedBy / AuthorizedBy | Key or authority domain, policy revision, permitted execution and disclosure |
BoundTo / PlacedOn | Qualified implementation, configuration and revision, and runtime placement |
Older Projects and Mirrors names can be aliases for precise materialization and replication relationships during migration. An unqualified “mirror” is insufficient: a full recoverable replica and a lossy search index have different obligations. Symlink-like references must say whether they are aliases, copies or separately authorized external data.
Mappings are typed expression IR where possible, including codecs and key transformations. Native mapping code references a stable operation plus explicit provider requirements and declared dependencies. A string of SQL or an arbitrary lambda does not become analyzable merely by being attached to an edge.
Intra-database and inter-database links#
Inside Postgres, a References edge may compile to a foreign key and join; a relationship in Memgraph may compile to an edge and traversal. The graph records which native mechanism enforces integrity. JSON references and blob pointers may require application-level checks even within one logical model.
Across stores, use typed entity references plus batched lookup, maintained views or a qualified federation plan. No common transaction or snapshot is assumed. Specify referential lag, dangling-reference repair, deletion behavior and authorization at every hop. A result reports relevant source versions and freshness; a “current” result cannot silently combine a week-old graph projection with newly committed SQL records when the contract forbids it.
A worked composition#
This is an illustrative descriptor structure, not an implemented Kotlin DSL:
entity Document@3
identity: (tenant, documentId)
fields: owner, title, bodyRef, permissions
authoritative: documents.sql
representation documents.sql
family: relational; facets: document-json, transaction, changefeed
binding: postgres.primary@12
representation documents.links
family: graph; binding: memgraph.knowledge@4
derives: DocumentCommitted@2 through LinkProjector@5
checkpoint: source-domain/epoch/position
representation documents.embedding
facet: vector; binding: postgres.pgvector@2
derives: bodyRef through Embed@7 using model@2026-08
policy: authorization filter + declared freshness budget
operation SearchDocuments@4
reads: permitted Document, documents.links, documents.embedding
result: DocumentSummary@2
constraints: bounded candidates/batches, tenant isolation, declared freshness
Embed@7 may bind to a synchronous C++ function locally or an asynchronous model service if its call contract allows that choice. Its data dependencies and model revision are unchanged by the implementation location. An end-to-end encrypted body cannot be routed to an untrusted server simply because that server has the required vector capability.
Replacing the Postgres host changes a binding revision and qualification. Moving vectors to another engine adds a materialization or replication boundary if they were previously in the same transaction. The graph makes the new lag and failure mode visible before rollout. It does not classify this as a zero-cost connection-string change.
Planning, execution and invalidation#
Pure visitors inspect a scoped snapshot and return findings, proposed patches or plans. Executors own authority checks, locks and transactions, RPC, storage, and receipts. Follow the main graph's path:
snapshot/query → proposal → typed patch → normalize/validate
→ fingerprinted plan → authority/policy checks → execute → reconcile → receipt
A plan fingerprint includes relevant graph, schema, operation and binding revisions, authority scope and observed preconditions. Revalidate before applying if these changed. Plans can be stored and reviewed without opening a database connection or invoking a workflow. Execution failures do not mutate a static definition into an unqualified “healthy” claim.
| Consumer | Plan produced from graph relationships |
|---|---|
| Query planner | Native pushdown, bounded batch composition, materialization or federation; unsupported findings where necessary |
| Consistency checker | Required invariant domains, transaction and merge mechanisms, fencing and cross-domain workflow boundaries |
| Cache planner | Query and predicate dependency sets, policy- and version-aware keys, invalidation or declared bounded staleness |
| Sync planner | Snapshot and changefeed handoff, view subscription, checkpoints, conflict and repair, permission-removal behavior |
| Migration planner | Impacted operations and native features, schema translation, backfill and change capture, catch-up and cutover |
| Lifecycle planner | Policy-qualified backup, archive and delete closure, ordering, retention blockers, unknown or unreachable copies |
| Placement and cost analysis | Residency constraints, data transfer, hot partitions, resource estimates and attribution |
Invalidation must account for query membership. A new row can change “latest 20 documents” without modifying any previously returned row. A permission change can invalidate an otherwise unchanged result. A new analyzer, model or transform revision can invalidate derived output without a source-row edit. Track these dependencies or conservatively invalidate; do not claim precise incremental maintenance from incomplete observations.
Producers, validation and drift#
Authored schemas and operations declare intent. Introspection reflects database schemas and provider capabilities. Runtime evidence supplies deployments, checkpoints, lag, failures and observed lineage. These producers contribute claims against shared identities with source ownership and reconciliation rules; one producer does not overwrite another's intent.
Build and deploy validation should catch incompatible schemas and ports, unresolved bindings, unsupported capabilities, missing authority, unsafe key mappings, illegal data movement, unbounded fanout, derivation cycles without a defined fixpoint, missing lifecycle coverage and unavailable target bindings. Capability, authority, policy and effect are different checks.
Runtime drift includes removed indexes, changed schemas, unavailable extensions, missed CDC positions, expired credentials and out-of-band writes. There is no universal “degraded mode is never fatal.” If drift invalidates a safety requirement, the affected operation fails closed or becomes unavailable. Independent local reads may continue where their contract remains valid. Tooling reports the exact affected scope and recovery action.
Lifecycle and security#
Graph traversal discovers declared obligations; it does not prove all copies have been discovered. Snapshot manifests record native positions, blob versions and checksums, schema and transform revisions, keys and dependency closure. Coordinated snapshots or replay protocols establish recovery consistency. An HLC alone does not.
A delete plan distinguishes authoritative data, searchable derivatives, broker retention, caches, offline copies, archives and backups. Ownership policy determines cascade, restrict or detach. Execution receipts state completed, pending, retained, unsupported and unknown coverage. Deletion fences prevent old events and backups from republishing erased data. Do not treat dropping a metadata vertex as deleting actual data.
Data graph metadata can itself be sensitive. Apply scoped queries, redaction and permissions to schema names, relationship topology, entity identifiers, samples and runtime evidence. Encryption domains constrain where transforms may see plaintext; key references do not contain secret material. Policy revisions participate in cache and plan validity.
Size, overhead and acceptance#
The design requires no global metadata server on the request path. Compile and cache plans and bindings; retain scoped local projections; load detailed lineage on demand. Avoid one static node per application row or invocation. Large entity graphs, logs and metrics remain in suitable stores and expose qualified queries into the main graph view. Measure actual descriptor size and runtime overhead instead of promising a fixed kilobyte footprint.
Acceptance requires identity parity between direct module use and graph installation, deterministic serialization, typed mapping and port checks, bounded planner output, actual enforcement at runtime boundaries, and crash and recovery tests for the mechanisms consuming plans. Include out-of-band writes, stale schema evidence, tenant revocation, inserted-row cache invalidation, partial backup closure, and interrupted migrations.
The value of this graph is that the same semantic relationships can drive composition and operational plans throughout Reaktor. Its limit is the accuracy of those relationships and the mechanisms implementing them. A useful graph makes missing guarantees explicit before they become production assumptions.
Datastore families and default bindings#
Families organize contracts and deployment choices. Capabilities determine compatibility. A product may implement several families or facets, and two members of one family are not automatically substitutable.
“Default” below means the intended Reaktor choice for that role, not a claim that every extension or adapter is installed. Reaktor currently uses Supabase only as a Postgres host. Supabase Auth, Storage, Realtime, and its other products are not dependencies of this architecture.
| Family or facet | Reaktor alignment | Alternate bindings | Compatibility boundary |
|---|---|---|---|
| Relational, including documents | Postgres; SQLite/SQLDelight locally; D1 for suitable edge SQL. DocumentDb<T> normally stores typed JSON in SQL, with indexed fields promoted as needed. | MySQL, TiDB, CockroachDB, SQL Server; MongoDB through an explicitly selected document adapter | SQL dialect, JSON operations, constraints, transaction isolation, migrations and CDC differ. A document API does not promise arbitrary Mongo operators. |
| Vector facet of relational data | VectorIndex<T> modeled on pgvector; Postgres is the default binding | Pinecone, Qdrant, Milvus, Cloudflare Vectorize, or a vector facet of another store | Dimension, model revision, distance metric, exact or ANN behavior, filtering, updates and read consistency are contractual. Provider-specific features are extra facets. |
| Search facet of relational data | SearchIndex<T> modeled on pg_search: fielded text queries, relevance, filtering and bounded results | Elasticsearch, OpenSearch, Typesense, Meilisearch | Analyzer and tokenizer, query semantics, ranking, pagination, highlighting and aggregation profiles need qualification. Rankings need not be identical. |
| Key-value and structured state | ObjectStore, local cache, Cloudflare KV; DO storage through a stateful service binding | Redis/Valkey, DynamoDB, FoundationDB, RocksDB, LMDB, other embedded KV stores | Key lookup, CAS, multi-key atomicity, TTL, durability, ordering and replication consistency vary. DO execution is an additional coordination capability. |
| Graph | Memgraph through graph services and Bolt | Neo4j; other property-graph adapters when qualified | Traversals, edge identity, query language subset, procedures, constraints and transactions. RDF/SPARQL is a separate optional profile. |
| Columnar / large-scale analytical and wide-column | ClickHouse for analytical serving; Parquet/Iceberg on R2 plus a selected query engine for lake and archive workloads | BigQuery, Snowflake, Redshift, DuckDB, Trino; Cassandra, ScyllaDB, HBase, Bigtable for the wide-column access profile | One family with distinct analytical scan/aggregate and partition-key wide-column profiles. Those profiles do not imply each other. |
| Time-series | A time-series profile on Postgres/TimescaleDB or ClickHouse when suitable; no mandatory extra service | InfluxDB, VictoriaMetrics, Prometheus-compatible stores, other qualified engines | Event time, out-of-order writes, labels and cardinality, retention, rollups, window semantics and late-data policy remain first-class. |
| Object and file | R2 remotely; platform files locally; immutable blobs and manifests | S3, GCS, Azure Blob, MinIO; filesystem adapters | Conditional writes, multipart upload, checksums, range reads, versioning, listing, file/POSIX semantics and retention controls differ. |
| Durable event log | Transactional outbox or change log; Pub/Sub for durable event distribution when selected | Kafka, Redpanda, Pulsar, Kinesis; other replayable logs | Pub/Sub subscriptions and replay are not automatically a Kafka-style indefinitely retained partition log. Retention, ordering, cursors and replay scope must be declared. |
Documents, vectors, and search are independent access interfaces backed by relational storage by default, so using all three does not require three services. Their independence also permits moving an expensive index without changing the authoritative entity model. pgvector supplies exact and approximate similarity search in Postgres; pg_search supplies search-oriented indexing and queries. Both are extensions: deployment must verify host and version support. Postgres native full-text search can be another explicitly selected search profile; it is not silently equivalent to pg_search/BM25.
The combined columnar family is a packaging decision. ClickHouse-style analytical columns and Cassandra-style wide-column partition models solve different access patterns; this distinction is also explained in ClickHouse's storage overview. An aggregate query cannot fall back to an unbounded Cassandra scan merely because both are in the same family.
Queues, ephemeral pubsub, actor coordination, workflows, WebRTC, SFUs, and TURN are data services, not extra database families. Their contracts sit alongside these stores and can be implemented by products that also expose storage.
Profiles instead of a lowest common denominator#
An adapter advertises versioned profiles with explicit limits and scoped evidence: transaction scope and isolation, unique constraints, conditional writes, query operators, changefeeds, consistency, durability, retention, residency, availability and target support. Requirements belong to a dataset or operation, not just to a global database selection.
Binding resolution returns supported, explicitly emulated with a reviewed plan, or unsupported. Emulation includes its additional components, cost, failure modes and semantic limits. No silent downgrade from serializable to eventual, exact to approximate, durable to ephemeral, or transactional CAS to read-then-write.
Extensions remain typed: Elasticsearch aggregations or Pinecone-specific capabilities attach a provider requirement to the calling operation. They do not expand every app's base interface. Such a requirement marks the corresponding portability boundary in the graph.
Specialized temporal and bitemporal, RDF, geospatial, spatial raster, array and scientific, ledger and immutable-audit, vector-model serving, and POSIX filesystem semantics are not all baseline promises. Some can be extension profiles on the families above; others need new vocabulary and adapters. Unsupported is a legitimate result.
Services: one contract, several interaction protocols#
The Service layer already gives the data layer most of what it needs from a contract. Operations are typed, with routes, effects and idempotency. Streams, topics and queues declare their delivery guarantees, a socket carries calls and streams, deadlines travel with each call, and a caller can tell four failure kinds apart, including OutcomeUnknown for a call that may have run. What it does not have yet are durable job handles, duplex sessions beyond sockets, and native calls as a link. The design keeps that one contract concept and adds the missing interaction protocols, while database engines, schedulers, transports and native memory management stay in their own implementations.
A service is a named collection of typed operations. Each operation declares stable identity and revision, input, output and error schemas, interaction protocol, effects, and capability requirements. An implementation supplies behavior; a binding supplies location, transport, lifecycle and an execution policy. These are independent choices only where their contracts allow it.
interface Contract<C> {
val id: Ref
val revision: Revision
val protocol: Ref
val requirements: Set<Requirement>
}
interface Binder {
fun <C> bind(contract: Contract<C>, choice: BindingChoice): BindingResult<C>
}
fun interface SyncCall<I, O, E> {
fun call(input: I, context: CallContext): Outcome<O, E>
}
fun interface AsyncCall<I, O, E> {
suspend fun call(input: I, context: CallContext): Outcome<O, E>
}
fun interface StreamCall<I, O, E> {
suspend fun open(input: I, resume: Cursor?, context: CallContext):
Outcome<Receiver<O, E>, E>
}
fun interface DuplexCall<Open, I, O, E> {
suspend fun open(input: Open, context: CallContext):
Outcome<DuplexSession<I, O, E>, E>
}
fun interface Publisher<T, E> {
suspend fun publish(event: Event<T>, context: CallContext):
Outcome<PublicationReceipt, E>
}
fun interface DurableCall<I, O, E> {
suspend fun submit(input: I, context: CallContext): Outcome<Job<O, E>, E>
}
These are callable interfaces, not merely transport enum values. The complete specimen also defines receivers with bounded demand, senders and half-close, upload completion, subscriptions with ack, retry and dead-letter, job inspection, watch and cancellation, typed outcomes, context, and data interfaces.
App code keeps the shape it has today: declare an operation with by get<In, Out>(…), answer it with handle, and bind a client with over. The descriptor carries enough information to generate clients and graph ports. Most app authors never construct low-level sessions, profiles, or binding plans by hand.
Context, failures, and execution#
Invocation context carries validated authority references, tenant scope, deadline budget, idempotency key, causation and tracing, and optional consistency requirements. Business DTOs do not become mutable bags of HTTP headers or native pointers. The receiver validates authority; possession of a graph ID is not authorization.
An outcome distinguishes a typed domain rejection from a runtime or transport failure, as today's Rejected and OutcomeUnknown already do. The design goes further: a failure also reports whether an effect was not started, applied, partially applied, or unknown. A timeout after committing a payment cannot safely mean “nothing happened.” Accepted publication, committed state, projected state, and device delivery are separate receipts and checkpoints.
Actors are an optional execution policy for serialized state ownership. Pure synchronous functions and native kernels can execute directly. A synchronous contract requires a binding that can actually return synchronously on that target; it cannot be transparently rebound to network RPC in a browser. suspend does not itself allocate a thread, guarantee a nonblocking implementation, or provide durability.
FFI is a Service binding family#
FFI shares Service identity, schemas, effects and interaction protocols. Its binding owns ABI version, codec, target availability, runtime generation, handle ownership, thread affinity, callback lifecycle and reentrancy. Keep those implementation details in reaktor-ffi; do not duplicate the public service concept.
Native sync calls can remain direct, without a mandatory coroutine, actor mailbox, serialization pass, or graph lookup. Borrowed memory is valid only for its declared scope. Async operations require owned or retained buffers until terminal completion, including cancellation acknowledgement. Runtime-scoped handles cannot be sent as raw pointers to remote peers. Process crashes and invalid native memory access are not universally recoverable structured errors. See Unified FFI and RPC.
Data access, intra-store links, and inter-store queries#
A semantic link carries a key mapping, cardinality, direction, integrity policy, authority, visibility rules and version expectations. Within one relational database, it may compile to a foreign key and join. Within a graph database, it may compile to a relationship and traversal. A JSON field, blob reference or search hit can point at the same logical entity without pretending that its storage representation is identical.
A cross-store reference is not a cross-store foreign key. Its contract states how dangling references, deletion, authorization and reconciliation work. An ownership edge may require restrict, cascade, detach, tombstone, or retained-reference behavior; the graph does not infer destructive cascades merely from reachability.
The query layer needs a typed expression and plan IR: selection, projection, stable ordering, pagination, joins, graph traversals, aggregates, text and vector predicates, and explicit native extensions. A plan includes estimated cardinality, pushdown boundaries, credentials and authority scope, consistency requirements, data movement limits, and the evidence behind estimates.
| Execution strategy | Use | Required visibility |
|---|---|---|
| Native pushdown | Join documents to owners in one Postgres transaction or snapshot | Native semantics and index plan |
| Batched composition | Read candidate graph IDs, fetch authorized SQL rows in bounded batches | Batch limits, missing rows, versions, no hidden per-row RPC loop |
| Maintained materialization | Search, vector index, denormalized feed or analytical read model | Source checkpoint, transform revision, lag, rebuild path |
| Qualified federation | Ad hoc cross-store analysis where adapters support it | Transfer and scan budget, snapshot limitations, spill and cancellation |
| Reject or request another plan | Unsupported operators or unacceptable cost or consistency | Concrete missing capability; no silent full scan |
For “search documents linked to this project and show author names,” the planner can push text and vector filtering into Postgres, traverse Memgraph for membership, and batch author reads. At higher scale it can use a maintained membership projection. These plans have different freshness and cost; the chosen contract makes that visible. Cross-store pagination needs a stable plan or snapshot, or a declared best-effort cursor. Approximate vector recall and changed search ranking cannot be disguised as byte-identical results.
Caching tracks queries and their membership predicates, not only rows previously returned. Inserts, deletes, permission changes, relationship changes, schema and transform revisions and embedding-model changes can invalidate a result. Cache identity includes tenant and authority scope, query and parameters, schema and plan revision, and appropriate version tokens. TTL is a bounded-staleness policy, not a proof of consistency. Opaque native SQL or FFI code must declare dependencies conservatively or opt out of automatic optimization.
Transactions, authority, replication, and failure#
A dataset specifies who may accept writes and what invariants must hold. Select a consistency profile per operation and coordination domain:
| Profile | Mechanism | Suitable examples |
|---|---|---|
| Transactional authority | Native DB transaction with required isolation and constraints | Inventory, ledgers, unique names, relational invariants |
| Serialized entity or room authority | DO or actor service plus qualified durable storage and ownership or fencing | Room state, game turn, entity state machine |
| Replicated consensus authority | Backend replication and a qualified client and read protocol | Multi-node durable state with specified availability and consistency |
| Convergent replicated state | A named CRDT or application merge law, causal metadata and repair | Collaborative sets, counters and document structures that satisfy that law |
| Immutable append and derivation | Ordered source log within declared scope plus idempotent transforms | Audit streams, telemetry, analytical views |
One app can use several profiles. A CRDT does not preserve arbitrary business invariants; an actor's local mailbox does not guarantee global single ownership; an HLC is not a consensus protocol. For cross-domain commands use a saga or workflow with explicit intermediate states and compensation, or an actually supported distributed transaction. Do not label a saga atomic.
Separate transaction domains, sync subscriptions, placement and sharding, tenant and security scopes, and retention and erasure groups. They often overlap but need not have the same boundary. For example, an offline dashboard may subscribe to several transactional accounts without making their updates one transaction.
| Failure or pitfall | Required design |
|---|---|
| Commit succeeds but response is lost | Stable idempotency or effect ID, request fingerprint, durable result lookup; retry policy handles unknown outcomes |
| DB commit and event publish split | Outbox in the same transaction as state, or qualified CDC; relay and consumer deduplication |
| Duplicate or reordered delivery | Idempotent projector with checkpoint and version checks; ordering only within declared keys or partitions |
| Stale leader resumes after failover | Fencing token checked by the resource that accepts writes; leases alone are insufficient |
| Network partition | Per-operation availability and consistency behavior; local pending state and explicit rejection or degradation |
| Retry storm or slow consumer | Deadline budget, bounded queues and credits, jitter, retry ownership, DLQ and admission limits |
| Schema or code changes during replay | Versioned events, mutations and transforms, compatible readers, pinned workflow history and a migration plan |
| Unauthorized data survives in cache | Scope-aware keys, revocation handling, local purge and repair, access checks at boundaries |
| Delete followed by old replay or restore | Tombstone or deletion fence plus generation and checkpoint rules applied before serving restored data |
The graph makes dependencies and obligations available to analysis. The mechanism and its conformance evidence supply the guarantee. Out-of-band writers, missing lineage and stale introspection reduce coverage and must appear as unknown or partial.
Sync, offline work, and reactive data#
Sync is a family of protocols over declared datasets and views. A sync contract names source authority, selection predicate, direction, conflict law, schema revisions, checkpoint scheme, authorization, deletion behavior and resnapshot policy. The change journal that exists today is the kind of ordered source a read-replication protocol starts from.
- Read replication: initial snapshot plus ordered changes; appropriate for offline reference data and local read models.
- Optimistic command and rebase: durable client outbox of named commands, speculative local state, authoritative execution, then rebase. Appropriate when replay is deterministic and side effects are separated.
- CRDT or domain merge: selected for data with a proved or qualified merge law; tracks causal metadata and compaction conditions.
- Bulk and batch synchronization: exports, CDC loads, ETL and periodic reconciliation with explicit freshness.
- Live ephemeral state: presence, cursors and game prediction can use a live transport and periodic checkpoints without making every sample durable.
Snapshot and changefeed handoff must avoid gaps. Persist incoming changes and their cursor atomically where the profile requires it. Retain deduplication and tombstones long enough for supported offline and replay windows; an expired cursor requires a resnapshot, not guessed continuation. Subscription changes and permission revocation include removals from the local view, not only newly visible rows.
A rebase transaction must never re-run email, payment, or network side effects while replaying local state. Those effects are named Service operations with durable execution and idempotency where required. Failed business commands stay inspectable; they do not disappear as successful local writes.
Device migration, logout, tenant switching, encryption key rotation and storage pressure are part of the sync lifecycle. Browser persistence is a separate target qualification: an in-memory fallback is not durable SQLite/OPFS support. Reactive UI observes committed or explicitly speculative query results through native Flow and state bindings; cancelling a collection releases its subscription.
Pubsub, queues, streams, and realtime#
Bus is a first-class data-layer responsibility; a particular broker is optional. Publication describes facts and events. A queue distributes work among competing consumers. A retained log supports position-based replay. An ephemeral pubsub channel distributes live notifications. One product can support several, but the semantics must be selected explicitly.
| Role | Reaktor-aligned binding | Contract |
|---|---|---|
| Domain event fanout | GCP Pub/Sub or another qualified broker | Independent subscriptions, delivery and ack rules, ordering scope, retention and replay |
| Background work | Cloudflare Queues, platform work adapters, or another queue | Claim, lease or delivery attempt, bounded retries, idempotent effect, DLQ and redrive |
| Source change stream | Transactional outbox, DB CDC or retained log | Source versions, snapshot handoff, replay horizon and schema |
| Live app channel | WebSocket or WebRTC DataChannel through Mesh | Connection and session scope, ordering and reliability, bounded buffers, reconnect behavior |
| Live media | Cloudflare Realtime SFU or another SFU | Track and session lifecycle, congestion and participant authorization |
| Connectivity relay | Cloudflare TURN or another TURN service | NAT traversal and relay; no application durability or event-log semantics |
GCP Pub/Sub gives subscriptions independent delivery state. Cloudflare Queues uses at-least-once delivery. Applications still need their own effect identity and transaction boundary; broker guarantees do not automatically make database writes or external effects exactly once.
A subscription ack means the subscriber took responsibility according to its processing contract. It does not mean every user device received the event. Keep publication receipts, source commits, projection checkpoints and device cursors separate. CDC row changes and domain events can coexist; they are not necessarily the same schema or business meaning. Large payloads use authorized blob references with retention long enough for replay.
Mesh carries application data as well as audio and video. Cloudflare Realtime DataChannels can relay arbitrary application messages, while TURN provides connectivity relay. Reliable ordered delivery on an established connection is not durable storage across disconnects. Room and signaling services authorize participants and establish sessions; explicit commit and recording services persist durable facts.
A voice note normally becomes an R2 object plus a durable message record. A live call uses media tracks and an SFU, optionally recording to object storage with a declared retention policy. Collaborative cursor movement can be ephemeral; an accepted document edit must follow the document's durable sync contract.
Durable workflows and materialized data#
A durable Service call returns a job handle; the workflow runtime owns history, timers, retries, checkpoints and recovery. Workflow steps invoke typed Service operations and record durable effect identities. Cancellation is a request, not proof that external effects were undone. Versions pin code or supply an explicit compatible migration across suspended executions. Work covers the background work that runs on each platform today.
For an upload: reserve metadata, accept the object, verify the checksum, invoke an FFI or native scanner or transcoder, generate thumbnails and embeddings, publish availability, and expire abandoned uploads. The graph relates each derived representation to its source, transform or model revision and checkpoint. It can identify stale thumbnails after a code change and schedule only affected rebuilds.
Materializations declare source authority, derivation, refresh mode, freshness budget, checkpoint, determinism assumptions and whether replay is sufficient to rebuild them. “Derived” does not mean disposable: external model output may be costly or nondeterministic, upstream logs may expire, and captured user events may be irreplaceable. Back up what cannot reliably be reconstructed.
Batch and streaming execution share logical transforms where semantics agree. Streaming additionally needs event-time versus processing-time rules, watermarks, late events, retractions and upserts, deduplication and bounded state. Backfills use separate epochs and checkpoints, run under resource budgets, and catch up before a versioned cutover. Kleppmann's data-infrastructure discussion motivates explicit logs and derived views rather than uncoordinated dual writes.
Cloudflare delivery and durable execution#
Use Queues and Workflows as the canonical provider profile: durable intent and outbox relay, at-least-once and reordered commands, effect deduplication, Queue-to-Workflow handoff, checkpointed steps, waits, cancellation and lifecycle. These compose with the dataset's existing authority; neither a Queue nor a Workflow becomes the record store. CompanyOS has an existing Workflow skeleton, while shared Reaktor executors remain proposed. A run receipt and an applied source position establish different kinds of progress.
Backup, restore, archival, deletion, and encryption#
Lifecycle plans traverse typed lifecycle relationships with policy, not every reachable graph edge. They account for authoritative records, blobs, replicas, derived indexes, caches, outboxes, broker retention, local devices and backups. A backup, an archive, and a replica have different purposes; none automatically substitutes for the others.
| Operation | How the graph helps | What the runtime must do |
|---|---|---|
| Backup | Discover required representations, schemas, keys and dependency order | Capture native snapshots and log positions, checksums, manifests and encryption metadata; verify restorability |
| Restore | Reconstruct dependencies and identify rebuildable indexes | Restore into an isolated epoch, reconcile checkpoints, apply deletion fences, rebuild and catch up, validate before routing traffic |
| Archive | Select closed or cold data and known consumers | Produce versioned immutable exports, preserve schema and provenance, verify reads before deleting hot copies |
| Delete | Find declared copies, references and derived content | Execute policy-specific purge, redaction or detach, collect receipts, report retained, unknown or unreachable copies |
| Key rotation | Locate datasets and derivatives in each encryption domain | Rewrap or re-encrypt, migrate readers, track key versions and prove completion before retiring keys |
A cross-store SnapshotSet manifest records each store's snapshot or log position, relevant schema, transform and binding revisions, blob versions and checksums, dependency closure and key references. A shared timestamp or HLC alone is insufficient. To claim application-consistent recovery, use coordinated barriers or quiescence, or a log and checkpoint scheme that produces a causally valid cut. Otherwise label the backup crash-consistent or individually consistent and document reconciliation and potential loss. Declare RPO and RTO and test recovery against them.
Archival can use Parquet/Iceberg on R2, or another object or lake binding. An analytical serving engine such as ClickHouse is selected for query latency, concurrency and cost. No single engine, zero-cost floor, or dataset-size threshold is universal. Restoring old data must not resurrect deleted accounts; a protected deletion ledger or fence must outlive relevant backups and replay windows.
Encryption has distinct profiles: transport encryption, server-side encryption at rest, application field and blob encryption, and end-to-end encryption. The graph carries key references and protection domains, never plaintext secrets. It can reject an untrusted server transform over end-to-end encrypted plaintext or route a permitted transform to a trusted client or runtime. Search and embeddings of encrypted data need an explicit trust and leakage model; ordinary server-side indexes do not work over opaque ciphertext.
Deleting a key only achieves the intended cryptographic erasure if all relevant copies, key backups, caches, exports and derivatives fall within that verified key boundary. Offline devices and unmanaged exports may be unreachable. Reports distinguish completed, pending, retained-by-policy, unsupported and unknown; traversal coverage is not a universal erasure or compliance proof.
Portability and changing infrastructure#
The graph protects application meaning and dependency structure from changes in physical placement. It cannot erase differences in database behavior. Portability has several levels:
| Change | Expected disruption | What must be qualified |
|---|---|---|
| Supabase-hosted Postgres → RDS, another managed Postgres, or self-hosted Postgres | Usually primarily binding and operations work | Extension and version availability, privileges, connection pooling, networking, backups, CDC, failover and performance; no Supabase product migration is implied |
| Postgres → TiDB | Logical entities and portable operations can survive; SQL, schema and affected features may change | TiDB is MySQL-compatible, not Postgres-compatible. Rewrite native SQL, JSON, DDL and type mappings and replace unavailable extension-backed facets. |
| Memgraph → Neo4j | Shared property-graph contracts can survive | Cypher subset, procedures, indexes and constraints, identifiers, transactions and measured query behavior |
| pgvector/pg_search → dedicated vector and search engines | Authoritative entities and callers of the qualified facet remain stable | New derivations and CDC, freshness, ranking and recall, filters, pagination, tenant isolation, index rebuild and rollout |
| Durable Object → Redis/Valkey plus compute | Potentially a runtime redesign behind the same stateful Service | Storage alone does not replace actor ownership, placement, alarms, WebSockets or failure fencing. Compose and qualify the missing runtime components. |
| ClickHouse → Elasticsearch | Some bounded event filtering and aggregation workloads may map | Query semantics, joins, precision, scan and concurrency limits, freshness and cost; general OLAP replacement is not guaranteed |
| Cloudflare and GCP services → AWS equivalents | Services and data contracts can remain stable where profiles match | Map storage, compute, coordination, pubsub and queues, workflows, realtime, identity and secrets, observability and egress separately |
TiDB's compatibility documentation and Memgraph's Cypher comparison make these distinctions concrete. Sharing SQL or Bolt is useful, but it is not a complete substitution proof.
A migration plan inventories consumers and native dependencies, compares required profiles, translates schema and query plans, backfills, captures ongoing changes, validates canonical data and query behavior, catches up to a checkpoint, and cuts over a binding revision. Avoid uncoordinated application dual writes. Rollback needs a data-compatibility and reverse-change plan once the new backend accepts writes; changing a connection string back is not sufficient.
For a Cloudflare-to-AWS migration, an R2 binding might become S3, a queue binding SQS, a fanout binding SNS or EventBridge with appropriate queue or log composition, and a service implementation Lambda or a container. A DO room authority may need compute plus a transactional store and ownership mechanism, and Mesh may need a different SFU or TURN provider. Those are candidate compositions, not certified one-to-one replacements. Placement and residency checks include logs, backups, caches, replicas and telemetry, not just the primary database.
Application scenarios#
The following are design scenarios, not reports of implemented features.
| Application | Composition | What the data layer contributes |
|---|---|---|
| Personal notes or local creative tool | SQLite documents + files + reactive queries; optional sync | Same logical document model works offline without brokers, remote graph services or distributed scheduling |
| Multi-tenant SaaS or CRM | Postgres relational/JSON, pg_search, object attachments, transactional outbox | Shared tenancy and authorization across queries, files, caches and events; indexes can move independently later |
| Team knowledge and AI workspace | SQL documents, Memgraph links, vector and search facets, FFI model service, R2 sources | Trace an answer or index hit to its source and model revision; permission-aware retrieval; invalidate and rebuild affected derivatives |
| Chat, multiplayer or collaborative editor | Durable messages and state, explicit merge or authority profile, local sync, Mesh presence and media | Different durability for cursor samples, game state, messages and recordings; reconnect and replay without treating SFU delivery as persistence |
| Commerce or booking | Transactional inventory and accounting, order workflow, event projections | Protect invariants inside the actual transaction domain; idempotent payment effects and visible compensation and reconciliation |
| Offline field or industrial app | Device database, scoped replication, sensor time-series, object evidence | Pending-versus-accepted state, bounded offline window, key and tenant lifecycle, reconnect repair, explicit conflict handling |
| Analytics and telemetry platform | Ingest log or queue, stream and batch transforms, ClickHouse, object archive | Late-event policy, backfill epochs, lineage, retention, resource budgets and reproducible rollups |
| Media and AI processing pipeline | Object upload, durable jobs, native or FFI execution, generated assets and indexes | Shared service contracts connect compute to data; resumable effects, bounded progress streams and lifecycle dependency planning |
For example, a CRM starts with customers and JSON notes in Postgres. Search and vectors stay in that database. Later, a recommendation feature uses Memgraph and a vector index. The existing Customer identity remains stable; new projections declare their source and lag. Deleting a customer can now plan removal from notes, attachments, recommendations, caches and indexes. That improves completeness only to the extent those dependencies are declared or observed.
A second example is a booking timeout: the database may have committed even though the client received no reply. The operation's idempotency key locates the prior result, and the outbox still delivers the booking event. A late projector uses source version checks; the UI can request at least the booking's commit token or display a pending projection. The graph connects these mechanisms; it does not replace any of them.
Overhead, cost, and scaling#
There is no fixed $5/month architecture and no measured performance advantage claimed here. A static contract and a direct local binding can be very small. Distributed coordination, extra indexes, cross-store queries and retained history have real cost regardless of the abstraction used.
| Source of overhead | Control |
|---|---|
| Metadata and code generation | Ship scoped definitions; intern IDs; compile and cache plans by revision; load optional modules only when used |
| Invocation | Resolve bindings outside hot loops; direct sync calls where qualified; avoid forced actor, coroutine or serialization hops |
| Query planning and federation | Native pushdown, prepared plans, bounded batches, explainable transfer and scan budgets; materialize only when justified |
| Write amplification | Every outbox, replica, index and archive is an explicit write and storage cost; avoid indexing every representation by default |
| Consistency and coordination | Pay for synchronous coordination only inside required domains; expose latency and availability consequences |
| Sync and recovery | Bound logs, pending work and replay windows; compact only after safety conditions; budget rebuild and backfill capacity |
| Operations | Account for adapter upgrades, conformance tests, schema evolution, debugging and incident ownership |
Scaling evolves the bindings and plans while retaining logical identity:
- Local: one process, SQLite and files, direct Service and FFI calls.
- Small connected: Postgres with JSON, vector and search as needed, object storage, minimal work and outbox processing; use edge storage where its profile fits.
- Growing: add read models and replicas, broker-backed fanout, partitioned work, cache tiers and selected analytical and graph engines after measuring bottlenecks.
- Large or multi-region: partition by access and coordination requirements, isolate hot tenants and keys, choose regional write ownership or a qualified replicated backend, and govern cross-region movement and recovery.
The graph stores partitioning and routing intent; runtime directories, placement controllers and databases execute it. Repartitioning requires backfill, routing epochs and fencing, checkpoint catch-up, and a cutover protocol. A single hot key cannot be solved merely by adding partitions. Broad transactions and cross-shard joins remain coordination and data-movement costs. Avoid a global graph lookup or catalogue service on every request; distributed applications use revisioned local projections and controlled refresh.
Measure p50, p95 and p99 latency, throughput, allocations, CPU, memory, connection use, scanned and transferred bytes, index growth, write amplification, replication and projector lag, queue age, replay duration, RPO and RTO, and cost per workload and tenant. Compare identical workloads, consistency, data volume and concurrency against direct native adapters. Include cold start, slow consumers, skew, outages and recovery. No performance or savings claim becomes a fact before that evidence exists.
What it improves#
| Usual approach | What goes wrong | Reaktor's approach |
|---|---|---|
| Each store reached through its own library: an ORM for SQL, a driver for the graph, a client for search, an SDK for the broker | Tenancy, retries, cache invalidation and deletion are rewritten for each integration, and nothing can list which code depends on which store. | Today, one object storage API runs on every target, and graph queries for a tenant go through one guarded entry point. In the design, the data graph names each dataset, its copies and the operations that use them, so tools can list those dependencies. |
| Tenant filters written by hand in every query | One query that forgets its tenant filter reads another tenant's rows, and only code review can catch it. | Today, the tenant guard refuses a graph query whose patterns do not carry the tenant, and binds the tenant itself. |
| Write to the database, then publish the event | A crash between the two loses the event or sends it twice, and consumers drift from the data. | Today, the change journal records each change inside the transaction that made it. The design adds an outbox in the same transaction, or change capture, with idempotent consumers. |
| Caches that expire after a fixed time | A cached list misses a new row, and a revoked user keeps reading cached data until it expires. | The design tracks which queries a change affects, puts the tenant and permissions into cache keys, and treats a fixed expiry as a stated staleness budget. |
| Deletion by script | The script misses search indexes, caches, replicas, exports and backups, and restoring an old backup brings deleted accounts back. | The design plans deletion from declared lifecycle relationships, keeps a deletion fence that every restore respects, and reports the copies it could not reach as unknown. |
| Swapping a database by changing its connection string | Differences in SQL dialect, isolation, extensions and failure behaviour appear in production. | The design records each dataset's requirements and native dependencies, so a swap is checked first and runs as a migration with backfill, catch-up and cutover. |
| Browser storage with a silent fallback to memory | Data looks saved, then disappears on reload in a browser that lacks the storage it needs. | Today, browser SQLite runs on OPFS in a Worker and refuses to open where those APIs are missing, instead of falling back to memory. |
Against a conventional stack#
| Dimension | Reaktor design | Conventional application stack |
|---|---|---|
| Composition | Common typed identities connect logic, data, deployment and lifecycle | Teams often connect ORM, broker, cache, jobs and telemetry through separate conventions |
| Portability | Requirements and native dependencies can be inspected before a swap | Drivers and ORMs may abstract common operations; semantic dependencies often remain in app code |
| Distributed correctness | Shared vocabulary enables reusable checks, failure tests and execution plans | Mature specialist tools offer strong mechanisms, but integration correctness remains application work |
| Performance | Cross-component context can enable pushdown, batching and targeted invalidation | Direct integrations have fewer framework layers and mature engine-specific tuning |
| Complexity | More work in framework contracts, adapters, planner and qualification; fewer repeated integration decisions for apps if done well | Less custom framework to maintain; more repeated glue and separate operational models |
| Adoption and debugging | Requires accurate declarations, transparent plans and strong escape hatches | Familiar ecosystem, hiring, libraries and vendor tooling; fewer Reaktor-specific concepts |
The strongest benefit is semantic continuity across an application's components. The strongest risk is creating a distributed platform whose abstractions promise more than its runtimes can enforce. Prefer small orthogonal contracts and explicit plans over a giant “universal database” interface. Keep native access available, recording the resulting requirements and unknown dependencies. Reaktor is worthwhile when shared composition and lifecycle knowledge repay the framework and adapter maintenance cost.
Limitations#
- Most of this page is a design. The code that exists is the object storage API and its journal, browser SQLite, the tenant guard, snapshot transfer, the Postgres and Cloudflare adapters and Hangar's Data pane. The data graph, query planner, sync engine, lifecycle plans and conformance suites are designs, and none of them is claimed to behave as described until it passes its gate.
- The tenant guard checks the shape of a query. It does not prove isolation for arbitrary Cypher, procedures or code that uses the driver directly, and only
transactionchecks nested parameters. - The object store's update gate is local. It serialises updates within one store instance. It is not a distributed lock or compare-and-swap.
- Snapshot transfer is not sync.
SyncAdaptercopies a whole database; it does not merge changes from two devices. - Browser storage can be lost. OPFS belongs to one origin, and the browser or the user can clear it.
- The change journal covers chosen stores on SQLite and D1. Other databases throw, and a journal's prefix cannot change without a storage migration.
- The data graph is only as accurate as its declarations. Writers outside the graph, missing lineage and stale introspection reduce coverage, which the design reports as unknown rather than guessing.
- There are no performance or cost figures yet. The design claims none until it is measured against direct native adapters on the same workload.
- The playground is a model. It ports the rules of
GraphDbPolicy.ktand the checksGraphDbruns for each call. It does not run Memgraph, and the Kotlin remains the source of truth.
Acceptance gates#
Implementation follows one real vertical path before it generalises; the sequence is driven by capabilities rather than a fixed schedule. The gates cover semantic identity, Service protocols, store conformance, transactional intent, duplicates and recovery, sync, lifecycle, inspection and qualified provider changes.
A support claim names the exact adapter or provider version, target, operation or profile, configuration, test revision and scope. “Designed,” “source-observed,” “tested,” “measured,” “stale,” “partial,” and “unknown” remain distinct. A compiled interface is a useful starting artifact; it is not an implemented runtime.
Reference#
| Repository area | Holds |
|---|---|
reaktor-db/.../ObjectDatabase.kt | ObjectDatabase, ObjectChange and readChanges |
reaktor-db/.../core/ObjectStore.kt, ObjectState.kt, ObjectCache.kt, RetentionPolicy.kt | Object operations, events, cache and state coordination, decoding and retention |
reaktor-db/.../core/JsonSqliteObjectDatabase.kt, ObjectJournalSchema.kt | SqliteObjectDatabase, and the change journal's tables and triggers |
reaktor-db/src/jvmMain/.../core/SqliteObjectDatabase.kt | createSqliteObjectDatabase over JDBC |
reaktor-db/src/jsMain/.../WebSqliteObjectDatabase.kt, src/jsMain/resources/reaktor-sqlite-worker.mjs | Browser SQLite, OPFS coordination and the IndexedDB import |
reaktor-db/.../graph/GraphDbPolicy.kt, JVM graph/GraphDb.kt | The tenant guard's three policies, and Bolt access |
reaktor-db/.../adapters/SyncAdapter.kt | Whole-database snapshot transfer |
reaktor-db/src/jvmMain/.../service/ExposedAdapter.kt, CrudRepository.kt | Postgres through Exposed |
reaktor-cloudflare/.../D1ObjectDatabase.kt | The object database on D1, next to the other Cloudflare bindings |
reaktor-cloud/.../memgraph/MemgraphInspection.kt | The bounded Memgraph reads that Hangar's Data pane uses |
MandatoryTenantParameterizationTest in reaktor-db covers the shapes the guard accepts and refuses. The Kotlin contract specimen states the design's interfaces.
The implementation boundaries span reaktor-service (contracts, links, serving and interceptors), reaktor-ffi (InteropRuntime and its synchronous JSON bridge), and reaktor-db (object storage and JVM graph access). The current graph adapter's raw Cypher and driver types and the proposed Service-to-FFI binding still need migration. Existing HTTP and mobile interop paths do not establish unified protocol or data portability.
- Work covers background work on each platform and its durable records.
- Data inspection covers Hangar's Data pane and the evidence each read returns.
- Service covers contracts, links, failures and contract nodes in the graph.
- Unified FFI and RPC covers native calls and the proposed Service bindings.
- Auth covers apps, tenants and how a tenant reaches a handler.
- Deployment covers where an app runs in production and how each part is deployed, and Observe and diagnose which tool holds which signal.