# ndb > Drop NDJSON. Query it. NoSQL. One Go daemon (version 1.26.0) that stores NDJSON as its WAL and answers NoSQL JSON queries over a unix socket or TCP, with Go, Ruby (ndb, ndb-rails) and TypeScript (@thadeu/ndb) SDKs, and streams with the model of Redis Streams. ## For AI agents: read this first ndb is one Go daemon. It stores documents (JSON objects) in collections and answers HTTP/JSON over a unix socket or TCP. Every SDK (Go, Ruby, Rails, TypeScript) and the CLI are thin layers over the same HTTP API: when an SDK and the HTTP docs differ, the HTTP docs are the contract. ### Run and connect - `ndb serve` with no flags (not as root): data in `~/.ndb/data`, unix socket `~/.ndb/ndb.sock`, TCP `127.0.0.1:7070`. As root, or with `/var/lib/ndb`: socket `/run/ndb/ndb.sock`, no TCP. - The SDKs read `NDB_URL` (`unix:///path/ndb.sock`, `http://host:port`). Over TCP with a token: `Authorization: Bearer `. The unix socket needs no token. - `GET /_health` is `{"status":"ok"}` when ready; `503 not_ready` while it recovers. The SDKs retry that for 10 s. - Logs: `ndb serve -log-level debug|info|warn|error|quiet`, or `PUT /_log {"level":"debug"}` with an admin token. ### Rules that agents get wrong - **Collection names** match `^[a-z0-9][a-z0-9_-]{0,63}$`. A path segment that starts with `_` is the daemon, never a collection. - **`_id`** is the primary key, a non-empty string; ndb makes a UUIDv7 when it is missing. An existing `_id` on insert is `409 duplicate_id`. - **`_v`** is the version, set by the daemon and added to every answer. A `_v` that you send in a document is dropped. To write only on a given version, use the guard: `POST /{coll}/_update/{id}` with `{"query":{"_v":3},"update":{...}}` (no match = `{"matched":0}`). The SDKs wrap it in `with_retry` (`WithRetry`, `withRetry`): read, change in a function, write with the guard, and retry on a conflict (`stale_object` after 5 tries); the function can run more than once. - **`$unwind`** in `_aggregate`, before `$group`: `{"$unwind": "$items"}` makes one row per array element (MongoDB rules; options `preserveNullAndEmptyArrays`, `includeArrayIndex`). One per pipeline; a `$match` after it filters the elements. - **Encrypted fields:** `PUT /users {"encrypted":["cpf"]}`: the daemon stores `"ndb:e1:k1:..."` (AES-256-GCM), never the plain value, also in logs. Answers have the sealed string by default; a read with `?decrypt=1` by the unix socket, the full token or a token with `decrypt: [users]` gets the plain value (without the right, the sealed string; no error). SDKs send `decrypt=1`; `Encrypted()` / `encrypted()` / `.encrypted` send `decrypt=0`. Only `$set`/`$unset` change the field; a filter on it is only `$exists`. Add `"blind":{"cpf":"numeric"}` (or `exact`, `lower`, `upper`; or a list of exact fields; a blind field is encrypted too) to find it: `$eq`, `$in`, `$ne`, `$nin`, `indexes`, `unique` and `$group` by `"$cpf"` then work on a hidden hash field `cpf_bidx`; no range, regex or sort. A field added to `encrypted` or `blind` later encrypts the old documents in the background (`"encrypting"` in `GET /{coll}`, `building` then `ready`); until then a filter also finds the old plain values. Key rotation: `ndb key rotate` (or `-env` for `NDB_ENCRYPTION_KEY`, with `NDB_ENCRYPTION_KEY_OLD` at the next start), on the host only; `POST /_cluster/key` is unix socket only, no SDK. A lost key cannot be rotated. - **Settings:** `GET` and `PUT /_cluster/settings` (admin): the log settings, stored in the data dir (`{"log":{"level":"debug"}}`), and the encryption key, masked. The key comes from `NDB_ENCRYPTION_KEY` (64 hex), or is made at the first start and kept in the data dir and the backups. - **Indexes:** `indexes: ["status", "account_id,created_at"]`. A name with commas is a compound index (2 to 4 fields): it serves equality on the first fields, then a range on the next one; it does not order the rows. `unique: ["account_id,email"]` is a compound unique key. `X-Ndb-Plan` names the index used. - **Optimistic locking (the default):** `_v` needs no setup. Rails models guard every save with it (`Ndb::StaleObjectError`); in Go, TypeScript and Ruby pass it as a guard or use `with_retry`. Overview of optimistic locking, pessimistic locking and transactions: `docs/dev/concurrency.md`. - **Pessimistic locking** (one holder): `POST /{coll}/_lock/{id}` `{"ttl":"30s","wait":"10s"}` answers `{"token","expires_at","doc"}`. Write with `?lock=`, then `POST /{coll}/_unlock/{id}` `{"token"}`. Other writes of the document wait; another `_lock` waits, then `423 locked`; a stale token is `409 lock_expired`. SDKs: `lock(id) { }` (`Lock`, `lock`), Rails `Model.lock.find(id) { }`. Use it when the code has an effect outside ndb. - **Transaction (one collection):** `POST /{coll}/_lock` `{"ids":[...],"ttl":"5s"}` locks a set (all or none, one token, no deadlock). `POST /{coll}/_tx` `{"ops":[{"op":"insert","doc":{}},{"op":"update","id","update","query"},{"op":"delete","id"}],"locks":[token],"unlock":true}` writes all ops in one WAL record or none; an update or delete that matches nothing is `409 tx_conflict`; an expired lock is `409 lock_expired`. `POST /{coll}/_unlock` `{"token"}` releases a set. No transaction across collections: write the side effects first with fixed ids and the status last, or use an outbox (`docs/dev/concurrency.md#writes-across-collections`). SDKs: Rails `Model.transaction(lock: [a, b], ttl: 5) { ... }` (writes collected, `Ndb::Rollback`), Go `coll.Tx(ctx, ids, fn)` (`ndb.ErrRollback`), TS `coll.transaction(ids, fn)` (`Rollback`), Ruby `coll.transaction(lock: ids) { |tx, docs| }`. - **Field names** that start with `$` are refused (`invalid_field`), except `$blob` (a blob reference). Names that start with `_` are reserved. - **Writes go through `update` operators**: `$set`, `$unset`, `$inc`, `$push`, `$pull`, `$min`, `$max`, `$setOnInsert`. Integers stay exact (an int64 overflow is `invalid_field`). - **Queries** are JSON in the body key `query`, with MongoDB-like filters (`$eq`, `$in`, `$gte`, `$regex`, `$elemMatch`, `$and`, `$or`, `$not`). `fields` keeps only the listed paths (`_id` too only if you list it). `_id` is the last tie-break of a sort, in the direction of the last sort key. An RFC 3339 string (`2026-11-12T15:00:05Z`) is an instant on every field (any width or offset; `_id` stays text). Write times in UTC with milliseconds, as the SDKs do (Go: `time.Time` fields and `ndb.Time`). - **Unknown body keys are errors** (`invalid_request`, `invalid_query`, `invalid_pipeline`): a typo never passes silently. - **Only `_doc` and `_bulk` create a collection.** `_update/{id}` (also with upsert), `_expire` and `_persist` on an unknown collection are `404 unknown_collection`: `PUT /{coll}` first. - **`_bulk` is all or nothing**, also on a partitioned collection (all checks run before any write). - **Partitioned collections** (`partition_by`, set only when the collection is made): `_id` is unique across the partitions, and a partition name (`calls-2026-11`) belongs to its logical collection. - **Patterns** (`logs-*`, `a,b`) work only on `GET /{coll}`, `_search`, `_count`, `_aggregate`. Every other route is `pattern_read_only`. - **Drop and truncate** need `?confirm={coll}`. ### Streams (Redis Streams model, on disk) - A stream is a collection made with `"stream": true` (or by its first append). Routes are under `/{s}/_streams/...`. - Entries are **append only**: `POST _doc`, `_bulk`, `_update*`, `_delete_by_query`, `_expire`, `_persist` on a stream are `400 stream_append_only`. Delete one entry with `DELETE /{s}/_doc/{id}`, or trim. - An entry ID is `-`. Read with a group (`groups/{g}/read`, then `ack`), without a group (`_streams/read`, XREAD), or with `_search`. - Delivery is **at least once**: make the work safe to repeat. A pending read counts as a delivery, as in Redis. - Delayed retry is **ndb only**: `nack` with `delay_ms`, then `claim {"due": true}`. The SDK workers do it with a retry schedule (`Retry` / `retry:` / `retry`) and a max age; a poison entry goes to `_dead`, and nothing sends it back by itself. - The Redis commands exist in each SDK for a move from Redis: Ruby `Ndb::Client#xadd` and the others, Go `sdk/go/ndbredis`, TypeScript `@thadeu/ndb/ioredis` and `@thadeu/ndb/node-redis`. ### Pick the SDK page - **Rails app**: `ndb-rails`. Models with `Ndb::Record` (`where` for a list, `find_by` for one, `find(id)` by id, `to_ndb` gives the JSON body). Each model has `created_at` and `updated_at` with an index, and `scope`, `uniqueness:`, `dependent:` and `readonly?` work as in ActiveRecord. Streams with `include Ndb::Streams` in `app/streams`, run with `bundle exec ndb streams`, test with `Ndb::Streams.inline!` or `perform_now`. ActionCable on ndb: `adapter: ndb` in `config/cable.yml` (a stream `cable`, read without a group by each process: fan-out, at most once). Turbo: each record has a GlobalID (`turbo_stream_from @record`); `Ndb::Turbo.refresh(record)` or `("name", id)` sends a throttled Turbo refresh (one per 2 s per stream and process, 0 s in tests), `broadcasts_live_refreshes` on a model does it after each commit. - **Plain Ruby**: the gem `ndb` (`Ndb::Client`). - **Go**: `github.com/thadeu/ndb/sdk/go` (standard library only). - **TypeScript (Node, Bun, Hono)**: `@thadeu/ndb`. ### Errors Every error has the body `{"error":{"code","message"}}`. The SDKs turn each `code` into a typed error (Go `ndb.ErrUnknownCollection`, Ruby `Ndb::UnknownCollection`, TypeScript `UnknownCollectionError`). The full list is on the Errors page. ## One file for one kind of work - [ndb for a Rails app](https://ndb.clowk.in/llms-rails.txt): the agent guide and 5 pages (clients, clients/rails, query, streams, http/errors). - [ndb from Ruby](https://ndb.clowk.in/llms-ruby.txt): the agent guide and 5 pages (clients, clients/ruby, query, streams, http/errors). - [ndb from Go](https://ndb.clowk.in/llms-go.txt): the agent guide and 5 pages (clients, clients/go, query, streams, http/errors). - [ndb from TypeScript](https://ndb.clowk.in/llms-typescript.txt): the agent guide and 5 pages (clients, clients/typescript, query, streams, http/errors). - [The ndb HTTP API](https://ndb.clowk.in/llms-http.txt): the agent guide and 10 pages (http, http/errors, http/system, http/collections, http/documents, http/queries, http/watch, http/streams, query, aggregate). ## Docs - [Architecture](https://ndb.clowk.in/architecture.md): One Go process: direct mode (the daemon reads your NDJSON files) and engine mode (writes go to a WAL with fsync), memory tables, Parquet segments, and the guarantees. - [Storage](https://ndb.clowk.in/storage.md): The data directory: catalog, WAL, segments, indexes, blobs, the stream group store, and how segments are sealed and compacted. - [WAL](https://ndb.clowk.in/wal.md): The WAL is plain NDJSON files and the source of truth; durability modes, fsync, retention and recovery. - [Concurrency](https://ndb.clowk.in/concurrency.md): On top of both, a **transaction** writes many documents of one collection in one step. You start at level 1 without doing anything. - [Encrypted fields](https://ndb.clowk.in/encryption.md): Encrypted fields and blind indexes: encrypted and blind (exact, lower, upper, numeric) in the collection, find by value, unique, index and $group on an encrypted field, ?decrypt=1 and the decrypt right, encrypted() reads in the SDKs, the ke - [Configuration](https://ndb.clowk.in/configuration.md): ndb.yml, the flags and env vars of ndb serve (listeners, tokens, logs), the defaults of a server and a user install, and the collection definition keys. - [HTTP API](https://ndb.clowk.in/http.md): The HTTP API contract: rules, every route, transport, auth, request and answer shapes, consistency, retries, long requests, limits and versioning. - [Errors](https://ndb.clowk.in/http/errors.md): Every error code with its HTTP status and meaning, and the typed error of each SDK. - [Query](https://ndb.clowk.in/query.md): The query language: filters, write operators, sort, fields, pagination and cursors, date math, $elemMatch, collection patterns and lookup. - [Query routes](https://ndb.clowk.in/http/queries.md): The routes _search, _count, _aggregate, _update_by_query and _delete_by_query: bodies, answers and errors. - [Aggregate](https://ndb.clowk.in/aggregate.md): The aggregation pipeline: $match, $group and its accumulators, $sort, $project, $having, $dateTrunc, $lookup, limits. - [Watch](https://ndb.clowk.in/watch.md): Watch and ack: stream the changes of a collection to a named consumer, the events, the delivery rules and the errors. - [Streams](https://ndb.clowk.in/streams.md): Streams (the Redis Streams model on disk): append, consumer groups, ack, pending, claim, a worker loop, delayed retry, the dead letter, the move from Redis and the contract between languages. - [Clients](https://ndb.clowk.in/clients.md): How the SDKs are built (a transport and a model layer), install, the address and token, retries while the daemon starts. - [Go](https://ndb.clowk.in/clients/go.md): The Go SDK: typed collections, queries, aggregate, watch, streams with Work (retry tiers, max age), admin, testing, and the ndbredis module (go-redis stream commands). - [Ruby](https://ndb.clowk.in/clients/ruby.md): The Ruby gem ndb (Ndb::Client): collections, queries, aggregate, watch, streams with the worker (retry tiers, max age), the Redis Streams commands (xadd, ...), the ndb executable, errors. - [Rails](https://ndb.clowk.in/clients/rails.md): The ndb-rails gem: Ndb::Record models (where, find_by, find, to_ndb, lookup, aggregate), Ndb::Streams classes in app/streams (append, perform, retry, perform_now), testing. - [TypeScript](https://ndb.clowk.in/clients/typescript.md): The TypeScript package @thadeu/ndb: typed collections, the query builder, aggregate, watch, streams with work (retry tiers, max age), and the ioredis and node-redis subpaths. - [CLI](https://ndb.clowk.in/clients/cli.md): The ndb CLI: serve, query, write and admin commands over the same HTTP API, for scripts. - [Examples](https://ndb.clowk.in/examples.md): Five small programs that do the same work in Go, Ruby, TypeScript and curl. - [CRUD](https://ndb.clowk.in/examples/crud.md): Insert, read, update with the _v guard, delete and count. - [Logs (direct mode)](https://ndb.clowk.in/examples/logs.md): Direct mode: query NDJSON files that other processes write, with no import. - [Reports (aggregate)](https://ndb.clowk.in/examples/reports.md): Group, sum and average with an aggregation pipeline. - [Outbox (watch and ack)](https://ndb.clowk.in/examples/outbox.md): An outbox with watch, a filter and ack, that continues after a restart. - [Expiring sessions](https://ndb.clowk.in/examples/ttl-sessions.md): Documents that expire by themselves: expire_in, ttl, expire and persist. - [Operations](https://ndb.clowk.in/operations.md): The runbook: health, metrics, logs, backup and restore, recovery after a crash, compaction, retention, TTL and upgrades. - [Point in time recovery](https://ndb.clowk.in/pitr.md): Point in time recovery: a copy of a collection as it was at an instant, and a rename to put it in place. - [Security](https://ndb.clowk.in/security.md): The threat model: unix socket and TCP, tokens and scopes, the CSRF and DNS rebinding guards (cors_origins, allowed_hosts), the token lockout, TLS with a proxy, data at rest, debug logs, the images, the DoS limits (max_conns, max_watches) an - [System routes](https://ndb.clowk.in/http/system.md): The system routes: _health, _metrics, _log, _collections, _stats, _size, _backup, _restore, _pitr and _blobs. - [Collection routes](https://ndb.clowk.in/http/collections.md): The collection routes: define (PUT), read, drop, truncate, rename, restore, indexes, stats, compact, quarantine, and partitioned collections. - [Document routes](https://ndb.clowk.in/http/documents.md): The document routes: _doc, _bulk, _update/{id} with the _v guard and upsert, _expire, _persist and _ttl. - [Watch routes](https://ndb.clowk.in/http/watch.md): The wire contract of _watch and _ack. - [Stream routes](https://ndb.clowk.in/http/streams.md): The wire contract of streams: entry IDs, append, trim, read without a group, groups, read, ack, nack, pending, claim and errors. - [ndb UI](https://ndb.clowk.in/ui.md): ndb-ui, the web console: connections, browser, JSON editor, dev tools, live watch and backups. - [Install the UI](https://ndb.clowk.in/ui/install.md): Install the console binary. - [Run the UI in Docker](https://ndb.clowk.in/ui/docker.md): Run the console in Docker, alone or in ndb-stack. - [UI guide](https://ndb.clowk.in/ui/guide.md): One section for each screen of the console. - [Deploy](https://ndb.clowk.in/deployment.md): How to choose a setup: one VM, Docker, systemd, Voodu, two VMs over WireGuard. - [Linux (systemd)](https://ndb.clowk.in/deploy/linux.md): Install on Linux with systemd. - [Docker](https://ndb.clowk.in/deploy/docker.md): Run the daemon in Docker, and ndb-stack: the daemon and the console in one image, for development. - [Voodu](https://ndb.clowk.in/deploy/voodu.md): Run ndb with Voodu. - [Single VM](https://ndb.clowk.in/deploy/single-vm.md): One VM with the app and ndb. - [Cross-VM over WireGuard](https://ndb.clowk.in/deploy/cross-vm.md): The app on one VM and ndb on another, over WireGuard. - [Development](https://ndb.clowk.in/development.md): Work on ndb itself: commands, tests (CI and local), fuzzing, the SDK tests and the code rules. - [Releasing](https://ndb.clowk.in/releasing.md): How a release is made: versions, tags, artifacts. ## Optional - [Full docs in one file](https://ndb.clowk.in/llms-full.txt): every page (large). - [Source code](https://github.com/thadeu/ndb)