Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API Reference

Three ways to talk to a rhypedb-server: the HTTP API, the rhypedb-cli tool, and the binary TCP protocol. All three execute the same query language.

HTTP API

Base URL defaults to http://127.0.0.1:4200.

Data plane (open)

POST /query

Execute a query or mutation.

Request:

{ "query": "User.get(1)" }
{ "query": "User.get(1).update({ name: \"Ann\" })", "origin": "9001" }
{ "transaction": [ { "op": "create", "type": "Label", "fields": { "name": "inbox" } } ] }

Give either query (any statement, including a transaction { ... } block) or transaction, a write transaction as a JSON op list; both, or neither, is a 400. The request body is limited to 2 MiB (413 beyond it). A response sent before the server has read the whole request body, such as that 413, carries Connection: close. The server keeps reading and discarding the rest of the body for up to 5 seconds or 8 MiB, so a client that writes its whole body before reading still gets the status; past those bounds the connection is reset.

origin is optional: a write origin to stamp on the change events of every write the query performs. It is a decimal string (any unsigned 64-bit value, written without sign, spaces or leading zeros), the same form the change-event payload uses, so it survives a JavaScript client past 2⁵³. A JSON number, or any other malformed value, is refused with 400 and the query is not run. Omit it (or send null) for an untagged query.

Responses (200 OK), depending on the query:

Query kindBody
Returns many objects{ "objects": [ <object>, ... ] }
Ordered page (.order_by){ "objects": [ <object>, ... ], "next_cursor": "…" }; next_cursor only when more rows follow
Returns one object{ "object": <object> }
Mutation with no return (update/delete){ "ok": true }
A transaction (block or op list){ "transaction": { "version": "<decimal>", "results": [ ... ] } }

Each <object> is { "type": …, "id": …, "fields": { … } }:

{ "object": { "type": "User", "id": 1, "fields": { "name": "Alice", "age": 30 } } }

A ranked query (.matches, .similar) returns objects in rank order, each with an extra "score" member — BM25 relevance for .matches (higher is better), the index distance for .similar (lower is closer, always). A .similar row the server's cross-encoder scored also carries "rerank_score" (higher is better); rows are then ordered by it. See Ranked results.

{ "objects": [ { "type": "Post", "id": 7, "fields": { "title": "Invoice 4471" }, "score": 2.31 } ] }
{ "objects": [ { "type": "Post", "id": 7, "fields": { "body": "…" }, "score": 0.18, "rerank_score": 4.72 } ] }

id is a JSON number (an unsigned 64-bit id). Treat it as opaque — ids above 2⁵³ can lose precision in clients that parse JSON numbers as doubles. See Object identity.

Errors: { "error": "message" } with a status that says whose problem it is. Only 5xx means the server is at fault; every mistake in the query is a 4xx.

StatusMeaningExamples
400The query is malformed, or names something the schema doesn't have. Fix the query.A syntax error; an unknown type, field or function; a wrongly typed value; .matches on a field without @fulltext; malformed full-text query text.
400The query is valid but too expensive: a query governor limit, or a full-text prefix that expands to more than 64 terms. Narrow the query; retrying it unchanged fails again.query resource limit exceeded: …; prefix term "c*" matches more than 64 indexed terms; use a longer prefix.
403A security rule denied a write.permission denied: …
404An object addressed by id does not exist.object not found: User:9
409The query is valid but the current data refuses it. Resolve that, or retry a write conflict.A @unique violation; a delete denied by a reference; a write conflict with a concurrent transaction; a transaction guard that rejected its object.
503The server can't serve this right now. Retry later.The embedding model is still loading; a @fulltext index is still being built; the server is shutting down.
500A fault on the server: storage, I/O, on-disk corruption, or a bug.storage error: …; full-text index corrupt …
curl -s http://127.0.0.1:4200/query \
  -H 'content-type: application/json' \
  -d '{"query":"User.filter(.age > 18).limit(10)"}'

GET /health

Liveness check. 200 OK with a short status string.

GET /status

Operational snapshot. subscriptions is the total change-feed subscriptions (in-process + network); network_subscriptions is the binary-protocol subset; events_dropped is the cumulative count of change events dropped to slow subscribers (each paired with a SubLagged push — see Subscriptions).

