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

rhypedb

A strongly-typed object database with first-class relationships and native vector search. Written in Rust.

rhypedb treats objects, relationships, and vectors as core primitives — not afterthoughts bolted onto a relational or document model.

  • Objects, not rows. You define typed schemas; stored objects conform to their type. No impedance mismatch between your data model and your domain model.
  • Relationships are properties. You declare links between objects in the schema. The database stores, traverses, and maintains them — and enforces referential integrity. No foreign keys, no junction tables, no JOINs.
  • Vectors are native. Vector<N> is a field type like String or i64. Vectors are compressed at rest with TurboQuant-adapted quantization, indexed with HNSW, and queried with a .similar(...) operator — optionally with server-side text embedding so you never have to compute embeddings yourself.
  • Full-text search is built in. A String @fulltext field gets a BM25-ranked inverted index — required terms, phrases, prefix terms, diacritic-insensitive, with an optional English stemmer — maintained inside each object's transaction, queried with .matches(...) right next to .similar(...).
  • One path-based query language for lookups, filters, relationship traversal, mutations, vector similarity, and full-text search.
  • Real-time subscriptions. Subscribe to query patterns and get semantically meaningful change events.

Design goals

  • Low memory. rhypedb is built to run inside Firecracker microVMs. TurboQuant compresses vectors 4–8×, and steady-state RSS stays in single-digit megabytes on the benchmark workloads. Scale-to-zero via VM snapshots.
  • Referential integrity. No dangling references. Delete policies (remove, cascade, deny) are declared in the schema and enforced atomically.
  • MVCC. Snapshot isolation with write-write conflict detection. Readers never block writers.
  • Single binary, no external dependencies. rhypedb is the default database for the jkbase cloud platform.

How it fits together

rhypedb ships three binaries:

BinaryRole
rhypedb-serverThe database server. Speaks HTTP (default 127.0.0.1:4200) and a binary TCP protocol (default 127.0.0.1:4201).
rhypedb-cliInteractive client and operator tool — run queries, drive migrations, take backups, export data.
rhypedb-importOffline importer for logical (NDJSON) exports.

A running server is configured by exactly one thing you write: a schema file (.rhype). Everything else — types, indexes, vector fields, relationships, delete policies — is declared there.

Where to go next

Status: early development. The data model, query language, storage engine, vector search, migrations, and backup/restore are all implemented and tested, but APIs may still change. This documentation describes the current behavior of the master branch.

For the internal design (storage engine, MVCC, the vector pipeline), see Architecture.

Getting Started

This walkthrough takes you from a clean checkout to a running server you can query — in about five minutes.

1. Build

rhypedb is a Cargo workspace. Build the server and CLI in release mode:

cargo build --release -p rhypedb-server -p rhypedb-cli

The binaries land in target/release/:

  • target/release/rhypedb-server
  • target/release/rhypedb-cli

The first build compiles the embedding runtime (ONNX), so it takes a while. Subsequent builds are fast.

2. Write a schema

Create a file blog.rhype:

type User {
    name: String
    email: String @unique
    age: u32
    friends: [User] @on_delete(remove)
    posts: [Post] @inverse(Post.author)
}

type Post {
    title: String
    body: String
    author: User @on_delete(cascade)
    tags: [Tag] @on_delete(remove)
}

type Tag {
    name: String @unique
}

This declares three object types and the relationships between them. @unique enforces a uniqueness constraint, @inverse makes User.posts and Post.author two ends of the same relationship, and @on_delete declares what happens to a relationship when an object is deleted. See the Schema Reference for everything you can write here.

3. Run the server

target/release/rhypedb-server --schema blog.rhype --data-dir ./data

You'll see:

rhypedb HTTP listening on 127.0.0.1:4200
rhypedb binary TCP listening on 127.0.0.1:4201

The ./data directory now holds the database (LSM-tree files, the write-ahead log, a copy of the schema, and a single-writer LOCK). Leave the server running and open a second terminal.

4. Run queries

With the CLI

Execute a single query with -e:

target/release/rhypedb-cli -e 'User.create({ name: "Alice", email: "alice@example.com", age: 30 })'
User:1
  age: 30
  email: "alice@example.com"
  name: "Alice"

Every object gets a database-assigned id (here 1) — see Object identity.

Create another user and a post, then link them:

rhypedb-cli -e 'User.create({ name: "Bob", email: "bob@example.com", age: 25 })'
rhypedb-cli -e 'Post.create({ title: "Hello", body: "first post", author: 1 })'

Read it back, including a relationship traversal:

rhypedb-cli -e 'User.get(1).posts'
rhypedb-cli -e 'User.filter(.age > 26)'

Run the CLI with no arguments to drop into an interactive REPL:

$ rhypedb-cli
rhypedb> User.get(1)
User:1
  age: 30
  email: "alice@example.com"
  name: "Alice"
rhypedb> quit

With HTTP

The same queries work over HTTP — POST /query with a JSON body:

curl -s http://127.0.0.1:4200/query \
  -H 'content-type: application/json' \
  -d '{"query": "User.get(1)"}'
{ "object": { "type": "User", "id": 1, "fields": { "name": "Alice", "email": "alice@example.com", "age": 30 } } }

This is all you need to build a client in any language: send a query string, get JSON back. See the API Reference for the full response shapes and the faster binary TCP protocol.

5. Check server health

curl -s http://127.0.0.1:4200/status
{ "subscriptions": 0, "vectorizer": { "pending": 0, "indexes": [] } }

Next steps

Schema Reference

A rhypedb schema is a text file (conventionally *.rhype) that declares your object types, their fields, and the relationships between them. The server reads it at startup (--schema), and it is the single source of truth for what the database will store and enforce.

type User {
    name: String
    email: String @unique
    age: u32
    friends: [User] @on_delete(remove)
    posts: [Post] @inverse(Post.author)
    embedding: Vector<384> @vectorize(source: "name", model: "all-MiniLM-L6-v2")
}

Types

A schema is a collection of type declarations. Each type has a name (used as-is in queries) and a brace-delimited block of fields:

type TypeName {
    field_name: FieldType
    another_field: FieldType @directive
}

Fields are separated by whitespace — write one per line. (Commas are not used between top-level fields, though an edge-field block accepts them.) Field names may not contain a double underscore (__) — that sequence is reserved for the engine's internal sidecar keys.

Object identity

Every object has an id — a database-assigned unsigned 64-bit integer that is its primary key. You don't declare it; every type has one implicitly.

  • Assigned on create. ids come from a counter and increase monotonically. You can't set or override an object's id when creating it.
  • Globally unique, not per-type. The counter is shared across all types, so a User and a Post created in sequence get different ids (e.g. 1 and 2) — ids are unique across the whole database, not 1..N within each type.
  • Never reused. Deleting an object does not recycle its id; the counter only moves forward (it is re-seeded past the highest existing id when the database reopens).

You reference objects by id in queries. A relation field in a create takes the target's id as a plain integer:

User.get(1)
Post.create({ title: "Hello", author: 1 })

ids on the wire

In a POST /query response an object is shaped as { "type": …, "id": …, "fields": { … } }, with id as a JSON number:

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

Because JSON numbers are IEEE-754 doubles in most clients, an id above 2⁵³ can lose precision if parsed as a number — treat ids as opaque identifiers, and in languages where it matters read them as 64-bit integers. (The logical export format encodes ids as strings precisely so a dump round-trips exactly.)

There is no user-defined auto-increment, default, or sequence for your own scalar fields — the object id is the only auto-assigned value. @unique enforces uniqueness on values you supply (e.g. email); it does not generate them.

Field types

Scalars

TypeMeaningWritten asReads back as
StringUTF-8 text"text"string
Boolbooleantrue / falseboolean
i32, i64signed integers42number
u32, u64unsigned integers42number
f32, f64floating point1.5number
DateTimetimestamp (epoch-millis UTC)RFC 3339 string "2026-06-20T12:00:00Z", or an integer epoch-millisRFC 3339 string
Bytesraw byte blobbase64 string "aGVsbG8="base64 string
Jsonarbitrary JSON valuea raw JSON literal { "k": 1 } (or any scalar)inline JSON

Note the casing: the named types (String, Bool, DateTime, Bytes, Json) are capitalized, while the numeric primitives (i64, u32, f64, …) are lowercase. This matches how you refer to them in queries and migrations.

DateTime is stored as a 64-bit epoch-millisecond timestamp (UTC); sub-millisecond precision in an RFC 3339 input is truncated. It is filterable and orderable (.filter(.created > "2026-01-01T00:00:00Z") works against either an RFC 3339 string or an integer epoch-millis), including pre-epoch (negative) timestamps. Mark it @indexed to build an ordered secondary index so range queries skip the full scan; @unique enforces an exact-match uniqueness constraint.

Bytes is an arbitrary byte blob, written and read as standard base64. From the query language it is not filterable beyond presence checks (== null / != null); any other comparison on a Bytes field is rejected with an error (the query syntax has no Bytes literal, and byte-ordering a blob is not a meaningful user query). Programmatic callers can still match exact or ranged byte values via the engine API Database::filter_scan_bytes (which uses a @indexed byte index when present).

Json holds an arbitrary JSON value. It supports whole-value equality filtering only (==/!= against a complete JSON literal). Ordering comparisons (<, >, …) are rejected (no total order over arbitrary JSON), and querying into a key or path (e.g. .meta.k == 1) is not supported yet — both are rejected with an error rather than silently matching nothing. @indexed is not supported on Json (use @unique for an exact-match constraint).

Relations

A field whose type is another type name is a relationship:

author: User          // to-one
posts: [Post]         // to-many

Relationships are stored and traversed by the database — there are no foreign-key columns or junction tables in your schema. You create and remove links at query time with .link(...) / .unlink(...) (see the Query Language).

Vectors

embedding: Vector<384>

Vector<N> declares an N-dimensional float vector. On its own it stores raw vectors you supply; add an @index(hnsw, ...) directive to make it searchable and @vectorize(...) to have the server compute embeddings for you. See Vector Search.

Edge fields (metadata on relationships)

A relationship can carry its own scalar fields — data that belongs to the link, not to either object. Declare them in a block after the relation:

type User {
    favorite_movies: [Movie] {
        rating: f32
        added_at: DateTime
    }
}

You set edge fields when linking, from the source object: User.get(1).link(.favorite_movies, Movie.get(42), { rating: 4.5 }). (Naming .favorite_movies is optional when it is the only field of User that points to Movie; see Links.)

Directives

Directives annotate a field with @name or @name(args).

@unique

On a scalar field, enforces that no two objects of the type share a value. A violating insert is rejected atomically.

email: String @unique

@indexed

On a scalar field, builds a secondary index so filter queries on that field don't scan the whole type. Use it for fields you filter or look up by frequently.

year: i64 @indexed

Each indexed field adds one index entry per object. For small objects that entry also holds a copy of the object, so an indexed query returns rows without a second lookup; see Storage cost of indexes and relations.

