The HTTP API, Documents and Revisions

Article · 6:00

Fauxton, databases and documents, `_id` and `_rev`, the full CRUD surface over HTTP, bulk operations and what a 409 means.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

The API is HTTP and it is complete. A database is a path: PUT /survey creates one. A document is a path within it: PUT /survey/doc-1 writes one, GET /survey/doc-1 reads it, DELETE /survey/doc-1?rev=... deletes it. There is no driver protocol and no connection state. Any HTTP client is a CouchDB client, which is why a browser, a phone and an embedded device can all be first-class participants.

_id and _rev are the two fields every document has. _id is the document's identifier - you may supply it, which you usually should, because a meaningful id (survey:2026-11-30:site-14) makes documents addressable without an index. _rev is the revision token: a counter and a hash, like 3-a1b2c3....

_rev is how CouchDB does optimistic concurrency, and it is the mechanism the whole course rests on. To update a document you must send the _rev you read. If it no longer matches, CouchDB returns 409 Conflict and your write is refused. So the normal update cycle is read, modify, write with the revision, and handle 409 by re-reading. This is not a limitation to work around - it is the guarantee that makes replication safe.

What _rev is not: it is not a version history you can rely on. Old revisions exist until compaction removes them, and after compaction they are gone. CouchDB is not a document version control system, despite appearances, and designing as though it is leads to data loss at the next compaction.

Deletion creates a tombstone. DELETE writes a new revision with _deleted: true, not nothing - because a deletion must replicate, and "absent" does not replicate. Tombstones persist, they occupy space, and a database with heavy churn accumulates them. This surprises people who expect a delete to free space.

Bulk operations are how you write efficiently: POST /_bulk_docs with an array of documents, which may mix creates, updates and deletes. POST /_all_docs with keys reads many at once. The bulk endpoint reports per-document success, so a partial failure is a list, not an exception.

Laboratory exercise 1 - provision and verify.

Stand up CouchDB 3.x with an admin configured. Confirm the version and the cluster parameters (n and q), and look at Fauxton.

Create a database and load at least 200,000 synthetic documents using _bulk_docs in batches - a survey response with nested answers and an array of photos as metadata is a good shape for the capstone.

Then demonstrate the revision mechanics, each with its HTTP evidence: read a document and update it successfully with its _rev; attempt the same update twice with the same stale _rev and capture the 409; delete a document and show the tombstone is still there in _all_docs?include_docs=true&deleted=true; and show an old revision being readable before compaction and gone after.

Deliverable: an idempotent setup script using only curl, a README taking a colleague from nothing to a loaded database, the cluster parameters with an explanation of each, and the four revision demonstrations with full curl -i output.

JS Example 1 138 lines
// ------------------------------------------------------------------
// The API is HTTP. curl -i, always, so you see the status codes -
// CouchDB communicates through HTTP semantics.
// ------------------------------------------------------------------
//   docker run -d -p 5984:5984 \
//     -e COUCHDB_USER=admin -e COUCHDB_PASSWORD=secret couchdb:3
//
//   curl -i http://admin:secret@localhost:5984/
//   { "couchdb": "Welcome", "version": "3.3.3", ... }
//
//   Fauxton (the built-in UI): http://localhost:5984/_utils
//
// CouchDB 3 REQUIRES an admin. "Admin Party" - where an unconfigured
// server let anyone do anything - is gone, and good.

//   curl -i -X PUT http://admin:secret@localhost:5984/survey
//   HTTP/1.1 201 Created
//   {"ok":true}

//   curl -s http://admin:secret@localhost:5984/survey | jq
const dbInfo = {
  db_name: "survey",
  doc_count: 200000,
  doc_del_count: 0,          // TOMBSTONES. Watch this grow.
  update_seq: "200000-g1A...",
  sizes: { file: 412000000,  // on disk, INCLUDING old revisions
           external: 180000000,  // the JSON itself
           active: 195000000 },  // live data
  cluster: { q: 8,   // shards per database
             n: 3,   // replicas per shard
             w: 2,   // write quorum
             r: 2 }  // read quorum
};
// file >> active means compaction is overdue. Module 4.