{
  "subscriptions": 2,
  "network_subscriptions": 2,
  "events_dropped": 0,
  "vectorizer": { "pending": 0, "indexes": [ { "name": "Post.embedding", "vectors": 12000 } ] }
}

GET /head

The head version: the latest committed version, the number every change event carries as version. A decimal string, like the event payload's, so the full 64-bit range survives a JavaScript JSON.parse. "0" means nothing has been committed yet.

{ "version": "1042" }

It is how a change-feed consumer lines the feed up with its reads; see Head version for the ordering guarantees. Like the other data-plane endpoints it is open.

GET /schema

A structured introspection of the live schema (the post-migration schema, not the on-disk file) plus its canonical SDL — intended for tooling and typed-client codegen. Each field's kind is scalar, relation, or vector:

{
  "format": "rhypedb-schema-introspection-v1",
  "types": [
    {
      "name": "Post",
      "fields": [
        { "name": "title", "kind": "scalar", "scalar": "String", "unique": false, "indexed": true },
        { "name": "author", "kind": "relation", "target": "Author", "many": false, "onDelete": "cascade" },
        { "name": "embedding", "kind": "vector", "dimensions": 384,
          "vectorize": { "source": "title", "model": "all-MiniLM-L6-v2" },
          "index": { "type": "hnsw", "metric": "cosine", "quantization": "turboquant_4bit", "m": 16, "efConstruction": 100 } }
      ]
    }
  ],
  "sdl": "type Author { ... }\n\ntype Post { ... }\n"
}

Types are sorted by name; fields are in declaration order. Like the other data-plane endpoints it is open (no admin token) — the schema is no more sensitive than the queries it enables. Put it behind your own network boundary if you need to restrict it.

Generated clients

rhypedb-codegen turns a schema into a typed Rust client module:

rhypedb-codegen --schema schema.rhype --out client.rs   # omit --out to write stdout

Or generate against a running server's live schema (no schema file needed) with the rhypedb-cli codegen subcommand, which fetches GET /schema:

rhypedb-cli --host http://127.0.0.1:4200 codegen --lang rust --out client.rs
rhypedb-cli --host http://127.0.0.1:4200 codegen --lang ts   --out client.ts
rhypedb-cli codegen --schema schema.rhype                    # offline file mode, to stdout

Both produce byte-identical output for the same schema; the live form just sources the SDL from the server instead of a file (handy after a migration, since the live schema reflects the post-migration shape).

It emits, per object type, a serde-deriving row struct (scalar fields, each Option<T> so a column-projected response still deserializes) plus typed query seeds that return a [rhypedb_client::Query<T>]. The generated module re-exports Query and Row from rhypedb-client, so you pair it with a Client and get the binary round-trip for free:

#![allow(unused)]
fn main() {
mod client;                                   // the generated module
use client::{User, Row};
use rhypedb_client::Client;

let client = Client::connect("127.0.0.1:4201")?;

// Seeds return a typed `Query<User>` — hand it straight to the client.
let adults: Vec<Row<User>> = client.fetch(&User::all().filter(".age > 18").limit(10))?;
for row in &adults {
    println!("{}: {:?}", row.id, row.data.name);
}

// Typed create from a row's set fields (strings escaped, numbers/bools coerced):
let ann: Row<User> =
    client.create(&User::create(&User { name: Some("Ann".into()), age: Some(30), ..Default::default() }))?;
// the query: r#"User.create({ name: "Ann", age: 30 })"#
}

A TypeScript client (--lang ts) mirrors the same shape against the official @rhypedb/client (Node/Bun/Deno) — an interface per type plus a value namespace of typed seeds returning a Query<T>, both Query and Row imported from the client:

rhypedb-codegen --schema schema.rhype --lang ts --out client.ts
import { AsyncClient } from "@rhypedb/client";
import { User, type Row } from "./client.ts";   // generated; re-exports Query/Row

const client = await AsyncClient.connect("127.0.0.1:4201");

const adults: Row<User>[] = await client.fetch(User.all().filter(".age > 18").limit(10));
const ann: Row<User> = await client.create(User.create({ name: "Ann", age: 30 }));   // typed create