@indexed(cover: false)

The same index without the copies: each entry holds only the field's value and the object's id, and a query fetches each matching object by id.

seen: Bool @indexed(cover: false)

Use it on a field whose index is large and that you rarely read in full, such as a Bool flag that half the objects share. With the default, three such flags on a mail store hold three extra copies of every small message. Queries return the same rows in the same order either way. Without the copies, a query that returns many rows makes one lookup per row, so it runs slower than one served from copies. cover: true is the default and the same as plain @indexed.

Type-level @index(field, ..., order [asc|desc])

On a type, declares an ordered index: the fields before the last are pinned by equality, and the last orders the rows within each group. It serves "the newest N messages in this place, then the next N" without reading the rest of the place:

type Message @index(place, created desc) {
    place: String
    created: DateTime
    body: String
}
Message.filter(.place == "lobby").order_by(.created, desc).limit(50)

A page through the index reads about limit + 1 entries (the extra one tells whether another page exists) and fetches only the rows it returns, however many objects the group holds. See Ordering and pages.

  • Fields. Any scalar but Json, each named once. Only the last field takes asc (the default) or desc. A type may declare several indexes, each with a different field list or direction; @index(at) with no equality fields orders the whole type.
  • Which queries use it. A query is served by an index when it is Type or Type.filter(...) (plus more .filter steps), every equality field of the index is pinned by a top-level == in the filter, and .order_by names the index's last field in its direction. Other conjuncts (&&), || branches and further filters are checked on each row the index yields. Any other ordered query is still answered, by sorting the rows its pipeline produces, with the same order and cursors. Ordering in the opposite direction from the index sorts too: declare the second direction as its own index if you need it.
  • Order. By the field's value: integers, floats (-0.0 equals 0.0; a NaN sorts by its sign, a positive one above every number and a negative one below), strings and bytes by their bytes, false before true. A missing or null value sorts first ascending and last descending. Ties are broken by id in the same direction, so the order is total and stable.
  • Maintenance. Every create, update and delete maintains every index of its type in its own transaction, so an index is never stale. Adding an index to a populated type (on a reopen or POST /admin/reload) builds it from the existing objects before the database accepts requests: the work is one pass over that type, once. Removing or changing a declaration sweeps the old entries the same way. Changing the type of a field an index uses is refused; drop the index first. Likewise, a schema that adds an index over a field whose type change is still in progress is refused at open; add it once the migration completes or is cancelled.

@fulltext / @fulltext(analyzer: "simple", positions: false)

On a String field, builds a full-text inverted index so the field can be searched by keyword with Type.matches(.field, "terms", k: N) (see Queries → Full-text search). The index is maintained synchronously inside each object's transaction, like @unique and @indexed, so it is never stale and survives a crash exactly as the object does.

type Post {
    title: String @fulltext
    body:  String @fulltext(analyzer: "simple", positions: false)
}

Parameters (both optional):

ParameterDefaultMeaning
analyzer"simple"How text is split into terms. simple: Unicode word segmentation, lowercase, diacritics folded to ASCII (Café → cafe), no stemming. english: the same, then English stop words removed (the Snowball list — the, of, my, is, don't, … 174 function words that would otherwise dominate BM25 ranking) and English stemming (Snowball/Porter2), so camera, cameras and Camera's are one term and run finds running — on indexed text and on query terms alike, phrases included. Use english for prose in English; simple for identifiers, codes, mixed-language text, or when prefix terms must complete character by character (a stemmed index holds stems, so securit* does not find security, stored as secur). The analyzer is part of the index; changing it — or upgrading to a release that changes what an analyzer does, as adding stop words to english did — rebuilds the index.
positionstrueStore term positions. Required for phrase queries ("distributed consensus"); costs roughly the size of the text again. positions: false halves the index and makes a phrase query on the field an error.

Only the first 65 536 words of a value are indexed; text past that is stored but not searchable. The words a create or update will index count against the query governor's examined-rows budget (an update, once per object it changes), so an oversized value is refused rather than indexed. This cap arrived with a change to what both analyzers do, so an index built by an earlier release is rebuilt in the background on the first open after upgrading.

@fulltext stacks with @unique and @indexed. It is rejected on any non-String field. Substring matching without an index is a separate predicate: .filter(.title.contains("invoice")) works on every String field.

Adding, changing or removing the directive on existing data. Unlike @indexed, @fulltext backfills: adding it to a populated type (on a reopen or POST /admin/reload) starts a background build of the index for every existing object; changing analyzer or positions rebuilds the index into a fresh generation and sweeps the old rows; removing the directive drops the index. New writes are indexed immediately throughout. While a build is running, .matches on that field returns an error carrying the progress, and GET /status reports it under fulltext (see Running rhypedb). A build interrupted by a restart resumes where it left off.

@on_delete(policy)

On a relationship, declares what happens to the link (and possibly the target) when an object is deleted. Policies:

PolicyBehavior
removeRemove the link only; leave the target object.
cascadeDelete the target object too (recursively).
denyRefuse the delete while the link exists.
posts: [Post] @on_delete(cascade)
friends: [User] @on_delete(remove)

@inverse(Type.field)

Marks two relationship fields as the two ends of a single bidirectional relationship. Linking one side makes the other side reflect it automatically.

type User {
    posts: [Post] @inverse(Post.author)
}
type Post {
    author: User
}

@index(hnsw, ...)

On a Vector<N> field, configures the HNSW index used for similarity search. All parameters are optional and have defaults.

embedding: Vector<768> @index(hnsw, metric: cosine, quantization: turboquant_4bit, m: 16, ef_construction: 200)
ParameterValuesDefault
metriccosine, l2, dot_productcosine
quantizationturboquant_2bit, turboquant_3bit, turboquant_4bitturboquant_4bit
mHNSW graph fan-out (≥ 1)engine default
ef_constructionbuild-time search width (≥ 1)engine default

Fewer quantization bits means a smaller index and faster search at some recall cost; pair it with per-query rerank (see Vector Search) to recover precision. quantization: none is rejected — vectors are always quantized in the index (the raw vectors are still kept losslessly at rest).

@vectorize(source, model)

On a Vector<N> field, tells the server to compute the embedding for you from a String field on the same object whenever it is created or updated.

text: String
embedding: Vector<384> @vectorize(source: "text", model: "all-MiniLM-L6-v2")
  • source — the name of a String field on this type.
  • model — the embedding model identifier (e.g. all-MiniLM-L6-v2). The vector dimension N must match the model's output size.

Combine it with @index(hnsw, ...) on the same field to both auto-embed and index. See Vector Search.

Storage cost of indexes and relations

rhypedb keeps each object once, under its id. Two read-path caches can add copies, and both are bounded by size:

  • @indexed fields. Every indexed field writes one index entry per object (key: field value + id). If the object serializes to at most 1 KiB, the entry also carries a copy of it, so filter on that field returns rows straight from the index. A larger object's entry carries only the key, as does every entry of an @indexed(cover: false) field; the query fetches the object by id, one point lookup per row. Results and their order are the same either way.

  • To-one relations. A link's reverse entry (what @inverse traversals walk) holds the ids of the linking object's other to-one targets, plus a copy of each such target that is at most 1 KiB, so a hop like Movie.ratings.user can return users without looking each one up. The linking object's own fields are never copied there, so a large type with many to-many links (a mail message with labels and recipients, say) costs a few dozen bytes per link.

  • Type-level @index(...). One entry per object per declared index. The entry holds no copy of the object: its key is the index's field values plus the id, and its value is empty. A page fetches its rows by id.

So a text-heavy type costs about its own size plus small per-index and per-link entries. Embedded users can move the threshold with OpenOptions::cover_max_bytes (usize::MAX copies everything, 0 nothing); the server uses the default. A new threshold, or a field switched to or from cover: false, applies to entries written from then on. Entries written by older versions (before 2026-11), under an earlier threshold, or before the switch keep their old form until rewritten. To bring a whole database up to the current rules at once, embedded users call Database::rewrite_covers() and then compact (db.storage().compact()). The pass runs in small batches alongside normal traffic and is safe to interrupt and rerun. On a 2.2 GB mail store it cut reverse-entry data from 333 MB to 136 MB.

Those stored target ids have to stay in step with the links themselves. Versions before 2026-11 let them drift: a reverse entry written before the object's other to-one link existed never learned about that link, and relinking or unlinking a to-one relation left the old id in the object's other reverse entries. A hop like Movie.ratings.user could then miss targets or return the old one. Current versions keep the ids in step on every link, unlink and delete. A database that an older version wrote with links in it starts out distrusted: Database::cover_peers_sound() returns false, and to-one hops read the links themselves instead of the stored ids. Results are correct, but those hops lose the shortcut. One rewrite_covers() run repairs the stored ids and records that the database can be trusted again; that record persists across restarts. New databases are trusted from the start.

A complete example

type User {
    name: String
    email: String @unique
    reputation: u32 @indexed
    friends: [User] @on_delete(remove)
    posts: [Post] @inverse(Post.author) @on_delete(remove)
    favorite_movies: [Movie] {
        rating: f32
        added_at: DateTime
    }
}

type Post {
    title: String
    body: String
    author: User @on_delete(cascade)
    tags: [Tag] @on_delete(remove)
    embedding: Vector<384> @vectorize(source: "body", model: "all-MiniLM-L6-v2") @index(hnsw, metric: cosine)
}

type Movie {
    title: String
    year: i64 @indexed
}

type Tag {
    name: String @unique
}

Evolving the schema

Changing the schema of a database that already holds data is a real operation with rules — adding fields is free, removing them is gated, and renames or type changes go through a migration system. See Schema Migrations.

Query Language

rhypedb has a single, path-based query language used for reads, writes, relationship traversal, and vector search. A query reads left to right: it starts from a source and then applies zero or more steps, each separated by a dot.

User.get(1).posts.filter(.title == "Hello").limit(10)
└─ source ─┘└ step ┘└────── step ──────────┘└─ step ─┘

You send a query as a string — via the CLI (-e '<query>' or the REPL), POST /query, or the binary TCP protocol. The result comes back as JSON. See the API Reference for response shapes.

In the examples on this page, text after // is a note for the reader. The query language has no comment syntax, so leave the notes out when you run a query.

Sources

Every query begins with one of these:

SourceMeaning
Type.get(id)Fetch one object by numeric id.
Type.get_many([id, ...])The objects of Type with these ids: missing ids are skipped, duplicates collapse, rows come back in ascending id order.
Type.filter(predicate)All objects of Type matching the predicate.
TypeAll objects of Type.
Type.create({ ... })Create one object; returns it (with its assigned id).
Type.create_batch([{ ... }, ...])Create many objects in one call.
User.get(42)
User.get_many([42, 7, 19])
User.filter(.age >= 18)
User
User.create({ name: "Alice", email: "alice@example.com", age: 30 })
User.create_batch([{ name: "Bob" }, { name: "Carol" }])

get_many is a set source: it chains like Type.filter(...). A .filter, a traversal, .limit / .offset, a .similar or .matches (which ranks only the listed objects, so k is the true top-k within them), and the writes .update / .delete / .link / .unlink (with guarded-write semantics: an id deleted after the read is skipped, not an error) all apply to the objects it found:

User.get_many([3, 9, 12]).filter(.active == true).update({ seen: true })
Post.get_many([4, 8, 15, 16, 23, 42]).similar(.embedding, "rust", k: 3)

The order the ids are written in, and any repeats, do not matter: User.get_many([9, 3, 9]) returns user 3 then user 9. Under security rules every returned object must pass the read rule, exactly as for get (an unreadable one is dropped), and a write straight after the source is gated per object by that write's own rule, as get(id).update(...) is. Each listed id counts as one examined row against the query governor's row budget, so a list longer than that budget is refused; the request size bounds it too (16 MiB per TCP frame, the HTTP body limit for POST /query). Lists of many thousands of ids are fine.

Object ids are assigned by the server. To reference another object in a create, give the relation field that object's integer id:

Post.create({ title: "Hello", author: 1 })      // the post's author is user 1

The value is a plain id literal, not a Type.get(id) expression; the target's type comes from the field's declaration. To add links after the object exists, or to set a relationship's edge fields, use .link.

Steps

Steps transform or act on the current set of objects.

Traverse a relationship — .field

Follow a relationship field to the objects on the other side. Traversals chain:

User.get(1).posts                       // posts authored by user 1
User.get(1).friends.posts               // posts by user 1's friends
User.get(1).posts.tags                  // tags on user 1's posts

Filter — .filter(predicate)

Keep only objects matching a predicate.

User.filter(.age > 18)
User.get(1).posts.filter(.title == "Hello")

Inside a predicate, .field refers to a field of the current object.

Comparison operators: ==, !=, <, <=, >, >=

Boolean operators: && (or and), || (or or), with parentheses for grouping. && binds tighter than ||.

User.filter(.age >= 18 && .active == true)
User.filter(.age < 13 || .age >= 65)
User.filter((.role == "admin" || .role == "mod") && .active == true)

Substring — .field.contains("text"): true when a String field contains the literal text. It is case-sensitive, never uses an index (the type is scanned like any other unindexed filter), and composes with the other operators. A null value never matches. Applying it to a non-String field is an error.

Post.filter(.title.contains("invoice"))
Post.filter(.published == true && .body.contains("4471"))

For ranked keyword search that does use an index, see Full-text search.

Vector similarity — .similar(.field, query, k: N, ...)

Find the nearest neighbours of a query in a Vector field. Covered in depth in Vector Search.

Post.similar(.embedding, "distributed systems", k: 10)        // text query (auto-embedded)
Post.similar(.embedding, [0.1, 0.2, 0.3], k: 10)              // raw vector query
Post.similar(.embedding, "databases", k: 10, ef: 200, rerank: 50)
ArgumentMeaning
.fieldthe Vector field to search
querya "text" string (requires @vectorize) or a raw [f32, ...] vector
k:number of results to return
ef:(optional) HNSW search width — higher is more accurate, slower
rerank:(optional) re-score this many candidates with full-precision vectors; 0/omitted = off

.similar can also follow a filter, narrowing the candidate set first:

Post.filter(.published == true).similar(.embedding, "rust", k: 5)

.similar returns a ranked result: each object carries a score — the index's distance under the field's metric (lower is closer) — and the rows come back in rank order. When the cross-encoder scored a row it also carries a rerank_score (higher is better). See Ranked results.

Full-text search — .matches(.field, "query", k: N)

Ranked keyword search over a String field declared @fulltext (see Schema → @fulltext). Sits where .similar sits: bare on a type, or after a filter or traversal that narrows the candidates.

Post.matches(.body, "invoice 4471", k: 20)
Post.filter(.published == true).matches(.body, "distributed consensus", k: 10)
User.get(1).posts.matches(.title, "+draft budget", k: 5)
ArgumentMeaning
.fieldthe @fulltext String field to search
"query"the search text (syntax below)
k:number of results to return (most relevant first)

Query syntax. The text is analyzed with the field's analyzer (lowercased, diacritics folded, split into words; under analyzer: "english" also stop words dropped and the rest stemmed), then:

FormMeaning
invoice 4471terms are OR-ed: a document matches if it contains any of them, and every term it contains adds to its score
+invoicea + prefix makes the term required
"distributed consensus"quoted words are a phrase: they must appear consecutively (the field must store positions — the default). Under english, a stop word inside the phrase leaves a gap the document must have too: "state of the art" searches for state followed three words later by art, so it matches state of the art but not state art
camera*a trailing * makes a prefix term: it matches every indexed term that starts with camera (camera, cameras, camerawork, …) and scores as one term — the type-ahead case
+"exact phrase" cam* extramodifiers combine: the phrase is required, the prefix and extra are optional

Results are ranked by BM25 (k1 = 1.2, b = 0.75): rarer terms count more, repeated terms count more with diminishing returns, and shorter documents win ties. Each returned object carries its score (higher is better) — see Ranked results.

A prefix term is analyzed like any other term before it is expanded — lowercased and folded, and under the english analyzer stemmed: cameras* searches for the stem camera, which is what the index holds. Be aware of what that means for type-ahead over a stemmed field: the index stores stems, which are often shorter than the word being typed, so a partial word that runs past the stem finds nothing until the word is complete (securit* matches nothing because security is indexed as secur; secur* and security* both match), and a prefix the stemmer shortens matches a little more than typed (agre* searches agr*). Stemming the prefix is still the better single strategy (a dictionary sweep found it matches more partial prefixes than leaving the prefix unstemmed, and it is what makes cameras* find camera), but if you need character-by-character completion, put it on a simple field. Text that analyzes to several words before the * (e-mail*) gives ordinary terms for all but the last, which becomes the prefix.

The prefix needs at least two characters after analysis (* and c* are errors — the error names the analyzed word, so 東京*, one ideograph per word under Unicode segmentation, reports the one-character prefix 京), it cannot appear inside a phrase, and an expansion of more than 64 distinct indexed terms is refused with an error asking for a longer prefix — so a one- or two-letter prefix over a large vocabulary fails fast instead of scanning half the index. The cap counts the field's whole vocabulary under the prefix, not only the terms of the candidates a preceding filter narrowed to (under security rules it counts only terms in documents the caller may read — see below). A * anywhere but the end of a word is ordinary punctuation and splits the word.

Under english, stop words are dropped from the query exactly as from the index: of my house searches for house, +of requires nothing, and a query made only of stop words (of the) returns an empty result rather than an error. A prefix term whose text is a stop word (the*, of*) is dropped the same way rather than expanded to theory, theatre, office, … — a type-ahead client sees no results at the and results again at theo, instead of results that vanish on the space that completes the word. (simple expands every prefix literally.) A query with no searchable terms (only punctuation), an unterminated quote, or a phrase against a field declared @fulltext(positions: false) is an error. So is .matches on a field without @fulltext; for an unindexed substring test use .contains instead — .contains is literal and never stems, whatever the field's analyzer. While the index of a freshly-declared (or reconfigured) field is still being built for existing objects, .matches on it is an error that reports the progress — see @fulltext.

.matches after a filter or traversal restricts the ranking to those candidates before taking the top k, so you always get up to k results from within the narrowed set.

Limits. A query text may be at most 16 KiB, carry at most 256 terms across all its clauses (a phrase counts each of its words, repeats included), and a phrase at most 32 words; past any of these the query is an error. Under the query governor every posting the search reads and every clause's walk over those postings count against the examined-rows budget (so "x x x" costs three walks of x's postings, not one), and a long postings scan stops at the query's time budget.