// ------------------------------------------------------------------
// _id: supply your own. A MEANINGFUL id is addressable with no index.
// ------------------------------------------------------------------
//   curl -i -X PUT http://.../survey/response:2026-11-30:site-14:r001 \
//     -H 'Content-Type: application/json' -d @-
const doc = {
  type: "response",              // a type field: every document in one
                                 // database, so this is how you tell
                                 // them apart. Standard CouchDB practice.
  surveyId: "site-14",
  collectedAt: "2026-11-30T09:14:00Z",
  collectorId: "field-07",
  answers: [
    { questionId: "q1", value: "yes" },
    { questionId: "q2", value: 42 },
    { questionId: "q3", value: ["a", "c"] }
  ],
  photos: [ { name: "front.jpg", size: 182344, sha: "ab12..." } ],
  // Device-local metadata, used for conflict resolution later:
  deviceId: "tablet-03",
  deviceClock: "2026-11-30T09:14:00.221Z"
};
//   HTTP/1.1 201 Created
//   ETag: "1-967a00dff5e02add41819138abb3284d"
//   {"ok":true,"id":"response:...","rev":"1-967a00dff5..."}
//           the ETag IS the revision. ^^^^^^^^^^^^^^^^^^^^

// ------------------------------------------------------------------
// _rev: OPTIMISTIC CONCURRENCY. The mechanism this course rests on.
// ------------------------------------------------------------------
//   1. GET the document, keep its _rev
//   2. modify it
//   3. PUT it back WITH that _rev
//   4. on 409, go back to 1
//
//   curl -X PUT http://.../survey/response:...:r001 \
//     -H 'Content-Type: application/json' \
//     -d '{"_rev":"1-967a00df...","type":"response","status":"reviewed",...}'
//   HTTP/1.1 201 Created   {"rev":"2-c3f1..."}
//
//   The SAME request again, with the now-stale _rev:
//   HTTP/1.1 409 Conflict
//   {"error":"conflict","reason":"Document update conflict."}
//
// Not a limitation to work around. It is the guarantee that makes
// replication safe, and your client must handle it on every write.

// WHAT _rev IS NOT: a version history you can rely on. Old revisions
// exist until COMPACTION removes them, and then they are gone.
//   curl -s 'http://.../survey/response:...:r001?revs_info=true' | jq '.._revs_info'
//   [ {"rev":"2-c3f1...","status":"available"},
//     {"rev":"1-967a00df...","status":"available"} ]
//   ... after compaction:
//   [ {"rev":"2-c3f1...","status":"available"},
//     {"rev":"1-967a00df...","status":"missing"} ]
// CouchDB is NOT a document version control system, despite
// appearances. Designing as if it is loses data at the next compaction.

// ------------------------------------------------------------------
// DELETE writes a TOMBSTONE, not nothing.
// ------------------------------------------------------------------
//   curl -i -X DELETE 'http://.../survey/response:...:r001?rev=2-c3f1...'
//   HTTP/1.1 200 OK   {"ok":true,"rev":"3-deadbe..."}
//                                      ^^^ a NEW revision, with
//                                          _deleted: true
//
// Because a deletion must REPLICATE, and "absent" does not replicate.
// Tombstones persist, occupy space, and accumulate under churn:
//   curl -s 'http://.../survey/_all_docs?include_docs=true' | jq '.rows[].value'
//   curl -s 'http://.../survey/_changes?include_docs=true' \
//     | jq '.results[] | select(.deleted == true)'
//
// A delete does NOT free space. People expect it to; it does not.

// ------------------------------------------------------------------
// BULK: how you actually write. Mixed creates, updates and deletes.
// ------------------------------------------------------------------
//   curl -X POST http://.../survey/_bulk_docs \
//     -H 'Content-Type: application/json' -d @batch.json
const batch = {
  docs: [
    { _id: "response:...:r002", type: "response", surveyId: "site-14" },
    { _id: "response:...:r001", _rev: "3-deadbe...", type: "response",
      status: "archived" },
    { _id: "response:...:r003", _rev: "1-aaa...", _deleted: true }
  ]
};
//   HTTP/1.1 201 Created
//   [ {"ok":true,"id":"response:...:r002","rev":"1-..."},
//     {"ok":true,"id":"response:...:r001","rev":"4-..."},
//     {"id":"response:...:r003","error":"conflict",
//      "reason":"Document update conflict."} ]
//
// PER-DOCUMENT results. A partial failure is a LIST to inspect, not
// an exception - so always read the response array, every time.

// new_edits: false is the replication mode - it writes revisions
// verbatim, including conflicting ones. You will meet it in Module 5.

// Reading many at once:
//   curl -X POST http://.../survey/_all_docs?include_docs=true \
//     -H 'Content-Type: application/json' \
//     -d '{"keys":["response:...:r001","response:...:r002"]}'

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.