Relations and vector fields are documented per type but are not scalar columns. Typed create sets a row's scalar fields: strings escaped, numbers/bools coerced, DateTime (RFC 3339 string) and Bytes (base64 string) emitted as quoted strings, and Json (a serde_json::Value / unknown) emitted as a raw JSON literal. Scalar types map per target — notably 64-bit integers (u64/i64) are Rust u64/i64 and, in TypeScript, bigint (lossless), while other numerics are number.

Admin plane (gated by RHYPEDB_ADMIN_TOKEN)

All routes below require Authorization: Bearer <RHYPEDB_ADMIN_TOKEN>. With the token unset they return 403; with a wrong token, 401. See Running rhypedb.

Errors are { "error": "message" } with the same statuses as POST /query, except that an unknown type or field named by the request is 404 (it is the resource the route acts on) rather than 400. A request the current state refuses — a migration in the wrong phase for a pause, cancel or cutover, a reload or export while a migration runs — is 409.

Method & pathPurpose
POST /admin/migrationsStart a field-type migration.
GET /admin/migrationsList migrations (filter with ?status=&type=).
GET /admin/migrations/{id}Migration detail / progress.
POST /admin/migrations/{id}/pausePause.
POST /admin/migrations/{id}/resumeResume.
POST /admin/migrations/{id}/cancelCancel (before cutover only).
POST /admin/migrations/{id}/cutoverForce cutover.
GET /admin/migrations/{id}/quarantineList quarantined rows.
POST /admin/migrations/{id}/quarantine/retryRetry quarantined rows.
GET /admin/migrations/{id}/eventsLive event stream (Server-Sent Events).
POST /admin/backupWrite a physical snapshot on the server.
GET /admin/backup/streamDownload a physical snapshot as a tar.
POST /admin/exportWrite a logical NDJSON export on the server.
GET /admin/export/streamDownload a logical export (?types=&vectors=).
POST /admin/import/streamApply a streamed logical dump to the live DB (?vectors=).
POST /admin/compactForce flush + full compaction.
POST /admin/rewrite-coversRewrite stored relation/index copies to the current rules and repair their to-one target ids (see Operations).
POST /admin/reloadHot-reload the schema (SDL in the request body).

Start a migration:

POST /admin/migrations
{
  "type": "User", "field": "score", "to": "f64",
  "converter": "widen_int_to_f64", "converter_version": 1,
  "chunk": 1000, "parallel": 4, "policy": "stop",
  "quarantine_cap": 100000, "dry_run": false
}
→ { "migration_id": 1, "created_at_ms": 1750000000000 }

See Schema Migrations and Backup & Recovery for the workflows these endpoints serve.

CLI reference

rhypedb-cli [GLOBAL FLAGS] [SUBCOMMAND]

Global flags

FlagDefaultMeaning
-H, --host <url>http://127.0.0.1:4200Server URL.
-e, --execute <query>—Run one query and exit.
--admin-token <token>$RHYPEDB_ADMIN_TOKENToken for admin subcommands.

With no subcommand and no -e, the CLI starts an interactive REPL (quit/exit to leave).

Subcommands

migrate start   --type T --field F --to TYPE --converter NAME
                [--converter-version V] [--chunk N] [--parallel P]
                [--policy stop|skip|quarantine] [--quarantine-cap N] [--dry-run]
migrate status  [ID]
migrate pause | resume | cancel | cutover   ID
migrate quarantine list   ID
migrate quarantine retry  ID --new-converter NAME
migrate events  ID

backup  --dest <server-path> [--label L]
backup  --download <local-dir> [--label L]
restore <snapshot-dir> <data-dir> [--force]
verify  <snapshot-dir>

export  --dest <server-path>  [--label L] [--types A,B] [--vectors raw|none|reembed]
export  --download <local-file> [--types A,B] [--vectors raw|none|reembed]
verify-export <export-file>

backup, export, and the migrate family talk to the admin API and need --admin-token. restore and verify/verify-export are offline/local and do not. (Logical import is a separate binary — see below.)

Offline binaries

rhypedb-import

Import a logical export into a fresh data directory (server stopped):

rhypedb-import <export-file> --data-dir <path> [--force] [--vectors raw|none|reembed]

Binary TCP protocol