Under security rules a search ranks only the documents the caller may read. Each candidate — the documents holding the query's terms, narrowed by any preceding filter or traversal — is checked against the read rule first; the top-k cut, the prefix-expansion cap and the BM25 statistics (document frequency, document count and average length) are then computed over those readable candidates alone, so neither a score, nor the number of rows under k, nor a "prefix matches too many terms" error depends on documents the caller cannot see. Scores therefore differ from the same query run without rules — they are comparable within one result, not across callers. More generally, with rules on every step of a query works only on rows the caller may read: a .filter, .limit, traversal or write after a search or filter never sees an unreadable row (a write over unreadable matches is a no-op, not a permission error). A write straight after Type.get(id) is still judged by the write rule alone, so deleting an object you may delete but not read works when you name it. Paging also changes: a .limit after a filter is no longer pushed into the index scan (it would cut before the read rule), so a filter under rules examines every match and a very large match set can exceed the governor's row budget — narrow it with a more selective indexed filter. One thing rules do not hide: resource limits are charged for the work a query really does, and that includes reading index entries and rows the caller then cannot see, so whether a query is refused for exceeding the examined-rows budget can reflect how many such rows exist — a coarse count, never their contents (the refusal names the configured limit, not how much of it was used).

Ranked results

.similar and .matches produce a ranked result: the same objects as any other query, in rank order, each carrying a score. Over POST /query the score is an extra "score" member on every object; over the binary protocol the result is a Scored frame (or a Reranked frame when a cross-encoder score is present — API Reference); the Rust and TypeScript clients expose it as Row.score (and Row.rerank_score / Row.rerankScore). The score's meaning depends on the step:

Stepscore
.matchesBM25 relevance — higher is better
.similarthe index distance under the field's metric (cosine distance, squared L2, or negated dot product) — lower is closer. Always the distance, so it can be thresholded on whatever the deployment's reranking configuration

A .similar row additionally carries rerank_score — the cross-encoder's relevance, higher is better — when all of these hold: [vectorizer] cross_encoder names a model, the query was a text query (a raw-vector .similar has no text to score against), the reranker model is currently loaded (a load failure is fail-soft — see reranker_error on GET /status), and the row's object has readable source text. Rows come back in rank order either way: the rows the cross-encoder scored first (by rerank_score, descending), then any candidates it could not score (by score, ascending). A .similar step's score is only comparable across queries against the SAME field (the metric is a property of the field).

A .filter, .limit or .offset after a ranked step keeps the order and the scores; a traversal or a mutation drops them.

Mutations — .update, .delete

User.get(1).update({ name: "Alice B.", age: 31 })
Post.get(7).delete()

delete honours the @on_delete policies declared in your schema (remove / cascade / deny).

Guarded writes (compare-and-set)

A write after a filter re-checks that filter on every object, atomically with the write, so a filter on a field's old value works as compare-and-set:

Account.filter(.handle == "h" && .step == 41).update({ step: 42 })
Ledger.filter(.key == "k" && .high_water < 900).update({ high_water: 900 })
Session.filter(.token == "t" && .revoked == false).delete()

