CouchDB HTTP API implementation reference
This page describes how the CouchDB wire is built: the HTTP listener, authentication, the route table, the revision-tree document store, Mango, views, _changes, server-side replication, errors, limits and tests. For the port, the proof scores, how to connect and how to re-run the differential suite, see the operator page CouchDB. Authentication policy across all wires is in Security.
Code lives in src/protocol/couchdb/: mod.rs (listener, HTTP parsing, authentication, _session, long-poll), api.rs (the router and every endpoint), store.rs (revision trees, per-database state, SQL persistence), mango.rs (selectors and view collation), views.rs (design-document views in QuickJS) and replicate.rs (POST /_replicate).
Third-party crates that matter here: rquickjs 0.14 (embedded QuickJS for map, reduce and filter functions), md-5 (revision ids and attachment digests), base64, regex ($regex), reqwest 0.12 (remote replication endpoints; pulled in by the default rest-api feature) and serde_json with preserve_order. The HTTP/1.1 parser is written in this repository; it does not use hyper. (source: Cargo.toml; src/protocol/couchdb/mod.rs, CouchDbHandler::parse_request; src/protocol/couchdb/replicate.rs, Ctx::call)
Listener and connection loop
- The default port is 5984 (
couchdb_port = Some(5984)insrc/config.rs;ProtocolHandler::default_port). The server builds the handler withCouchDbHandler::with_storage, orCouchDbHandler::with_tlswhen a TLS config exists. (source:src/config.rs;src/server/mod.rs;src/protocol/couchdb/mod.rs,CouchDbHandler::start) - TLS is implicit: when configured, each accepted socket goes through
TlsListener::acceptbefore any HTTP byte is read, so plaintext and TLS clients cannot share the port. (source:src/protocol/couchdb/mod.rs,CouchDbHandler::start) Not verified: no Rust test covers CouchDB over TLS. -
TCP_NODELAYis set on every accepted socket. One task per connection; each connection shares the server-wideCouchState. (source:CouchDbHandler::start) - In cluster mode
with_storageregisters aCouchReplicaSynclistener on the storage engine, so writes replicated from the leader invalidate the in-memory databases. On a read-only node,routerefuses any write with503 {"error":"not_leader"}and names the leader when known. (source:src/protocol/couchdb/mod.rs,CouchDbHandler::with_storage;src/protocol/couchdb/store.rs,CouchReplicaSync;src/protocol/couchdb/api.rs,route,is_write_request) Not verified: no test covers the follower path.
HTTP parsing
parse_request reads the request line and headers with a BufReader that lives for the whole connection, so keep-alive requests are never cut. (source: src/protocol/couchdb/mod.rs, CouchDbHandler::handle_connection, CouchDbHandler::parse_request)
| Behaviour | Detail |
|---|---|
| Methods | Upper-cased from the request line; header names are lower-cased. |
| HTTP/1.0 | Treated as Connection: close unless the client sends Connection: keep-alive. Tested by http10_request_closes_the_connection. |
Expect: 100-continue |
Answered HTTP/1.1 100 Continue before the body is read. |
| Bodies |
Content-Length or Transfer-Encoding: chunked (trailers skipped). |
| Body cap | 256 MB (MAX_HTTP_BODY). A body over 1 MB (PREAUTH_BODY_LIMIT), or any chunked body, is read up to 256 MB only if the headers authenticate; otherwise the cap is 1 MB and a larger body closes the connection. |
| Response headers |
Content-Type, Content-Length, Cache-Control: must-revalidate, Server: CouchDB/3.4.2 (SynergyDB), Connection, plus WWW-Authenticate: Basic realm="server" on 401. HEAD and 304 replies carry no body. |
| Path decoding | Each path segment is percent-decoded as UTF-8 (pct_decode); query values also turn + into a space. Tested by percent_decoding_is_utf8. |
(source: src/protocol/couchdb/mod.rs, parse_request, encode, pct_decode, parse_query, MAX_HTTP_BODY; src/protocol/buffer_limits.rs, PREAUTH_BODY_LIMIT)
Authentication
CouchDbHandler::authenticate runs before routing for every request except the two open routes below. (source: src/protocol/couchdb/mod.rs, handle_inner, authenticate)
| Credential | Handling |
|---|---|
Authorization: Basic ... |
Decoded by decode_basic_authorization and checked with verify_wire_credential("couchdb", ...): a SynergyDB catalog role and password, which must be a superuser or a member of synergy_wire_couchdb or synergy_wire_all unless SYNERGYDB_WIRE_ACCESS=open. A bad header or password is 401 unauthorized "Name or password is incorrect.". |
Cookie: AuthSession=<token> |
Looked up in the in-memory session map. A session lasts 600 s (SESSION_TTL) from its last use; each use renews it. |
| Neither |
SYNERGYDB_DEV_INSECURE_AUTH=1 or true lets the request through as user admin; otherwise 401 unauthorized "You are not a server admin.". |
(source: src/protocol/couchdb/mod.rs, authenticate, cookie_user, check_password, SESSION_TTL; src/auth/wire_auth.rs, verify_wire_credential, dev_insecure_auth_enabled)
Open without credentials: GET/HEAD / (the welcome document) and GET/HEAD /_up, from any address. Nothing in the handler checks for loopback. /_session is handled before the auth gate. (source: src/protocol/couchdb/mod.rs, handle_inner) Tested by anonymous_requests_are_refused (unit) and requests_without_valid_credentials_are_refused in tests/protocol_couchdb.rs.
/_session
| Method | Behaviour |
|---|---|
POST |
Reads name and password from a form-encoded or JSON body, verifies them as above, and returns {"ok":true,"name":...,"roles":["_admin"]} with Set-Cookie: AuthSession=<32 hex>; Version=1; Path=/; HttpOnly. The token is 128 random bits. |
DELETE |
Removes the session named by the cookie and clears the cookie. |
GET and others |
Returns userCtx (name, roles) and info.authenticated (default for Basic, cookie for a session). An anonymous call answers name: null instead of 401; a bad Basic header answers 401. |
(source: src/protocol/couchdb/mod.rs, session)
Authorization model. Every authenticated login gets the role _admin. The per-database _security object is stored and returned but not enforced; nothing reads it when serving a request. There are no CouchDB user documents and _users is not special beyond being an allowed database name. (source: src/protocol/couchdb/mod.rs, session; src/protocol/couchdb/api.rs, in_db (_security arms), valid_db_name; src/protocol/couchdb/store.rs, default_security) Not verified: no test checks _security.
Sessions live only in memory, so a restart logs out every cookie session. (source: src/protocol/couchdb/store.rs, CouchState::sessions)
Route table
handle_inner handles three routes itself (_changes?feed=longpoll, /_replicate, GET /_scheduler/jobs); everything else goes to api::route and then to in_db for paths inside a database. The match arms of route and in_db are the source of truth. (source: src/protocol/couchdb/mod.rs, handle_inner; src/protocol/couchdb/api.rs, route, in_db)
Server level
| Method and path | Result |
|---|---|
GET/HEAD /
|
Welcome: couchdb: "Welcome", version: "3.4.2", git_sha: "synergydb", a server UUID, a fixed features list, vendor.name: "SynergyDB". |
GET /_up |
{"status":"ok","seeds":{}} |
GET /_uuids?count=n |
n random 32-hex ids (default 1; over 1000 is 400 bad_request). |
GET /_all_dbs |
Names, with startkey/start_key, endkey/end_key, descending, skip, limit. |
POST /_dbs_info |
Info for each name in keys; a missing database gets {"key":...,"error":"not_found"}. |
GET /_active_tasks |
Always []. |
GET /_membership |
One fixed node, nonode@nohost. |
GET /_node/{node}/_versions |
javascript_engine: quickjs. |
GET /_scheduler/jobs |
Running continuous replications (see Replication). |
GET /_scheduler/docs |
Always empty. |
POST /_replicate |
Server-side replication. |
/_session |
See above. |
Database level (/{db})
| Method | Result |
|---|---|
PUT |
Create. The name must match valid_db_name (lowercase letter first, then a-z 0-9 _ $ ( ) + - /) or be _users, _replicator or _global_changes; otherwise 400 illegal_database_name. An existing name is 412 file_exists. Returns 201. |
DELETE |
Drop; 404 not_found if missing. |
GET/HEAD
|
Database info: doc_count, doc_del_count, update_seq, purge_seq, sizes (estimated as 16 times the JSON body length), cluster {q:1,n:1,w:1,r:1}. |
POST |
Create a document; _id from the body or a new 32-hex UUID. batch=ok answers 202. |
Inside a database (/{db}/...)
| Method and path | Result |
|---|---|
GET/POST _all_docs, _design_docs, _local_docs
|
Listings; POST merges body options over the query string (with_body_params). |
POST _bulk_docs |
Many writes; new_edits: false for replication. Returns 201 with one result per doc. |
POST _bulk_get |
Several docs and revisions. |
POST _revs_diff, POST _missing_revs
|
Missing revisions (with possible_ancestors for _revs_diff). |
POST _find, POST _explain
|
Mango query and its plan. |
GET _index, POST _index, DELETE _index/{ddoc}/json/{name}
|
Mango indexes. |
GET/POST _changes
|
Changes feed (see below). |
POST _compact, POST _compact/{ddoc}
|
Drops bodies of non-leaf revisions. Requires Content-Type: application/json (else 415 bad_content_type). Returns 202. |
POST _view_cleanup |
202, no effect. |
POST _ensure_full_commit |
201, no effect (every write is already persisted). |
GET/PUT _security
|
Stored object, not enforced. |
GET/PUT _revs_limit
|
Default 1000; must be a positive integer. |
POST _purge |
Removes revisions; bumps purge_seq. |
GET _purged_infos_limit |
Always 1000. |
* _local/{id} |
Local (non-replicated) documents. |
* _design/{ddoc}/_view/{view} |
View query. |
GET _design/{ddoc}/_info |
Fixed view-index info. |
* _design/{ddoc} and _design/{ddoc}/{attachment}
|
Design document and its attachments. |
GET/HEAD/PUT/DELETE/COPY {docid}
|
Single document. |
* {docid}/{attachment...} |
Attachments (the name may contain /). |
Anything else inside a database is 400 bad_request "Invalid request"; an unknown database is 404 not_found "Database does not exist.". (source: src/protocol/couchdb/api.rs, route, welcome, all_dbs, dbs_info, db_level, in_db, db_info_json)
Document store
Data structures
Each database is a Db held behind its own parking_lot::Mutex: a BTreeMap of documents, a BTreeMap of local docs, the update sequence seq, DbMeta (security, revs_limit, purge_seq) and a per-design-doc view cache. A Doc is a revision tree: revs: BTreeMap<rev, RevNode> and the doc's last seq. A RevNode holds its parent, deleted, an optional body (dropped by compaction or unknown for ancestors) and attachments. (source: src/protocol/couchdb/store.rs, Db, Doc, RevNode, DbMeta, CouchState)
| Rule | Implementation |
|---|---|
| Revision id |
<gen>-<32 hex>, the MD5 of parent rev, deleted flag, the body's JSON and each attachment's name and digest. The same edit on the same parent gives the same rev. It is not byte-identical to CouchDB's own hash. |
| Leaves | Revisions that are nobody's parent. |
| Winner | Non-deleted leaves first, then highest generation, then highest hash. |
_conflicts / _deleted_conflicts
|
The other live / deleted leaves, newest first. |
| Stemming | After each write, each branch keeps at most revs_limit revisions (default 1000). |
| Compaction | Non-leaf revisions lose their bodies and attachments. |
(source: src/protocol/couchdb/store.rs, new_rev, Doc::leaves, Doc::winner, Doc::conflicts, Doc::stem, Doc::compact) Tested by revision_tree_and_conflicts and delete_recreate_and_changes in src/protocol/couchdb/mod.rs.
Writes
-
Interactive edit (
edit_doc,new_edits=true): the id must be non-empty and may start with_only as_design/or_local/(400 illegal_docid). A body member starting with_other than_id,_rev,_attachments,_deleted,_revisions,_revs_info,_conflicts,_deleted_conflicts,_local_seqis400 doc_validation. A new doc must have no_rev; an existing live doc needs_revnaming a leaf; a deleted doc can be recreated without_revon top of its deleted winner. Anything else is409 conflict "Document update conflict.". Design docs are checked byvalidate_ddoc(their map and reduce sources must compile). (source:src/protocol/couchdb/api.rs,edit_doc,check_id,split_incoming,SPECIAL_IN;src/protocol/couchdb/views.rs,validate_ddoc) -
Replicator write (
force_doc,new_edits=falseonPUTor_bulk_docs): stores the given rev and its_revisionsancestry as-is, adding unknown ancestors as body-less nodes; an already known rev changes nothing. A_revthat is not<gen>-<hash>with gen at least 1 is400 "Invalid rev format". (source:force_doc,valid_rev) -
PUTdetails: arevquery parameter orIf-Matchheader must agree with any_revin the body; a body_idmust equal the URL id. A successful write answers 201 (200 for a delete) withETag: "<rev>";batch=okanswers 202.DELETEwithout a rev is a 409.COPYcopies to theDestinationheader. (source:doc_op,rev_param,copy_doc) -
Concurrency: every write takes the database mutex, applies the edit in memory, then persists before releasing it, so two writers with the same
_revcannot both win. Tested byconcurrent_updates_with_the_same_rev_admit_exactly_oneanddocument_revisions_enforce_optimistic_concurrencyintests/protocol_couchdb.rs. (source:write_one) -
_bulk_docsis not all-or-nothing: each document succeeds or fails on its own, then all touched docs are persisted in one pass. If that persist fails, the database is invalidated (reloaded from storage on next use) and the whole request answers 500.all_or_nothingis not read. (source:bulk_docs)
Attachments
Attachments are kept inline in the revision: content type, bytes, revpos and digest (md5-<base64>). Inline data is base64; a stub: true entry reuses the parent's attachment (or, for new_edits=false, any revision's), else 412 missing_stub. Reads honour Range (206 with Content-Range, multipart/byteranges for several ranges, 416 when unsatisfiable) except for compressible types (text/*, JSON, JavaScript, XML), which are served whole with Accept-Ranges: none. (source: src/protocol/couchdb/store.rs, Att; src/protocol/couchdb/api.rs, build_atts, att_op, compressible, parse_ranges) Tested by attachments_and_local_docs.
Persistence
State is written through to two SQL tables through the query engine before the HTTP response is sent:
| Table | Columns | Holds |
|---|---|---|
_couchdb_dbs |
name TEXT PRIMARY KEY, meta TEXT |
One row per database; meta is the DbMeta JSON. |
_couchdb_docs |
db_name, doc_id, seq INTEGER, doc TEXT, key (db_name, doc_id)
|
One row per document: the whole revision tree as JSON. _local/... ids hold the local doc with seq 0. |
New documents use plain multi-row INSERTs and changed ones INSERT ... ON CONFLICT ... DO UPDATE, 500 rows per statement. Databases are loaded lazily on first use and then kept in memory. Tables written by the older single-revision layer (_couch_dbs, _couch_docs) are migrated once by migrate_legacy. (source: src/protocol/couchdb/store.rs, module comment, CREATE_DBS, CREATE_DOCS, persist_docs, persist_doc_row, CouchState::db, CouchState::load, migrate_legacy) Tested by the restart phase of the differential suite (13/13, see below); no Rust test restarts the handler.
Internal tables behind this wire are denied to ordinary SQL roles; see Security.
Query features
Mango (_find, _explain, _index)
- Selector operators:
$lt,$lte,$eq,$ne,$gte,$gt,$exists,$type,$in,$nin,$size,$mod,$regex,$elemMatch,$allMatch,$keyMapMatch,$all,$not,$or,$and,$norand$beginsWith. Selectors are validated before running, so a bad operator is a 400 even on an empty database.$regexuses the Rustregexcrate, whose syntax differs from CouchDB's PCRE in places. (source:src/protocol/couchdb/mango.rs,FIELD_OPS,validate,field_matches) - Request fields read:
selector,fields,sort,limit(default 25),skip,bookmark,use_index,conflicts,execution_stats. (source:src/protocol/couchdb/api.rs,find) - Index definitions are stored in design documents and listed with the built-in
_all_docsindex. (source:mango_indexes,list_indexes,create_index,delete_index) - Comparison uses CouchDB view collation: null < false < true < numbers < strings < arrays < objects, strings compared case-insensitively first with lowercase before uppercase on a tie. This is an approximation of ICU collation, not ICU itself. (source:
src/protocol/couchdb/mango.rs,collate,collate_str)
Tested by collation_order, operators and projection in mango.rs, mango_find_and_index in mod.rs, and post_bulk_docs_all_docs_and_find in tests/protocol_couchdb.rs.
Views (_design/{ddoc}/_view/{view})
- Map functions are JavaScript, run in an embedded QuickJS runtime (
rquickjs) with a 512 MB memory limit, 1 MB stack and a 30 s interrupt deadline per indexing run.emit(k, v)collects rows. (source:src/protocol/couchdb/views.rs,new_runtime,MAP_TIMEOUT,refresh) - Reduce: the built-ins
_count,_sum,_stats,_approx_count_distinct, or a custom JavaScript reduce. Errors use CouchDB'sbuiltin_reduce_errorshapes. (source:builtin_reduce,js_reduce) - Each design doc's index is built on first query, kept in
Db::view_cache, and brought up to date from the database sequence on later queries. The index is in memory only and is rebuilt after a restart. (source:views.rs, module comment,refresh) -
include_docswith a reduce is400. (source:run_query)
Not verified: no Rust test runs a view, a reduce or a JavaScript filter; views are covered only by the differential suite.
_changes
- Parameters:
since(nowsupported),limit,descending,style=all_docs,include_docs,conflicts,attachments,filter. Filters:_doc_ids,_selector,_design, or a JavaScript filterddoc/name.filter=_viewis refused with400 "The _view filter needs JavaScript views; use _selector or _doc_ids.". (source:src/protocol/couchdb/api.rs,changes;src/protocol/couchdb/views.rs,filter_fn) - Sequences are written as
<n>-g1AAAA...with a fixed suffix; only the leading number is read back (parse_seq). (source:seq_str,parse_seq) -
feed=longpollwaits on theCouchState::changednotifier (woken by every committed write) until a change arrives ortimeoutpasses (default 60 s, capped at 300 s). (source:src/protocol/couchdb/mod.rs,longpoll) -
feed=continuousreturns the current rows as newline-delimited JSON followed by thelast_seqline, and the response ends. The connection is not held open for later changes, andheartbeatis not read. (source:src/protocol/couchdb/api.rs,changes) -
feed=eventsourceis not handled; it is answered as a normal feed.
Replication
POST /_replicate runs the CouchDB replication protocol between a source and a target, each a local database name or a URL (this server or another CouchDB). It reads the source _changes (all leaves), asks the target _revs_diff, fetches missing revisions with _bulk_get?revs=true in batches of 100, and writes them with _bulk_docs and new_edits: false. Checkpoints go to _local/<replication id> on both sides (50 history entries), so a repeat run starts where the last stopped; a checkpoint counts only when both sides recorded the same session, and a doc_ids replication does not use checkpoints. Options: create_target, continuous, cancel, doc_ids, selector, filter; remote credentials come from the URL, auth.basic or headers. Local endpoints are called in-process through api::route as the requesting user. (source: src/protocol/couchdb/replicate.rs, module comment, BATCH, MAX_HISTORY, parse_config, run_once, Ctx::call)
(source: src/protocol/couchdb/replicate.rs, run_once, read_checkpoint, write_checkpoint)
Continuous replications run as background tasks listed by _scheduler/jobs; a local source waits up to 5 s on the change notifier between rounds, a remote source is long-polled with a 10 s timeout. They live in memory only and are not restarted after a server restart. There is no _replicator database and _active_tasks does not list replications. (source: replicate.rs, continuous, scheduler_jobs; src/protocol/couchdb/api.rs, route; docs/status/2026-11-24-memcached-meta-auth-couchdb-replicate.md) Not verified: no Rust test covers _replicate; the evidence is the PouchDB replication result on the operator page and the status entry above.
A source or target that starts with http:// or https:// is a remote endpoint; anything else is a local database name. parse_ep does not restrict the remote host, so the server will connect to any address a caller names. (source: src/protocol/couchdb/replicate.rs, parse_ep) Not verified: no test covers remote endpoints.
Error replies
Errors are JSON {"error": ..., "reason": ...} with the HTTP status below. (source: src/protocol/couchdb/api.rs, Resp::err, CErr; src/protocol/couchdb/mod.rs, status_text)
| Status | error |
When |
|---|---|---|
| 400 | bad_request |
Invalid JSON, mismatched _rev/_id, bad rev format, unknown route inside a db |
| 400 |
illegal_database_name, illegal_docid, doc_validation, query_parse_error
|
Name and body validation, bad integer parameters |
| 401 | unauthorized |
Missing or wrong credentials |
| 404 | not_found |
Missing database (Database does not exist.), document (missing) or deleted document (deleted) |
| 405 | method_not_allowed |
Method not allowed on a db or doc path |
| 409 | conflict |
Document update conflict. |
| 412 |
file_exists, missing_stub
|
Database exists; attachment stub not found |
| 415 | bad_content_type |
_compact without JSON content type |
| 416 | requested_range_not_satisfiable |
Attachment range |
| 500 | internal_server_error |
Persist failure (the in-memory edit is discarded by reloading) |
| 503 | not_leader |
Write on a cluster follower |
Limits and configuration
| Setting | Default | Source |
|---|---|---|
couchdb_port |
5984 | src/config.rs |
| Request body | 256 MB authenticated, 1 MB before authentication |
MAX_HTTP_BODY, PREAUTH_BODY_LIMIT
|
| Session lifetime | 600 s since last use | SESSION_TTL |
_revs_limit |
1000 | default_revs_limit |
_uuids count |
1000 max | route |
_find limit
|
25 | find |
| Long-poll timeout | 60 s default, 300 s max | longpoll |
| View JS | 512 MB heap, 1 MB stack, 30 s |
views.rs, new_runtime
|
| Replication batch / checkpoint history | 100 / 50 | replicate.rs |
SYNERGYDB_DEV_INSECURE_AUTH |
off | src/auth/wire_auth.rs |
SYNERGYDB_WIRE_ACCESS |
enforced | src/auth/wire_auth.rs |
Every database is held fully in memory once used, including all attachment bytes and every stored revision body, so memory grows with the data. (source: src/protocol/couchdb/store.rs, module comment, Db)
Test coverage
| Where | What |
|---|---|
tests/protocol_couchdb.rs (5 tests) |
Starts the handler on a real TCP port with a catalog role: requests_without_valid_credentials_are_refused, database_lifecycle, document_revisions_enforce_optimistic_concurrency, concurrent_updates_with_the_same_rev_admit_exactly_one, post_bulk_docs_all_docs_and_find. |
src/protocol/couchdb/mod.rs (7 unit tests) |
HTTP/1.0 close, anonymous refusal, revision trees and conflicts, delete and recreate with _changes, attachments and _local docs, Mango find and index, UTF-8 percent decoding. |
src/protocol/couchdb/mango.rs (3 unit tests) |
Collation order, operators, projection. |
Proof log docs/proof/2026-11-30/proof-pack-a3232c9/logs/couchdb-couchdb-diff.txt
|
CouchDB: 177/177 match (single 159/159, cross 5/5, durable 13/13) against CouchDB 3, with both servers restarted for the durable phase. The proof harness ran this wire under its wirediff profile, with real authentication (prove/wires.py, prove/sdb.sh). |
No Rust test covers views, reduce, _changes long-poll or continuous feeds, _replicate, _purge, attachment ranges, cookie sessions or TLS.
Not implemented
- Enforcement of
_security, CouchDB user documents in_users, roles other than_admin, proxy and JWT authentication. -
validate_doc_update, show, list, update and rewrite functions in design documents. -
all_or_nothingin_bulk_docs. - A streamed
feed=continuousandfeed=eventsource,heartbeat. - The
_replicatordatabase; persistence of continuous replications across restarts; replications in_active_tasks. - Partitioned databases (
_partition/...),_search/ Nouveau,_shards,_db_updates,_config,_node/.../_stats. - Persisted view indexes (rebuilt in memory after each restart).