For high-throughput clients, the server speaks a length-prefixed binary protocol (default 127.0.0.1:4201, --tcp-listen). It executes the same queries as POST /query with less per-request overhead, and adds a bulk vector-ingest message.

Frame format

[ len: u32 BE ] [ req_id: u32 BE ] [ type: u8 ] [ payload: (len - 5) bytes ]

len counts req_id + type + payload. Responses echo the req_id.

Client message types

TypeNamePayload
0x01Query[ q_len: u32 BE ][ utf-8 query ]
0x02Ping(empty)
0x03VectorBatchbulk vector ingest for one Vector field
0x04Prepare[ q_len: u32 BE ][ utf-8 query ] (same as Query)
0x05Execute[ stmt_id: u64 BE ]
0x06Subscribefilter (see Subscriptions)
0x07Unsubscribe[ sub_req_id: u32 BE ]
0x08Auththe raw UTF-8 end-user JWT (the whole payload)
0x09QueryWithOrigin[ origin: u64 BE ][ q_len: u32 BE ][ utf-8 query ] — a Query whose writes carry a write origin
0x0AExecuteWithOrigin[ origin: u64 BE ][ stmt_id: u64 BE ] — an Execute whose writes carry a write origin
0x0BHeadVersion(empty) — read the latest committed version (see Head version)
0x0CTransaction[ flags: u8 ][ origin: u64 BE, if flags & 1 ][ utf-8 JSON op list ] — a write transaction

Server response types

TypeNamePayload
0x80Objects[ count: u32 BE ] then encoded objects
0x81Singleone encoded object
0x82Done(empty)
0x83Error[ msg_len: u32 BE ][ utf-8 message ]
0x84Pong(empty)
0x85Prepared[ stmt_id: u64 BE ]
0x86Subscribedack of a Subscribe, correlated by req_id: empty, or [ granted_ms: u32 BE ] when the Subscribe asked for heartbeats
0x87EventUTF-8 JSON WireEvent (server-pushed)
0x88SubLagged(empty; server-pushed lag notice)
0x89Scored[ count: u32 BE ] then, per row, [ score: f32 BE ] + one encoded object — a ranked result (.matches / .similar) in rank order
0x8AReranked[ count: u32 BE ] then, per row, [ score: f32 BE ][ rerank_score: f32 BE ] + one encoded object — a ranked .similar result in which at least one row was scored by the cross-encoder; rerank_score is NaN on a row it did not score. Sent instead of Scored only in that case, so clients that predate it keep working wherever the cross-encoder is off
0x8BHeadVersion[ version: u64 BE ] — reply to HeadVersion
0x8CHeartbeat(empty; req_id = 0; server-pushed on a subscription connection that asked for heartbeats)
0x8DTransaction[ version: u64 BE ][ count: u32 BE ] then one result per operation — reply to Transaction, and to a transaction { ... } block sent as a query (see Write transactions)
0x8EPage[ cursor_len: u32 BE ][ utf-8 cursor ] then the Objects payload ([ count: u32 BE ] then encoded objects) — an ordered page; cursor_len 0 means no row follows

VectorBatch (0x03) bulk-ingests caller-supplied f32 vectors for one type's Vector field — the path used by rhypedb-import and the recommended way to load precomputed vectors at scale.

Prepared statements

Prepare (0x04) parses a query and caches it for the lifetime of the connection, replying with a Prepared (0x85) carrying a stmt_id. Subsequent Execute (0x05) messages re-run that statement by id — no re-parse and no re-sent query string — and reply exactly like Query (Objects / Single / Done / Error). Each Execute runs against the current data, so a prepared read reflects the latest writes. Statement ids are per-connection (like a Postgres session) and are dropped when the connection closes; executing an unknown id is an Error. This is purely a transport optimization for hot, repeated queries — there are no bind parameters yet (the query is fixed at Prepare time).

Pins are bounded per connection by both a count (1024 statements) and aggregate query-text size (1 MiB); exceeding either returns an Error. There is no per-statement deallocate message yet — reclaim slots by closing the connection.

Write origins