The filter selects objects on a snapshot. Each selected object is then written in its own transaction, which re-reads the object and evaluates the filter again on its current committed version:

  • If the object is gone, or no longer matches, it is skipped: not written, not returned by update, and no change event is emitted.
  • If it still matches, the write commits only if no other transaction has written the object since that read. If one has, the write is retried from a fresh read and a fresh check; the database does this internally, so contention shows up as a skipped object, not as an error.

So any number of concurrent statements guarded on the same old value apply exactly once: one writes the object, and every other one finds it no longer matches. The caller tells which happened from the result: update returns only the objects it wrote (an empty list when it wrote none). delete, link and unlink return no rows, so to learn whether a guarded delete applied, re-read the object (or guard an update instead).

The guarantee covers .update, .delete, .link and .unlink, and the predicates it re-checks are the ones about the written objects themselves: the source filter and every .filter() after the last traversal. .limit, .offset, .similar and .matches in between keep them. A filter before a traversal constrained other objects, which the write does not lock, so it is not re-checked: User.filter(.active == true).posts.delete() deletes the posts of users that were active when the filter ran.

.limit picks the objects before the re-check, not after it. In the queue-claim pattern Job.filter(.status == "queued").limit(1).update({status: "taken"}), a statement that loses the race returns no rows; it does not move on to the next queued job. Retry the statement to claim another.

Writes without a filter behave as before: T.get(id).update(...) writes the object as it is now and fails if it does not exist; T.update(...) (every object) and T.get_many([...]).update(...) skip an object deleted since the read.

The guarantee is per object, not per statement. A statement that writes several objects runs one transaction per object, so another reader can see some of them written and others not yet, and an error part-way (a unique-constraint violation, say) leaves the objects before it written. When several writes must land together, use a transaction.

A write gives up with a write-conflict error only after many consecutive conflicts on the same object (other writers changing it continuously while it still matches); retrying the statement is then safe.

Security rules are checked atomically with the write

Under security rules, the update and delete rules (and the update rule that gates .link / .unlink on the source object) are decided inside each object's write transaction, on the version of the object that write is based on — for point writes (T.get(id).update(...)) as well as filtered ones. Everything the rule reads joins that transaction's conflict check:

  • the object's own fields (resource.ownerUid);
  • the edges of every relation the rule follows (resource.editors, including @inverse fields) — an edge added, removed or replaced by another writer counts;
  • the fields of the linked objects it reads (resource.editors.uid).

If another transaction changes any of these after the write's snapshot, the write is retried from a fresh read and the rule is evaluated again. So a write lands only if the rule allowed it on the state it actually committed over: revoking ownership, removing an editor or adding someone to a deny-list takes effect for every write that commits after the change, with no window in between. A denied object is reported as a permission error and nothing is written for it (no field, index, edge or change event).

The rule is also checked once on the query's snapshot before any object is written, so a statement the rules refuse on any of its objects is normally refused whole. Like the compare-and-set guarantee above, the atomic check is per object: if a rule input changes while a multi-object statement is running, the objects written before the change stay written and the statement stops with a permission error at the first object the rule now refuses.

A create rule sees only the incoming fields (request.*), which no other writer can change, so it has nothing to race.

Create or remove a relationship between objects. Edge-field values (if the relationship declares any) go in the optional object literal.

User.get(1).link(User.get(2))                            // user 2 becomes a friend of user 1
User.get(1).link(Movie.get(42), { rating: 4.5 })         // with an edge field on favorite_movies
User.get(1).unlink(User.get(2))

The source is whatever the query has reached when .link runs. User.get(1).link(...) links from user 1; a traversal before it moves the source, so User.get(1).friends.link(User.get(2)) links each of user 1's friends to user 2, not user 1. The target is always written as Type.get(id).

The link is made on the source object's relation field to the target's type. When the source type has only one such field, it is found automatically. When it has several (a parent and a related, both pointing to Page), name the field first; the unnamed form is then an error that asks you to:

Page.get(7).link(.parent, Page.get(3))
Page.get(7).link(.related, Page.get(9), { weight: 0.5 })
Page.get(7).unlink(.parent, Page.get(3))

A named field must be a relation field of the source type that points to the target's type.

An @inverse field can't be linked or unlinked directly: it has no edges of its own, and shows the links made through the forward field it names. Link from the forward side instead. With parent: Page and children: [Page] @inverse(Page.parent), to make page 7 a child of page 3:

Page.get(7).link(.parent, Page.get(3))     // page 3's children now include 7
Page.get(3).link(.children, Page.get(7))   // error: link from the other side

An inverse field still counts when the unnamed form looks for a field, so a type with both parent and children must name the field.

Transactions — transaction { ... }

A transaction block is an ordered list of writes that commits as one: every write or none, at one commit version.

transaction {
    let $m = Message.create({ subject: "Hello", step: 1 });
    MessageContent.create({ body: "…", message: $m });
    Message.get($m).link(.labels, Label.get(7), { weight: 0.5 });
    Thread.get(9).filter(.rev == 3).update({ rev: 4, last: $m });
    Draft.get(12).delete();
}

Each statement is one point write, separated by ;:

StatementWrites
T.create({ ... }), let $name = T.create({ ... })a new object; let names it for later statements
T.get(id).update({ ... })the object's fields
T.get(id).delete()the object, with its @on_delete policies
T.get(id).link([.field,] U.get(id) [, { edge fields }])an edge, as .link
T.get(id).unlink([.field,] U.get(id))an edge, as .unlink

Names. A new object's id is not known until the transaction runs, so a create bound with let $name is referred to as $name: in place of an id (Message.get($m), Label.get($m)), or as a field value, which then holds the new object's id (message: $m sets the message relation). A name must be bound once, by a create that comes earlier in the block; anything else (an unknown name, a name used before its create, a name bound twice) refuses the whole block before it runs.

Guards. .filter(...) steps between .get(id) and the write (ANDed together) are the statement's guard: it must hold on the object as the transaction sees it, after the earlier statements' writes, or the whole transaction aborts with a transaction guard rejected error (409 over HTTP). This is compare-and-set across several objects. Without a guard, a statement whose object does not exist aborts the transaction with object not found (404), an unlink included, although a single .unlink statement of a missing source does nothing.

All or nothing. If any statement fails (a @unique value already taken, a missing object, a guard or a security rule that refuses it, a wrongly typed value), nothing is applied. Every statement sees the writes of the statements before it, and a reader outside sees either none of them or all of them. A transaction that conflicts with a concurrent writer is retried internally from a fresh snapshot, like any write.

Change events. Subscribers see one event per changed object, carrying the transaction's commit version and the object's final state: a create followed by an update of the same object in one block is a single create event. A write origin (see the API reference) is stamped on every event of the block.

Security rules. Each statement is checked against its rule as a single write is, inside the transaction, so a rule sees the earlier statements' writes (a link from an object created earlier in the block is judged on that new object). A denial anywhere refuses the whole block with permission denied (403). Each created or updated object comes back as that statement left it, and only if the read rule lets the caller read it in that state; otherwise its result gives the id alone.

Limits. A block holds at most 10,000 statements, and each one counts toward the query governor's row budget. Over the network, the request size limits of POST /query and the binary protocol apply.

Result. One result per statement, in order: the id (and object) of each create and update, and for each unlink whether there was an edge to remove. Over HTTP it is the "transaction" member of the reply; the clients also take the list as data rather than query text (see Write transactions).

Pagination — .offset, .limit

User.filter(.age > 18).limit(10)
User.filter(.age > 18).offset(20).limit(10)

Apply offset before limit. Writing .limit(N).offset(M) is rejected — that order silently drops rows and is treated as a mistake.

Ordering and pages — .order_by, .after

Message.filter(.place == "lobby").order_by(.created, desc).limit(50)
Message.filter(.place == "lobby").order_by(.created, desc).after("AQAAAAAA…").limit(50)
User.order_by(.name)

.order_by(.field) sorts the rows ascending; .order_by(.field, desc) descending. The result is a page: the rows, plus a next_cursor when more rows follow (see the API Reference). Pass that cursor to .after("…") to read the next page. The last page has no cursor.

  • Where it goes. .order_by comes after the filters, traversals and writes that build the set, and ends the pipeline: only .after (directly after it), then .offset and .limit, may follow. It cannot follow .similar or .matches, whose rows are ordered by score, and takes one field. The field must be a scalar other than Json.
  • Order. Nulls and missing values first ascending, last descending; ties by id in the same direction. The rules are in the schema reference.
  • Cursors are opaque strings. A cursor names a position, not a row: rows written or deleted between pages are handled as you would expect. The next page starts right after where the cursor's row was, even if that row is gone; a row inserted before that position is not seen and one inserted after it is. A cursor from a different ordering (type, field or direction) is refused, as is a malformed one, with a 400. A cursor carries its row's value of the ordering field, so ordering by a long string field gives a cursor about as long as that string; order by a short field (a time, a number) when cursors travel in URLs.
  • Cost. With a type-level @index that matches the query, a page reads about offset + limit + 1 entries however large the set is. Without one, the query reads every row of its set, then sorts, as a filter without an index does. Prefer .after to a growing .offset for deep pages: an offset still reads the rows it skips.
  • Security rules. Every row is checked against the read rule before it counts, so a page holds limit readable rows when that many exist, and the cursor never points into rows the caller cannot read.

Literals

KindExamples
String"hello"
Integer42, -10
Float3.14, -2.5
Booltrue, false
Nullnull
Vector[1.0, 2.0, 3.0]
JSON{ "k": 1, "tags": ["a", "b"] }

How a literal is interpreted depends on the field's declared type — the language has no inline type annotations. A string literal becomes a DateTime when written to a DateTime field, base64-decodes into a Bytes field, and a raw JSON object/array literal is stored in a Json field:

Event.create({
  created: "2026-06-20T12:00:00Z",    // DateTime  (RFC 3339; or an integer epoch-millis)
  blob:    "aGVsbG8=",                // Bytes     (base64)
  meta:    { "k": 1, "tags": ["a"] }  // Json      (raw JSON value)
})

These read back faithfully — created as an RFC 3339 string, blob as base64, meta as inline JSON. A malformed value (a non-RFC-3339 DateTime, invalid base64, or unparseable JSON) is a clear error, not a silent default.

Examples

// Create
User.create({ name: "Alice", email: "alice@example.com", age: 30 })

// Read by id and by filter
User.get(1)
User.filter(.reputation >= 100 && .active == true).offset(0).limit(20)

// Traverse
User.get(1).friends.posts.filter(.title != "")

// Mutate
User.get(1).update({ reputation: 150 })
Post.get(7).delete()

// Relate
User.get(1).link(.favorite_movies, Movie.get(42), { rating: 5.0 })

// Vector search, narrowed by a filter
Post.filter(.published == true).similar(.embedding, "vector databases", k: 10, rerank: 50)

Vector Search

Vectors are a native field type in rhypedb, not an add-on. You declare a Vector<N> field, optionally index it for approximate nearest-neighbour (ANN) search, and optionally have the server compute embeddings for you from text. Then you query it with .similar(...).

Declaring a vector field

type Post {
    body: String
    embedding: Vector<384>
}

Vector<N> stores an N-dimensional f32 vector. The dimension N is fixed by the schema. On its own, this field stores whatever vectors you write to it; to search it efficiently you add an index.

Two ways to get vectors in

1. Bring your own vectors

Compute embeddings in your application and write them like any other field:

Post.create({ body: "hello world", embedding: [0.12, -0.04, 0.98, ...] })

The vector literal must have exactly N elements. For bulk ingestion of precomputed vectors, the binary TCP protocol has a dedicated VectorBatch message (see the API Reference).

2. Server-side embedding with @vectorize

Let the server embed text for you. Point @vectorize at a String field and a model:

type Post {
    body: String
    embedding: Vector<384> @vectorize(source: "body", model: "all-MiniLM-L6-v2")
}

Now you only supply the text — the server fills in the vector on create and re-embeds on update:

Post.create({ body: "distributed systems are hard" })

The embedding is computed asynchronously by a background worker. Every write that sets the source field queues one — create, create_batch, and single- or multi-object update, over HTTP or TCP.

An update that doesn't touch the source field does not re-embed. The vector depends only on the source text, so an update that leaves body out keeps the existing vector as it is. Writing the source field again, even with the same text, does re-embed it.

The embedding job is recorded in the same transaction as the write, including every object a multi-object write transaction creates or updates. If the write commits, the object is durably marked as owing a vector, even if the process dies a moment later before the worker has run; the job is picked up again when the database next opens. If the object is rewritten while an older job for it is still in flight, the older job's vector is discarded and only the newest text is embedded.

Embedded users (calling rhypedb-engine directly) get the same behaviour by attaching their Vectorizer to the database once, before writing: db.attach_vectorizer(Arc::clone(&vectorizer)). There is no need to call Vectorizer::enqueue per write. A write made while no vectorizer is attached is still marked as owing a vector, and the next vectorizer opened over the database embeds it.

Which fields get embedded follows the database's current schema, including after a schema reload or a rename_field. A vectorizer builds its indexes when it is created, so if a reload adds a @vectorize field the running vectorizer doesn't know, writes to it are held as pending, not dropped: the vectorizer counts them in IndexingStatus::awaiting_reopen, logs the field once, and embeds them after the next restart.

GET /status reports how many embeddings are pending, how many vectors each index holds, and whether the embedding model is currently loaded:

{
  "vectorizer": {
    "pending": 3,
    "indexes": [ { "name": "Post.embedding", "vectors": 1000 } ],
    "model_loaded": true,
    "model_error": null
  }
}

model_loaded is true once the model has loaded successfully at least once. model_error carries the most recent load-failure message while one is in effect (for example, the model is still downloading, or this binary was built without the fastembed feature) and goes back to null as soon as a load succeeds. A model-load failure does not lose or fail any pending jobs — they stay queued and are retried with a backoff; see Embedding pipeline settings below.

The Vector<N> dimension must match the model's output size (e.g. all-MiniLM-L6-v2 produces 384-dimensional vectors).

Embedding pipeline settings

The background embed worker (and the query-time embedder used by a text .similar) can be tuned via the [vectorizer] table in rhypedb.toml (see Running rhypedb):

KeyDefaultWhat it costs
batch_size32Jobs claimed and embedded per pass. Higher batches trade memory for throughput — at 512-token texts, a batch of 256 (the old hard-coded value) could take a desktop process to 15 GB resident; 32 keeps peak memory bounded.
max_length256Token limit per text. MiniLM/BGE-small were trained at 256; attention memory grows with the square of this, so raising it is expensive.
intra_threadshalf the CPU coresONNX Runtime intra-op threads used by each lazily-loaded model.
quantizedtruePrefer the int8-quantized model variant when fastembed has one (all-MiniLM-L6-v2, bge-small-en-v1.5); smaller and faster, a small quality cost. Base/large BGE models have no quantized variant and always use fp32 regardless of this setting.
cpu_arenafalseUse ONNX Runtime's CPU memory arena. With it, a loaded model keeps every block it has allocated and never shrinks: about 600 MB of memory for all-MiniLM-L6-v2, against roughly 100–170 MB without it. Query embedding speed is the same either way; batch embedding (backfills, re-embeds) may be somewhat faster with the arena on. Turn it on when bulk-embedding throughput matters more than memory.
cache_dirfastembed's own defaultWhere downloaded model files are cached on disk.
cross_encoder"off""off" disables cross-encoder reranking of .similar text search; any other string names the reranker model to turn it on with (see Cross-encoder reranking below). A second model, off by default.
rerank_candidatesmin(k * 3, 48)ANN candidates the cross-encoder scores per text query — one forward pass each, so this is the dominant query cost when reranking is on. Never below k.
reranker_dirdownloadLoad the reranker from a local directory (model.onnx plus the four tokenizer files) instead of downloading it — for bundled deployments that must not touch the network.
reranker_fp32falseUse the full-precision bge-reranker-base (~1.1 GB) instead of the int8-quantized build (~280 MB, equivalent quality).

If the model fails to load — a network hiccup mid-download, a cold cache on first boot, or simply the time it takes to download and initialize a ~100MB+ ONNX model — the background worker does not fail or drop the affected jobs. It puts them back on the queue, records the failure under vectorizer.model_error on GET /status, and retries with an exponential backoff (starting at 2s, doubling up to a 60s cap) until a load succeeds, at which point model_error clears and the backoff resets. A .similar text query made while the model is unavailable gets a clear ModelUnavailable error rather than panicking: the first query after a failure attempts the load itself (and waits for that attempt, which for a download can be the network timeout); queries during the backoff window are refused immediately without retrying, so a known-bad model doesn't cost every query a download attempt. Embedded callers driving process_pending see the same failure as an Err(ModelUnavailable) when a batch could not be embedded at all (its jobs are re-queued), so a "loop until 0" driver can back off rather than spin.

Upgrading from a build before this setting existed: the cross-encoder used to run by default and was opted out of with RHYPEDB_DISABLE_RERANK. It is now off unless you set cross_encoder — a deployment that relied on the old default silently loses reranking after upgrading (queries still succeed; GET /status shows reranker_loaded: false). Add [vectorizer] cross_encoder = "bge-reranker-base" to keep it. RHYPEDB_DISABLE_RERANK is no longer read (the server warns at startup if it, or RHYPEDB_RERANKER_DIR with the cross-encoder off, is set).

Cross-encoder reranking

.similar text search can optionally run a SECOND pass over the ANN candidates: a cross-encoder model scores each candidate's source text directly against your query text, which typically ranks results more accurately than vector distance alone — at the cost of one extra model (~280MB) and one forward pass per candidate. It is off by default (cross_encoder = "off"); turn it on by naming the reranker model — today exactly one is supported:

[vectorizer]
cross_encoder = "bge-reranker-base"

This is a separate knob from the per-query rerank: argument (see Searching — .similar below) — rerank: N always means "re-score N candidates against the exact f32 vectors," a cheap step that is always available. The cross-encoder runs in addition to that, whenever it is turned on here AND the field has a readable @vectorize source text; a raw-vector .similar query never uses it (there is no query text to score against). Like the embedder, a cross-encoder load failure is fail-soft: .similar falls back to returning the ANN/rescored order rather than erroring, and the failure is visible under vectorizer.reranker_error on GET /status (vectorizer.reranker_loaded mirrors model_loaded).

The reranker is tuned by the [vectorizer] keys rerank_candidates, reranker_dir and reranker_fp32 (table above; a downloaded reranker shares cache_dir with the embedding models). Three environment variables predate those keys and are still honoured as fallbacks when the key is absent — RHYPEDB_RERANK_CANDIDATES, RHYPEDB_RERANKER_DIR, RHYPEDB_RERANKER_FP32 — prefer the config keys. RHYPEDB_DEBUG_RERANK (any value) logs the search path taken (brute-force / ANN / rerank pool) to stderr.

Indexing for search — @index(hnsw, ...)

To run similarity search at scale, add an HNSW index:

embedding: Vector<384> @vectorize(source: "body", model: "all-MiniLM-L6-v2")
                       @index(hnsw, metric: cosine, quantization: turboquant_4bit, m: 16, ef_construction: 200)
ParameterValuesDefaultNotes
metriccosine, l2, dot_productcosinedistance function
quantizationturboquant_2bit, turboquant_3bit, turboquant_4bitturboquant_4bitin-index compression
m≥ 1engine defaultgraph fan-out
ef_construction≥ 1engine defaultbuild-time accuracy/effort

The index stores quantized vectors (TurboQuant, 2–4 bits per component) for speed and a small memory footprint; the raw f32 vectors are kept losslessly at rest and are what get re-ranked and what survive a backup or logical export. quantization: none is rejected — there is always an index-side quantization.

The index is persisted as hnsw_<field>.bin in the data directory and rebuilt from the raw vectors if missing or stale (for example, after a logical import).

Searching — .similar

Post.similar(.embedding, "vector databases", k: 10)

Arguments:

ArgumentMeaning
.fieldthe Vector field to search
querya "text" string (only if the field has @vectorize) or a raw [f32, ...] vector
k:number of nearest neighbours to return
ef:(optional) HNSW search width — higher = better recall, more work
rerank:(optional) re-score this many ANN candidates with full-precision vectors before returning the top k

A text query is embedded with the same model as the field's @vectorize. A raw-vector query works on any vector field and must match the field dimension. (Text after // below is a note for the reader, not query syntax.)

// text query (field must have @vectorize)
Post.similar(.embedding, "distributed consensus", k: 5)

// raw vector query
Post.similar(.embedding, [0.01, 0.42, -0.17], k: 5)   // shortened: give the field's full N elements

// tune recall: widen the search and rerank the top 50 with exact vectors
Post.similar(.embedding, "distributed consensus", k: 10, ef: 200, rerank: 50)

// narrow the candidate set with a filter first
Post.filter(.published == true).similar(.embedding, "rust async", k: 10)

Every .similar result is ranked and each carries a score, read as Row.score: the index's distance under the field's metric (lower is closer), with results nearest-first. When cross-encoder reranking is on and the reranker scored a row, that row additionally carries rerank_score (higher is more relevant) and the scored rows come back most-relevant-first; score stays the distance, so the two never share a column. Rows the cross-encoder could not score (a raw-vector query, the reranker failed to load, or the object has no readable source text) have no rerank_score; see Ranked results for the exact rules. See Ranked results and, for keyword search over the same objects, .matches.

Under security rules .similar searches only rows the caller may read. A bare Type.similar(...) lists the type and checks each row against the read rule before searching, so it is subject to the governor's scan budget like any listing — on a large type, narrow first with an indexed filter (Post.filter(.ownerUid == "u1").similar(...)). Up to 10 000 readable candidates are searched exactly; beyond that the approximate index is filtered to the readable set, which (as for any large filter) can return fewer than k rows.

Tuning recall vs. latency