A write origin is an opaque, caller-chosen unsigned 64-bit tag that the server stamps on every change event a statement's writes produce. It is the network form of the engine's create_with_origin / update_with_origin / delete_with_origin / link_with_origin / unlink_with_origin verbs, and it is stamped exactly as they stamp it:

  • create and every row of a create_batch;
  • .update() and .delete(), on a point write and on a filter-guarded set write alike — a delete stamps the same origin on every object its @on_delete(cascade) policies delete;
  • .link() / .unlink(), on every relationship event they publish (the source's and each @inverse target's), point and filter-guarded alike;
  • a read-only query ignores it.

Its use is loop-breaking: a backend that subscribes to the feed and writes in reaction to it tags its own writes and subscribes with the origin excluded (SubscriptionFilter::excluding_origin in Rust, .excludingOrigin() in TypeScript), so it never reacts to its own changes — see WireEvent.

Send it with QueryWithOrigin (0x09) or ExecuteWithOrigin (0x0A), which run and reply exactly like Query and Execute; on HTTP, with the origin member. The origin is chosen per request, not per connection, so one connection serves tagged and untagged writers alike, and one prepared statement can run either way. An untagged request keeps using the plain Query/Execute frames, so old clients are unaffected; a server that predates origins answers 0x09/0x0A with its "unknown request type" Error. The official clients expose it as the *_with_origin (Rust) / *WithOrigin (TypeScript) variants of query, fetch, create, execute, execute_prepared, fetch_prepared and create_prepared.

An origin is not an identity. Any client can send any value, and the server does not check it, so it must never be used for authorization, auditing, or to decide whom a change "belongs to". It plays no part in the security rules, which judge a write by the request's verified principal alone; write the value you want subscribers to skip, nothing more.

Head version

HeadVersion (0x0B, empty payload) replies HeadVersion (0x8B) with the database's latest committed version: the number every change event carries as version, and what an embedded caller reads with Database::head_version(). On HTTP it is GET /head. The official clients expose it as head_version() (Rust Client and AsyncClient) and headVersion() (TypeScript, a bigint).

It lets a consumer line the change feed up with its own reads:

  1. Subscribe, and wait for the Subscribed ack.
  2. Read the head, h.
  3. Read the state it needs.
  4. Apply only events with version > h. Every commit at or below h is already in the reads of step 3. Every change the feed reports that commits above h reaches the subscription as an Event, unless a SubLagged says events were dropped (then re-read). The head can also move past commits that publish no event (background derived writes such as embeddings), so a gap in the versions you see is normal.

Events from concurrent commits can arrive out of version order: each commit publishes after it releases the commit lock. Order by version, not by arrival: keep the highest version applied per object and ignore an event whose version is at or below it.

The server guarantees, across connections and across TCP and HTTP:

  • An acknowledged write is at or below the head. Once the reply to a write has arrived, a head read sent afterwards returns at least that write's commit version.
  • The head never goes back. A later head read never returns a smaller value.
  • Reads sent after a head read see everything up to it. A query sent after the reply to a head read of h observes every commit <= h in the stored objects and their scalar, unique and relation indexes. The full-text index (.matches) and vector embeddings (.similar) are derived after a commit becomes visible, so for a commit that was still in flight when the head was read, those two can briefly trail it.

Like a query, HeadVersion is refused on a subscription connection; read it on a query connection. A server that predates it answers 0x0B with its "unknown request type" Error.

Write transactions

A write transaction is an ordered list of writes committed as one: all of them or none, at one commit version, with one change event per changed object. Its semantics (names, guards, rules, events, limits) are those of the query language's transaction { ... } block; this is the same thing as data, for clients that build it in code.

The Transaction frame (0x0C) carries a flags byte (bit 0: an origin follows; the other bits are reserved and must be 0), the optional write origin, then the operations as a UTF-8 JSON array. POST /query takes the same array as {"transaction": [...]}.