Three knobs trade accuracy for speed:

  • quantization (schema, per field) — more bits = higher base recall, larger index. turboquant_4bit is a good default; drop to 3bit/2bit to shrink the index and lean on rerank.
  • ef (per query) — a larger HNSW search width explores more of the graph. Raises recall at a latency cost.
  • rerank (per query) — pull a larger candidate pool from the (quantized) index, then re-score those candidates with the exact f32 vectors and return the best k. This recovers most of the precision lost to quantization for a modest cost.

A common high-recall pattern is a moderate ef with rerank set to a few × k:

Post.similar(.embedding, "query text", k: 10, ef: 200, rerank: 50)

Server-wide defaults for ef and rerank can also be set via the RHYPEDB_EF and RHYPEDB_RERANK environment variables (see Running rhypedb); they apply only to queries that omit the corresponding argument, and an explicit per-query ef:/rerank: (including rerank: 0 to force rerank off) always overrides them.

What's preserved across backups

Because the raw f32 vectors are stored losslessly, both a physical backup and a logical export preserve your vectors exactly. A logical export ships the raw vectors and the HNSW graph is rebuilt on import (the graph itself holds only lossy quantized codes and is cheap to regenerate). See Backup & Recovery.

Schema Migrations

Changing the schema of a database that already holds data is a real operation with rules. rhypedb sorts schema changes into four kinds, by how much work and risk each carries:

ChangeHow it happensCost
Add a field or typeImplicit — update the schema and reloadFree, instant
Remove a field or typeImplicit, but opt-in and one-wayInstant (data tombstoned)
Rename a field or typeExplicit migration verbInstant (catalog only)
Change a field's typeExplicit online migration with a converterProportional to row count

The reason renames and type changes need explicit operations is that they cannot be inferred safely from a schema diff: a rename looks identical to "drop the old field, add a new one," and a type change requires rewriting every stored value. Adds and removes have no such ambiguity.

Adding fields and types

Additive changes are the easy case. Add the field or type to your schema file and apply the new schema — existing objects simply don't have the new field (it reads back as absent/null until set), and existing ids are never renumbered.

To apply a new schema to a running server without a restart, POST /admin/reload with the new SDL (see Running rhypedb); otherwise restart the server pointing at the updated schema file.

Fields are not "required," so adding one to a populated type is always safe.

Removing fields and types

Removal is also driven by the schema diff, but it is refused by default and is one-way. Retiring a field or type tombstones it (the catalog entry is marked retired; the bytes in existing object blobs age out as objects are rewritten) and a retired name cannot simply be re-added. Because it is destructive, it requires an explicit opt-in at the engine level (allow_schema_shrink) rather than happening silently on reload.

Renames

A rename preserves the underlying field/type identity and all its data and indexes — only the name in the catalog changes, in a single atomic step. Renames are expressed as migration verbs (rename_type, rename_field) through the engine's migration API.

Changing a field's type (online migration)

This is the substantial one: changing a field's encoding — say i64 → f64 — across a table that may hold millions of rows, while the server keeps serving reads and writes. It runs as a driven, multi-phase online migration and is fully exposed over the admin API and the CLI.

The pieces

  • A converter: a named, versioned function that turns an old value into the new type. The server ships a set of built-in converters (it prints the available list in its startup banner — e.g. widen_int_to_f64). User-supplied/network-supplied converters are not yet available; you migrate using a built-in converter that matches your change.
  • A target type: the new scalar type for the field.
  • Tuning: chunk size, parallelism, an error policy, and an optional dry run.

Running one with the CLI

rhypedb-cli --admin-token "$RHYPEDB_ADMIN_TOKEN" \
  migrate start --type User --field score --to f64 \
  --converter widen_int_to_f64 --chunk 1000 --parallel 4 --policy stop

This returns a migration id. Watch its progress:

rhypedb-cli migrate status 1            # list all, or detail for id 1
rhypedb-cli migrate events 1            # live event stream until it settles

And control it:

rhypedb-cli migrate pause 1
rhypedb-cli migrate resume 1
rhypedb-cli migrate cancel 1            # only before cutover
rhypedb-cli migrate cutover 1           # force cutover for a parked-but-done plan

migrate start flags:

FlagMeaning
--type, --fieldthe field to migrate
--totarget scalar type (f64, i64, String, …)
--converter, --converter-versionthe named converter and its version
--chunkobjects converted per commit (0 = default)
--parallelnumber of partition workers
--policystop (default), skip, or quarantine — what to do on a converter error
--quarantine-capmax quarantined rows before failing (with quarantine)
--dry-runrun a full preflight that writes nothing

The same operations exist as admin HTTP endpoints (POST /admin/migrations, GET /admin/migrations/{id}, .../pause|resume|cancel|cutover, .../events); see the API Reference.

What happens under the hood

  1. Arm. A double-write hook is installed so every live write to the field is also carried forward into the new encoding while the migration runs.
  2. Backfill. Worker threads convert existing rows in chunks, committing durably and recording per-partition cursors (so the work is crash-resumable).
  3. Cutover. Once every row is converted, the new encoding is promoted to the live field, indexes are reconciled, and the hook is disarmed. This is the point of no return — cancel is refused from here on.
  4. Done. The migration settles as completed.

Three things to know

  • Cancel is lossless before cutover, impossible after. Cancelling rolls back the in-progress conversion (the source field was never overwritten during backfill). Once cutover starts promoting the converted values, there's nothing to roll back to.
  • It survives restarts. If the server stops mid-migration, it auto-resumes on startup from the durable per-partition cursors. After a change_field_type cutover completes, the server hot-reloads its in-memory handle automatically so it serves the new type without a restart.
  • Pick an error policy up front. stop (default) fails the whole migration on the first converter error. skip counts and skips bad rows. quarantine sets bad rows aside so you can inspect and retry them (migrate quarantine list <id> / migrate quarantine retry <id>) before cutover proceeds. --dry-run does a full conversion pass that writes nothing, so you can validate before committing.

Running rhypedb

This page covers running and operating a rhypedb-server in practice: configuration, the data directory, authentication, hot reload, compaction, and monitoring.

Upgrading

Opening a database with a release that changes what an analyzer does rebuilds every @fulltext index in the background, into a fresh generation. .matches on a field reports it as still building until its rebuild finishes (GET /status shows the progress); everything else, including writes, is unaffected, and nothing is lost. The 0.1 release that added the per-value word cap (simple/2, english/3) is such a change, so plan for search on a large corpus to be briefly unavailable after that upgrade.