[
  { "op": "create", "type": "Message", "fields": { "subject": "Hello" }, "as": "m" },
  { "op": "create", "type": "MessageContent", "fields": { "body": "…" }, "refs": { "message": "m" } },
  { "op": "link", "type": "Message", "id": { "ref": "m" }, "field": "labels",
    "target_type": "Label", "target": 7, "edge_fields": { "weight": 0.5 } },
  { "op": "update", "type": "Thread", "id": 9, "fields": { "rev": 4 }, "where": ".rev == 3" },
  { "op": "unlink", "type": "Message", "id": 3, "target_type": "Label", "target": 7 },
  { "op": "delete", "type": "Draft", "id": "12" }
]
  • fields (create, update) and edge_fields (link) hold JSON values, coerced to the declared field types as query literals are; arrays and objects are for Json fields. An integer past 2⁶³−1 is refused.
  • as names a create; a later operation refers to it with {"ref": name} wherever an id goes, or sets a field to its id through refs (field → name). A field may be in fields or refs, not both.
  • An id is a JSON number, a decimal string (for ids past 2⁵³ from JavaScript), or {"ref": name}.
  • field (link, unlink) names the source's relation field; omit it when there is only one to the target's type.
  • where is a guard in the predicate syntax: the transaction aborts unless it holds on the object.
  • Unknown members, and an unknown op, are refused.

The reply (0x8D, or the "transaction" member over HTTP) is the commit version and one result per operation, in order:

TagResultThen
0x01Created[ id: u64 BE ][ has_object: u8 ] + the encoded object if has_object
0x02Updatedthe same, the object as the update left it
0x03Deleted—
0x04Linked—
0x05Unlinked[ existed: u8 ] — whether there was an edge to remove

has_object is 0 when the read rules hide the object from the caller (the id is still given). Over HTTP each result is {"op": "create" | "update" | "delete" | "link" | "unlink", "id"?, "object"?, "existed"?} and version is a decimal string, as in GET /head.

A failed transaction replies Error (HTTP: the status table above): 403 for a rules denial, 404 for a missing object, 409 for a @unique violation or a guard that did not hold, 400 for a malformed list, an unresolvable name, or more than 10,000 operations. Nothing is written.

Like a query, Transaction is refused on a subscription connection. A server that predates it answers 0x0C with its "unknown request type" Error; a client that predates it reports a 0x8D reply to a query-text block as an unexpected response. The official clients expose it as Transaction with client.transaction(&tx) / transaction_with_origin (Rust, both clients) and client.transaction(tx, { origin }) (TypeScript); create returns a placeholder that later operations take as an id and that finds the new id in the result.

Subscriptions

Subscribe (0x06) registers a live change-event stream on the connection and replies with Subscribed (0x86). Thereafter the server pushes Event (0x87) and SubLagged (0x88) frames for that subscription. The subscribe frame's req_id is the subscription handle: every pushed frame echoes it, and Unsubscribe (0x07) carries it to cancel (replying Done).

Subscriptions are the network transport for the engine's change feed — created, updated and deleted objects, and linked or unlinked relationships, matching an optional filter. The subscriber is a trusted backend (a tenant app server or jkbase-internal consumer); like POST /query, the path is open, so network-level access control is the deployment's responsibility.

Pushes are unsolicited. An Event/SubLagged can arrive at any time — including between a request and its reply — so a subscribing client MUST demultiplex frames by kind first and never assume "the next frame answers my last request". To keep simple synchronous clients safe, a connection that issues a Subscribe becomes a subscription connection: it serves only Subscribe/Unsubscribe/Ping and rejects Query/Prepare/Execute (with or without an origin)/VectorBatch/HeadVersion with an Error. Run queries on a separate connection. A connection that never subscribes never receives a push, so existing request/response clients are unaffected. (An old server replies Error to a Subscribe — treat that as "subscriptions unsupported".)

Subscribe filter payload

[ flags: u8 ]            bit0 = has type, bit1 = has object id,
                         bit2 = has heartbeat (other bits must be 0)
[ if has type:   type_len: u16 BE, type utf-8 ]   (zero length is rejected)
[ if has object: object_id: u64 BE ]
[ kinds: u8 ]            bitmask bit0=create bit1=update bit2=delete; 0 = all kinds
[ if has heartbeat: heartbeat_ms: u32 BE ]        (≥ 1; see Heartbeats below)

Clearing the type flag matches all types; an all-zero kinds byte matches all kinds. The decoder is strict (reserved bits, an empty type name, a zero heartbeat interval, truncation, and trailing bytes are all rejected) so a malformed filter fails loudly.

WireEvent (the Event JSON payload)

{ "v": "rhypedb-event-v1", "kind": "create", "type": "User",
  "id": "42", "version": "7", "origin": "9001", "fields": { "name": "Alice", "age": 30 } }

id and version are decimal strings so 64-bit values survive a JavaScript JSON.parse (which would coerce a bare number to a float and lose precision past 2^53). origin (also a decimal string) is optional: it is present only when the writer tagged the mutation with a write origin — in process via the engine's create_with_origin / update_with_origin / delete_with_origin verbs, or over the network via QueryWithOrigin / ExecuteWithOrigin or the HTTP origin — and is omitted for an untagged write. It is an opaque, caller-defined token — a subscriber that also writes uses it to recognise and skip its own changes and so avoid a write → event → react → write loop. A batch or cascade write stamps the same origin on all of its events. The official Rust and TypeScript clients honor a subscription filter's excluding_origin / .excludingOrigin() by dropping matching events client-side after decode (the server still sends them), so you can break the loop without inspecting origin yourself. The Event is a notification, not a faithful snapshot: fields use the /query read form (Bytes as base64, DateTime as RFC 3339, Json inline), but large 64-bit scalar field values may lose precision in a JS JSON.parse — re-query for authoritative state. create, update, and delete events all carry the object's scalar fields; a delete reports the deleted object's last-known values (so you can tell which object — by slug/identifier — went away). The exception: a cascade-deleted pure edge-only join row (a type with no scalar fields) carries no fields. A relationship change is an update that carries them too.

Relationship changes

A committed .link() or .unlink() (in process: link, unlink, link_if, unlink_if and their _with_origin forms) publishes an update event with an edge member:

{ "v": "rhypedb-event-v1", "kind": "update", "type": "Page", "id": "1",
  "version": "12", "origin": "9001", "fields": { "title": "Intro" },
  "edge": { "op": "link", "field": "parent", "peer_type": "Page", "peer_id": "2" } }
  • Who gets one. The link's source, with its forward relation field and the target as the peer. The target gets one too for every @inverse field its type declares over that relation (children: [Page] @inverse(Page.parent) above would get "field": "children" with the source as the peer), since a reader of that field sees the change. A target whose type declares no inverse gets none: nothing it reads changed.
  • Kind. update, because a relationship is part of the object's state and a subscriber filtering on updates must hear of it. Filters match on the header alone (type, id, kind, origin), so for_object("Page", 2) hears of page 2's new child, and a create- or delete-only filter does not. A new kind was not used because the Rust and TypeScript clients released before it reject an unknown kind.
  • Version and origin. The commit's version, shared by every event of that commit, and the write's origin.
  • Fields. The object's scalar fields as of that commit, as an update carries them. The link did not change them; they are there so that read rules can authorize the event (below), and so that an older client sees an ordinary update.
  • Read rules. On a server with security rules, a subscriber receives an edge event only if it may read both the event's object and the object at the other end of the edge (peer_type / peer_id), each judged on its fields as of the commit. A query never shows a reader a linked object it may not read, and an event names that object, so it must not either.
  • Only what committed. A guard that rejects, a failed link, and an unlink of an edge that does not exist publish nothing. Relinking a to-one relation that already points elsewhere publishes the unlink of the old edge (for the source and the old target's inverse) before the link of the new one; linking an edge that already exists publishes a link again (edge fields may have changed).
  • Compatibility. edge is additive, like origin: the format tag stays rhypedb-event-v1, and an older client decodes such an event as a plain update. peer_id is a decimal string, like id. The Rust client exposes it as ChangeNotification::edge (EdgeChange { op, field, peer_type, peer_id }), the TypeScript client as change.edge ({ op, field, peerType, peerId }). Both decode an op they do not know (from a newer server) as no edge at all, so the event stays a plain update rather than failing the subscription.

Two other writes add or remove edges, and publish the events a .link() or .unlink() of those edges would, with the same shape, read rules, version and origin, to every end of the edge that is still there:

  • A create that sets a relation inline (create, create_batch, and a restore or import): Post.create({ author: alice }) with User.posts: [Post] @inverse(Post.author) publishes the post's create, then a link for alice on posts with the post as the peer. The new object's own create covers its side, so it gets no edge event. A target whose type declares no inverse gets none either.
  • A delete, with its cascade: an object that survives it gets an unlink for each of its edges to a deleted object, after the delete events. That is the source of an @on_delete(remove) relation to a deleted object (on its forward field), and the target of a deleted object's relation (on each @inverse field). An edge whose two ends were both deleted gets no edge event: the delete events cover it. For read rules, the deleted peer is judged on its fields as they were just before the delete.

Heartbeats & dead connections

A subscription is silent while nothing matches its filter, so on its own the wire cannot tell a quiet, healthy subscription from a half-open one (a NAT or firewall dropped the flow, or the server vanished without a FIN or RST). A subscriber can ask for heartbeats to tell them apart:

  1. The client sets the heartbeat flag in the subscribe filter and appends the interval it wants, heartbeat_ms.
  2. The server clamps it to 100 ms..10 min. A connection heartbeats at the smallest interval any of its subscriptions asked for, and the Subscribed ack carries that interval as [ granted_ms: u32 BE ].
  3. While the connection has a live subscription, the server pushes a Heartbeat (0x8C, req_id 0, empty payload) every granted interval, whatever other traffic flows. Heartbeats may also arrive between an Unsubscribe and its Done.
  4. A client that receives no bytes at all for 3 granted intervals treats the connection as dead: the subscription ends with an error, and the consumer resubscribes and reconciles by re-querying (events may have been missed).

It is opt-in, so old peers are unaffected. An old client never sets the flag: it gets the empty ack it expects and no Heartbeat frames. An old server's strict decoder rejects the unknown flag bit with an Error containing reserved flag bits set. That subscribe registered nothing, so the client resends a plain Subscribe on the same connection and runs without heartbeats.

The official clients ask for a 30 s heartbeat by default, so a dead subscription connection is reported after about 90 s:

  • Rust (rhypedb-client): ClientConfig::subscription_heartbeat (None to opt out). Subscription / AsyncSubscription report the grant with heartbeat_interval() (None against a server that predates heartbeats), and a silent connection ends next_event with Error::HeartbeatTimeout. The client's read_timeout bounds the subscribe handshake, but not the event reads.
  • TypeScript (@rhypedb/client): the subscriptionHeartbeatMs option (null to opt out). AsyncSubscription#heartbeatIntervalMs reports the grant, and a silent connection rejects next() with a heartbeat_timeout error.

TCP keepalive is a second, OS-level net, and it also covers the query connection. It is off unless configured: in Rust, ClientConfig::keepalive (TcpKeepalive { idle, interval, retries }, applied to every client socket); in TypeScript, keepAliveInitialDelayMs (Node only exposes the idle time).

#![allow(unused)]
fn main() {
use std::time::Duration;
use rhypedb_client::{Client, ClientConfig, TcpKeepalive};

let config = ClientConfig {
    subscription_heartbeat: Some(Duration::from_secs(10)),   // dead after ~30 s
    keepalive: Some(TcpKeepalive::new(Duration::from_secs(60))
        .with_interval(Duration::from_secs(10))
        .with_retries(3)),
    ..ClientConfig::default()
};
let client = Client::connect_with("127.0.0.1:4201", &config)?;
}

Backpressure & lag

Each connection has a bounded event buffer. A merely-slow consumer absorbs bursts; on overflow the server drops events and pushes a SubLagged for the affected subscription (delivered eagerly — you get it even if no further event ever arrives). SubLagged means "you missed events — reconcile by re-querying". There is no unbounded server-side buffering. An Event whose JSON would exceed the 16 MiB frame cap (e.g. a very wide String field) is likewise downgraded to a SubLagged instead of being shipped as a frame the peer would reject. The buffer is shared across a connection's subscriptions, so a high-volume subscription can cause a SubLagged on the connection's other subscriptions — put a firehose on its own connection. The server also pushes a best-effort SubLagged to each live subscription on graceful shutdown, so a backend reconciles across a deploy. Subscriptions are capped per connection (64) and per process (512); /status reports the live network_subscriptions count and a cumulative events_dropped counter.

A reference Rust client lives at crates/rhypedb-server/examples/subscribe.rs:

cargo run -p rhypedb-server --example subscribe -- 127.0.0.1:4201 --type User