The release that shortened full-text index keys (GH #98) rebuilds every @fulltext index once in the same way, on its first open of a database whose indexes an earlier release built. The new keys take roughly 25 bytes less per indexed word of each document, so the index takes about a third less space. Opening that database with an earlier release afterwards, even before the rebuild has finished, rebuilds the indexes again in the earlier form, and the newer release rebuilds them back on its next open, removing the rows the earlier release left. Results are the same throughout. One case leaves rows behind: if you remove a field's @fulltext directive while running the earlier release, that field's newer-form rows stay on disk (unused) until the directive is added back.

A schema that uses @indexed(cover: false) can't be opened by a release older than that parameter: its schema parser rejects it. Remove the parameter, and open the database once with the newer release, before you downgrade.

Starting the server

rhypedb-server --schema schema.rhype --data-dir /var/lib/rhypedb

Command-line flags

FlagDefaultMeaning
-s, --schema <path>(required, except with --restore-from)Path to the SDL schema file. Optional when restoring (the snapshot carries its own authoritative schema).
-d, --data-dir <path>./rhypedb-dataStorage directory (created if absent).
--restore-from <dir>offRestore a physical backup snapshot into --data-dir before serving (see Restore on boot). Idempotent.
--restore-forceoffAllow --restore-from to overwrite an existing, different database in --data-dir.
--listen <addr>127.0.0.1:4200HTTP listen address.
--tcp-listen <addr>127.0.0.1:4201Binary TCP listen address.
--no-syncoffSkip the WAL fsync at commit. Faster, but a power loss can drop the last few writes. Equivalent to Postgres fsync=off. Don't use in production.

Environment variables

VariableMeaning
RHYPEDB_ADMIN_TOKENBearer token that gates all /admin/* endpoints. If unset, admin routes return 403.
RHYPEDB_EFDefault HNSW search width (ef) for .similar queries that omit ef: (must be ≥ 1; overridable per query). An invalid value is ignored with a warning.
RHYPEDB_RERANKDefault rerank pool size for .similar queries that omit rerank: (0 = off; overridable per query). An invalid value is ignored with a warning.
RHYPEDB_RESTORE_FROMSnapshot directory to restore on boot (same as --restore-from; the flag wins if both are set).
RHYPEDB_RESTORE_FROM_FORCE1/true/yes/on ⇒ same as --restore-force.
RHYPEDB_CONFIGPath to a TOML config file (same as --config; the flag wins if both are set).
RHYPEDB_BLOCK_COMPRESSIONnone (default) or lz4 — per-block SST compression for new files (same as --block-compression).

Configuration file

Instead of (or alongside) flags and env vars, point the server at a TOML config file with --config <path> or RHYPEDB_CONFIG. There is no auto-discovery — the file is loaded only from the explicit path.

Precedence (most-specific wins):

CLI flag  >  env var  >  config file  >  built-in default

So a config file is a fallback layer: anything you also pass as a flag or env var overrides it, and with no --config the server behaves exactly as before.

The keys map one-to-one to the flags/env vars (flat, snake_case):

KeyTypeDefaultEquivalent flag / env
schemapath(required unless restore_from)--schema
data_dirpath./rhypedb-data--data-dir
listenstring127.0.0.1:4200--listen
tcp_listenstring127.0.0.1:4201--tcp-listen
no_syncboolfalse--no-sync
admin_tokenstring(unset → admin off)RHYPEDB_ADMIN_TOKEN
efint ≥ 1(heuristic)RHYPEDB_EF
rerankint (0 = off)offRHYPEDB_RERANK
restore_frompath(off)--restore-from
restore_from_forceboolfalse--restore-force
cache_max_entriesint ≥ 1256(file only)
graceful_drain_secsint ≥ 120(file only)
worker_quiesce_budget_secsint ≥ 110(file only)
block_compression"none" | "lz4""none"--block-compression / RHYPEDB_BLOCK_COMPRESSION

Background embedding pipeline. A [vectorizer] TABLE (not a flat key) tunes the embed worker used by @vectorize fields: batch_size, max_length, intra_threads, quantized, cpu_arena, cache_dir, plus cross_encoder ("off", the default, or a reranker model name) to turn on cross-encoder reranking of .similar text search and its knobs rerank_candidates, reranker_dir, reranker_fp32 — all optional, config-file only, no flag/env in this version. See Embedding pipeline settings for defaults and what each knob costs.

SST block compression. block_compression controls how newly written SST files (memtable flushes and compactions) store their data region. "none" (the default) keeps the uncompressed layout, whose reads are zero-copy views into the memory-mapped file. "lz4" compresses each ~16-entry block with LZ4 — roughly 3.8× smaller files, so more of the working set fits in the OS page cache — but it is opt-in because a benchmark showed it costs ~3.7× on a 1M-row multi-hop graph traversal: each scattered cover-blob read decompresses a whole block to pull a single entry, which doesn't amortize the way a sequential scan does. Turn "lz4" on where disk size / cold-cache density matters and reads are scan-heavy or rare (range/filter scans amortize the block decompress well); keep "none" for point-lookup- and traversal-heavy workloads. Both formats are always readable regardless of this setting — it only affects new writes — so a data directory can hold a mix, and changing the value lets natural compaction migrate files to the new format over time (no offline rewrite needed). An unrecognized value is warned about and ignored (falls back to the lower layer / the default).

Validation. A typo'd or unknown key, invalid TOML, a wrong-typed value (e.g. ef = "x"), or an unreadable --config path is a fatal startup error (exit 1) that names the file. Out-of-range tuning values (ef/rerank/cache/drain below their minimum) are warned about and ignored — they fall back to the lower layer or the default, so a fat-fingered tuning hint never bricks an unattended start. The boolean flags (--no-sync, --restore-force) can only force a value on; to keep one off, leave it unset everywhere.

Relative paths (schema, data_dir, restore_from) resolve against the server's current working directory, not the config file's location — prefer absolute paths in a config file. The effective resolved config is logged at startup (the admin_token is never printed — only whether admin is enabled). Keep any config file containing admin_token out of version control. A commented example with every key and its default ships at docs/examples/rhypedb.toml.

Restore on boot

For a managed deployment (where the platform controls the instance lifecycle and fetches backups from object storage), the server can restore a physical backup snapshot into its --data-dir at startup, before it opens the database or binds a listener, then serve normally:

rhypedb-server --restore-from /restore/snapshot --data-dir /var/lib/rhypedb

The typical scale-to-zero wake flow is: the platform stops the instance (a clean SIGTERM flushes the memtable and saves the HNSW snapshots), fetches a backup from object storage to a local path, and starts the server pointed at it.

What it does, in order: validate the snapshot's MANIFEST.json (a typo'd or incomplete source is refused before anything is cleared) → take the single-writer data-dir lock → clear stale LSM data → copy the SSTs, WAL, schema.rhype, and the hnsw_*.bin index snapshots → open and serve.

Key points:

  • The snapshot's schema wins. A restored data dir carries its own schema.rhype, which is authoritative (the SSTs were written for it). --schema is therefore optional under --restore-from; if you pass it, it must match the snapshot's schema exactly or startup fails.
  • The HNSW snapshots travel with the backup. Restoring the hnsw_*.bin files lets a vector index wake in ~hundreds of ms instead of rebuilding from the LSM (which is multi-second per 100k vectors — see the cold-start benchmark). A missing index snapshot is a warning, not an error (it rebuilds on open).
  • Idempotent. --restore-from records the snapshot identity, so a restart with the same snapshot already in place is a no-op — you can leave RHYPEDB_RESTORE_FROM set across restarts without re-clobbering live data.
  • Overwrite protection. Restoring over an existing, different database requires --restore-force (or RHYPEDB_RESTORE_FROM_FORCE=1). A stale LOCK file from a crashed instance does not count as existing data.
  • Same host only. Like all of rhypedb, the single-writer lock is same-host; the managed platform must guarantee the previous instance is stopped first.

This is the in-server counterpart to the offline rhypedb-cli restore, which remains available for manual use.

The data directory

A data directory is self-contained. After running, /var/lib/rhypedb contains:

EntryWhat it is
sst/LSM-tree sorted-string-table files (the bulk of the data), and MANIFEST, which records the live ones and the ones a compaction superseded (see SST manifest).
wal.logWrite-ahead log for durability between flushes.
wal.log.tmpPresent only briefly: the empty WAL a flush writes before renaming it over wal.log. One left by a failed flush or a crash is removed at the next open; older releases ignore it.
schema.rhypeThe schema (written here by restore/import; the server otherwise reads --schema).
hnsw_<field>.binPersisted HNSW vector index, one per indexed Vector field. Rebuilt from the raw vectors if missing or stale.
LOCKThe single-writer advisory lock (see below). It also carries the token that tells the SST manifest whether anything else has opened the directory since it was written.

One writer per data directory

A data directory must be opened by one process at a time. Two writers on one directory would corrupt the LSM, so on open the server takes an advisory lock (flock) on the LOCK file, held for the lifetime of the process and released automatically when it exits.

If you try to start a second server — or run an offline tool like rhypedb-import or restore — against a directory that's already in use, it fails fast:

data directory is locked: /var/lib/rhypedb/LOCK is locked (held by pid 1234 on host db-1). Stop the server or other tool using this data directory before opening it.

This is a same-host guard. It does not make it safe to point two machines at the same shared/network-mounted directory — never do that. (On a network filesystem the lock may not engage at all; in that case rhypedb still detects a second opener at the next write and halts loudly rather than corrupting data, but the supported model is one host, one local data directory.)

SST manifest

sst/MANIFEST lists the live SSTs in read order and, as obsolete, every SST a flush or compaction superseded whose delete has not been seen to succeed (a compaction's inputs can outlive it on disk: a platform may refuse to delete a file a reader still has mapped, or the process may stop between the swap and the deletes). An obsolete SST is never loaded again: after a compaction that dropped a delete marker, loading it would bring the deleted rows back. It is deleted at the next opportunity, and at the next open.

On open, rhypedb compares the token the manifest was written under with the one LOCK carries. Every open by a release with the manifest carries that token forward. An opener that does not (an older release, or a copy of the directory made without LOCK) breaks it, and the next open treats the manifest as possibly stale. A restore made with this release's rhypedb restore is safe: it removes sst/MANIFEST and carries the token forward, so nothing is left to mismatch.

  • No manifest (a directory from a release before it): every *.sst is live, as before, and a manifest is written. Existing data opens unchanged.
  • Tokens match (only this release has opened the directory since): exactly the listed SSTs are loaded. An unlisted *.sst is this release's own unfinished output (its rows are still in the WAL, or in the SSTs it was merging) and is deleted. A listed SST that is missing was lost outside rhypedb, and open fails rather than drop its rows (see below).
  • Tokens differ (something else may have changed the directory): every SST the manifest does not list as obsolete is kept and loaded, including ones it has never heard of, and a listed SST that is gone is assumed to have been compacted away. An obsolete SST is still deleted, provided it is still the very file that was listed (same length, modification time and CRC of its last 4 KiB): an older release may have reused its name for new data. See the limits below.

Each decision other than a routine delete is logged to stderr, with lines starting rhypedb: the SST manifest in ….

Rolling back and forward. You can roll back to a release from before the manifest and forward again, any number of times, without manual steps. The older release ignores MANIFEST and loads every *.sst; it never deletes the manifest. On the next open by a newer release the tokens differ, so everything the older release wrote is kept, everything it compacted away is accepted as gone, and SSTs the newer release had superseded are still deleted. One caveat belongs to the older release itself: an obsolete SST that was still on disk when you rolled back is live to it, exactly as after the same interruption of its own compaction. Obsolete SSTs are deleted as soon as possible, so one is left only when a delete was refused or the process stopped right after a compaction; the open-time log and sst/MANIFEST (obsolete lines) show any that remain.

Copying a data directory. Copy it whole, with LOCK, preserving modification times (cp -a, rsync -a), or use backups.

Limits of the fingerprint. It relies on a file's length, modification time and tail CRC; it is not a content hash. Two consequences, both outside the supported paths:

  • A copy that drops LOCK and does not preserve modification times can make a superseded file look different from the one listed, so it would be kept and loaded again. That is an unsupported way to copy a data directory.
  • On a filesystem with coarse timestamps (1 to 2 seconds), a file that reuses a superseded file's name with the same length and tail bytes, within one timestamp tick of it, could in theory be mistaken for the superseded file and deleted. This is unlikely: an older release reuses a name only after the directory has been emptied of higher numbers, which takes a restart.

Restoring with an older rhypedb. A v0.2.x restore ignores errors when it clears sst/ and does not touch LOCK. After restoring with an old binary or CLI, before starting the new binary make sure sst/ holds only the restored files and no sst/MANIFEST remains (or, with the server stopped, delete LOCK). Otherwise a leftover MANIFEST whose token still matches LOCK would make the new binary treat the restored SSTs as unlisted and delete them.

Recovery. Open fails, with a message naming the files, in two cases:

  • The manifest is damaged (its checksum or format is wrong). Restore from a backup. Or, with the server stopped, move sst/MANIFEST aside: the next open takes every *.sst as live, as releases before the manifest did. Any SST the damaged manifest listed as obsolete would then be live again and could bring deleted rows back, so prefer a backup if a compaction ran shortly before.
  • A listed live SST is missing while only this release has opened the directory. Its rows are gone from this directory. Restore from a backup. Or, to accept the loss, delete LOCK with the server stopped: the next open treats the manifest as possibly stale, opens with the SSTs that are there (still deleting the obsolete ones), and logs the missing file.

When a flush fails

Every few MB of writes, the memtable (the newest writes, held in memory and in wal.log) is written to a new SST: a flush. If a flush fails, most often because the disk is full, no acknowledged write is lost or hidden:

  • The write whose commit set off the flush was already in wal.log and visible before the flush began, so it succeeds. The failure is logged to stderr, on a line starting rhypedb: a memtable flush in … failed.
  • Until a flush succeeds again, each write first retries it. If the retry fails too, the write fails with that error and changes nothing. Reads keep working and see every acknowledged write.
  • wal.log is not replaced until every row it holds is in an SST, so a restart or crash while the disk is full recovers every acknowledged write from it.
  • Once there is space again (or the I/O fault is fixed), the next write's retry succeeds and writes carry on. No restart is needed.

Authentication

The data-plane endpoints (POST /query, GET /status, GET /health, GET /schema) are open — put them behind your own network boundary or proxy as needed.

The administrative endpoints (/admin/* — migrations, backup, export, compaction, reload) are gated by RHYPEDB_ADMIN_TOKEN:

  • Token unset → admin routes return 403 Forbidden.
  • Token set, request missing/mismatched Authorization: Bearer <token> → 401 Unauthorized.
  • Token set and matched → request proceeds.
curl -s -X POST http://127.0.0.1:4200/admin/compact \
  -H "Authorization: Bearer $RHYPEDB_ADMIN_TOKEN"

The CLI reads the token from --admin-token or the RHYPEDB_ADMIN_TOKEN environment variable.

Hot schema reload

After you change the schema file, you can apply it without restarting the process:

curl -s -X POST http://127.0.0.1:4200/admin/reload \
  -H "Authorization: Bearer $RHYPEDB_ADMIN_TOKEN" \
  --data-binary @schema.rhype

The server rebuilds its in-memory handle on the same underlying storage and swaps it in atomically — in-flight queries are not interrupted. Reload is refused while an online field-type migration is armed (the migration owns the schema until it finishes). After a change_field_type migration cuts over, the server reloads automatically. See Schema Migrations.

Compaction

rhypedb compacts its LSM automatically in the background. To force a flush + full compaction on demand (an expensive, mutating operation — hence admin-gated):

curl -s -X POST http://127.0.0.1:4200/admin/compact \
  -H "Authorization: Bearer $RHYPEDB_ADMIN_TOKEN"
{ "flush_ok": true, "flush_ms": 50, "compact_ok": true, "compact_ms": 200 }

Opening a large database. Each data file records which object ids it holds, so startup rebuilds its set of live objects from those small records without reading object data. Files written by versions before 2026-11 lack the record. For those files, startup walks their object keys instead, which pages in roughly half of their object bytes on every open. A compaction rewrites them in the current format, after which opens stay fast; one POST /admin/compact (or compact() when embedding) converts an older data directory in one go.

Upgrading relation copies

Reverse relation entries store their linking object's other to-one target ids (see Storage cost of indexes and relations). Versions before 2026-11 could let those ids drift from the links. A database that such a version wrote with links in it opens with "cover_peers_sound": false in GET /status. Queries stay correct, but hops through a to-one relation read the links themselves instead of the stored ids, so they run slower. One rewrite pass repairs the ids and shrinks oversized copies; compact afterwards to reclaim the freed space:

curl -s -X POST http://127.0.0.1:4200/admin/rewrite-covers \
  -H "Authorization: Bearer $RHYPEDB_ADMIN_TOKEN"
curl -s -X POST http://127.0.0.1:4200/admin/compact \
  -H "Authorization: Bearer $RHYPEDB_ADMIN_TOKEN"
{ "ok": true, "ms": 5400, "objects": 120000, "rev_edges_rewritten": 3100, "index_entries_rewritten": 0, "cover_peers_sound": true }

The pass runs in small batches alongside normal traffic and is safe to interrupt and rerun. Once it completes, the database stays marked sound across restarts. Embedded users call Database::rewrite_covers() instead.

Monitoring

  • GET /health — liveness. Returns 200 OK with a short status string.
  • GET /status — operational snapshot: active subscriptions, pending embeddings, per-index vector counts, the embedding model's load state (model_loaded, model_error) and the cross-encoder's own load state (reranker_loaded, reranker_error — always present; both stay false/null while the cross-encoder is off) — see Embedding pipeline settings — and — when the schema has @fulltext fields — a fulltext block: building (fields whose index is still being backfilled), failed (background index tasks that hit an error — the next restart retries them), and per-field indexes entries with state (building / built, or dropping for a field whose directive was removed and whose rows are still being swept), generation, documents (indexed documents), and backfill progress indexed / total.
  • GET /schema — live schema introspection (JSON + canonical SDL) for tooling and typed-client codegen. See the API reference.
curl -s http://127.0.0.1:4200/status
{
  "subscriptions": 2,
  "vectorizer": {
    "pending": 0,
    "indexes": [ { "name": "Post.embedding", "vectors": 12000 } ],
    "model_loaded": true,
    "model_error": null,
    "reranker_loaded": false,
    "reranker_error": null
  }
}

Neither requires authentication, and /status exposes only operational metrics (no data), so it is safe to scrape.

Backups

See Backup & Recovery for taking consistent online backups (physical snapshots and portable logical exports) and restoring them.

Backup & Recovery

rhypedb offers two complementary ways to get your data out and back in:

Physical backupLogical export
What it isA byte-level snapshot of the storage files.A portable NDJSON dump of objects, relationships, and vectors.
FormatLSM SSTs + WAL + indexes.rhypedb-logical-export-v1 text stream.
SpeedVery fast (hard-links files).Slower (serializes every object).
PortabilitySame storage format/version.Version-independent; survives format changes.
Use it forFast local snapshots, point-in-time recovery, VM scale-to-zero.Migrating between versions, moving data, archival, inspection.

Both are taken online from a running server against a single consistent snapshot, and both are gated by RHYPEDB_ADMIN_TOKEN.

Physical backup

A physical backup flushes the memtable, hard-links the immutable SST files into the destination, copies the WAL and vector indexes, and writes a MANIFEST.json last as a completeness marker.

Take one

Write it on the server's filesystem:

rhypedb-cli --admin-token "$TOKEN" backup --dest /backups --label nightly

Or stream it to your local machine (downloaded as a tar and unpacked into a directory):

rhypedb-cli --admin-token "$TOKEN" backup --download ./snap-2026-06-19

The equivalent HTTP endpoints are POST /admin/backup and GET /admin/backup/stream.

Verify one

rhypedb-cli verify ./snap-2026-06-19

This checks that MANIFEST.json is present and every file it lists exists.

Restore one

Restore is an offline operation — the target server must be stopped (the data-dir lock will refuse it otherwise).

rhypedb-cli restore ./snap-2026-06-19 /var/lib/rhypedb --force

restore:

  • validates the snapshot's manifest and completeness before touching the target,
  • clears any stale sst/, wal.log, and hnsw_*.bin from the target first (so you never mix two databases),
  • copies the snapshot in, and
  • prints the command to start the server on the restored directory.

--force is required to overwrite a non-empty target directory.

Restore on boot (managed deployments)

The server can also restore a snapshot itself, at startup, before it opens the database — no CLI needed. This is the path a managed platform uses to wake an instance from object storage:

rhypedb-server --restore-from ./snap-2026-06-19 --data-dir /var/lib/rhypedb

It applies the same validation and clear-then-copy as the CLI restore, but holds the single-writer lock across the operation, takes the schema from the snapshot (so --schema is optional), restores the hnsw_*.bin index snapshots for a fast wake, and is idempotent (a restart with the same snapshot already in place is a no-op). See Restore on boot for the full contract.

Logical export

A logical export is a single self-describing NDJSON stream — header, schema, objects, relationships, vectors, trailer — read at one consistent snapshot. The trailer (with per-type counts and a complete marker) is written last, so a truncated dump is detectable. Because it carries the schema and typed values rather than raw storage bytes, it imports into any version of rhypedb.

Values are encoded losslessly: 64-bit integers as decimal strings (to survive JSON), floats as the exact IEEE-754 bit pattern, bytes as base64, and raw f32 vectors verbatim. The HNSW index is not exported — it is rebuilt from the raw vectors on import.

Take one

# write on the server
rhypedb-cli --admin-token "$TOKEN" export --dest /exports --label v2

# or stream to a local file
rhypedb-cli --admin-token "$TOKEN" export --download ./dump.ndjson

Options:

FlagMeaning
--types A,BExport only these types (relationships to excluded types are dropped and counted).
--vectors raw|none|reembedraw (default) ships the f32 vectors; none omits them; reembed omits @vectorize vectors so the importer regenerates them from source text.

The equivalent HTTP endpoints are POST /admin/export and GET /admin/export/stream. An export is refused while a field-type migration is in progress.

Verify one

rhypedb-cli verify-export ./dump.ndjson

This validates the header, the trailer, and the per-type counts.

Logical import

Importing a logical export is done by the dedicated rhypedb-import binary, offline (server stopped):

rhypedb-import ./dump.ndjson --data-dir /var/lib/rhypedb

It:

  • validates the file (header, trailer, counts) and parses the embedded schema before touching anything,
  • builds the entire import in a fresh staging directory and atomically swaps it into place only on full success — a failed import never wipes or corrupts the target,
  • preserves object ids exactly (relationships and vectors reference ids by value, so no remapping is needed), and
  • writes schema.rhype and tells you how to start the server.
imported 3 type(s): 1000 objects, 500 edges, 100 vectors
start the server with:
  rhypedb-server --schema /var/lib/rhypedb/schema.rhype --data-dir /var/lib/rhypedb
(the HNSW vector index rebuilds from the imported vectors on first start)

Flags:

FlagMeaning
--data-dir <path>Target directory (must be empty unless --force).
--forceOverwrite a non-empty target.
--vectors raw|none|reembedHow to handle vectors (raw = default). reembed re-derives @vectorize vectors from source text by loading the embedding model — it fails cleanly if the model is unavailable, and is lossy/non-deterministic vs. the originals.

Online import (into a running server)

POST /admin/import/stream applies a dump to a live server without stopping it — stream the NDJSON as the request body:

curl -X POST "http://127.0.0.1:4200/admin/import/stream?vectors=raw" \
  -H "Authorization: Bearer $RHYPEDB_ADMIN_TOKEN" \
  --data-binary @dump.ndjson

Unlike the offline path it can't stage-and-swap (the server holds the data dir open), so it writes directly to the live database. That means:

  • Additive and non-atomic — a mid-stream failure can leave partially-imported data (there is no all-or-nothing swap).
  • Insert-only; refuses id collisions — ids are preserved verbatim, and the format is built for restoring a whole database into a fresh dir, not merging into a populated one. An imported id that already exists is refused (overwriting it would leave the old object's unique/index/edge entries stale). You can still import into a populated DB with a disjoint id space; to replace existing data, import into a fresh database.
  • Refused during a migration — returns 409 while a field-type migration is in flight.
  • Vectors are searchable immediately — imported vectors are written through the live index, not just the on-disk keys, so no restart is needed. vectors=reembed instead enqueues re-embedding jobs for @vectorize fields (the worker fills them in asynchronously).

Use the offline rhypedb-import for the safe, all-or-nothing path; use online import when you need to load into a running server and accept the upsert/non-atomic semantics.

Which should I use?

  • Fast local snapshot, same version, point-in-time recovery, or VM snapshotting → physical backup/restore.
  • Moving data between rhypedb versions, archiving, or inspecting the contents → logical export/import.

Physical restore and the offline rhypedb-import are offline by design and protected by the single-writer data-dir lock: they refuse to run against a directory a live server still holds. Online import (above) is the exception — it runs through the live server, not against its files directly.

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

Architecture

This documentation covers how to use rhypedb. For how it works inside — the LSM-tree storage engine, the write-ahead log, MVCC snapshot isolation, the TurboQuant/HNSW vector pipeline, the wire protocol, and the crate layout — see the architecture document in the repository:

→ ARCHITECTURE.md

A short orientation to the workspace crates:

CrateRole
rhypedb-storageLSM-tree, WAL, memtable, SSTs, MVCC, the single-writer data-dir lock.
rhypedb-schemaThe schema DSL parser and type system.
rhypedb-engineThe database engine: catalog, object model, migrations, the vectorizer queue.
rhypedb-vectorHNSW indexing, TurboQuant quantization, distance metrics.
rhypedb-queryQuery language AST, parser, and executor.
rhypedb-embedText embedding models (via ONNX Runtime) for @vectorize.
rhypedb-subscribeChange events and subscription filters.
rhypedb-serverThe server binary: HTTP + TCP, admin API. Also ships rhypedb-import.
rhypedb-cliThe client and operator tool.