00:00

CouchDB Tutorial: Documents, Mango Queries, Replication and Spring Boot

Last updated:

Apache CouchDB is an open-source document database that stores JSON documents and lets you work with them through a plain HTTP API. Its standout feature is replication: copies of a database can live on many servers, or on a phone or laptop that goes offline, and sync up later without losing anyone's changes. That makes CouchDB a strong fit for field-service apps, point-of-sale systems and any product that must keep working without a network.

This CouchDB tutorial explains documents and revisions, how to fix the common 409 Conflict error, Mango queries and indexes, map/reduce views, the changes feed, replication and conflict resolution, and security. It ends with a complete Spring Boot 4 example that calls CouchDB with RestClient and is tested against a real CouchDB container. Every request and response on this page was run against CouchDB 3.5.3.

1. What Is Apache CouchDB?

CouchDB is a document database. Instead of rows in tables, it stores documents: self-contained JSON objects such as one product, one order or one customer profile. Documents live in a database, and every document has two special fields:

  • _id is the document's unique key inside its database, for example product:1001.
  • _rev is the revision, a version token such as 1-1de3cb4d34c00ac88dad9442db43b83c. The number before the dash counts the edits; the rest is a hash of the content. CouchDB changes it on every write.

You create, read, update and delete documents with ordinary HTTP methods (PUT, GET, DELETE), so any language, and even curl, can talk to CouchDB. It also ships with Fauxton, a web admin console at http://localhost:5984/_utils.

CouchDB is a project of the Apache Software Foundation, released under the Apache License 2.0. If you are new to document stores, read What Is NoSQL first.

Version note: This page targets Apache CouchDB 3.5.3 (the current stable 3.5 release), Spring Boot 4.1 and Java 21.
Not Couchbase: CouchDB and Couchbase are different products. Couchbase has its own SDKs, query language and Spring Data module, none of which work with CouchDB.

2. CouchDB vs MongoDB vs Relational Databases

AspectCouchDBMongoDBRelational (MySQL, PostgreSQL)
Data modelJSON documentsBSON documentsTables with rows and columns
APIHTTP + JSONBinary wire protocol with driversSQL over a database protocol
UpdatesWhole document replaced; must send _revPartial updates with operators such as $setPartial updates with UPDATE … SET
ConcurrencyOptimistic, through revisions (409 on conflict)Document-level locking, optional transactionsLocks and ACID transactions
QueryingMango selectors and map/reduce views; no joinsRich queries and aggregation pipelineSQL with joins and aggregation
ReplicationMulti-master, including offline devices (PouchDB)Replica sets with one primaryUsually primary/replica
Multi-document transactionsNoYesYes

The short version: choose CouchDB when many copies of the data must sync, even after being offline. Choose MongoDB (see the MongoDB Tutorial) or a relational database when you need rich queries or transactions across documents.

3. How CouchDB Works: Documents, Revisions and MVCC

CouchDB uses multi-version concurrency control (MVCC). It never edits a document in place: each write adds a new revision, and readers keep seeing a consistent version while a write is in progress. Data is stored in an append-only file, which makes crashes safe: the file never contains a half-written change.

The rule that follows from MVCC is simple: every update and delete must include the current _rev. CouchDB compares it with the latest revision. If they match, the write succeeds and a new revision is created; if not, someone else changed the document first, and CouchDB answers 409 Conflict.

Revisions of product:1001 and a stale update Document product:1001 starts at revision 1-1de3 with price 799. A client that sends _rev 1-1de3 with price 749 creates revision 2-6a11. A second client that still holds 1-1de3 tries to update the price to 699 and receives 409 Conflict. Deleting with _rev 2-6a11 creates revision 3, a tombstone. Document product:1001 in database products _rev 1-1de3…price 799created by PUT _rev 2-6a11…price 749current revision _rev 3-…_deleted: truetombstone PUT with_rev 1-1de3… DELETE withrev=2-6a11… Second client still holds_rev 1-1de3…, price 699 409 Conflict"Document update conflict."
Figure 1: Every write must name the revision it changes. A write based on an old revision is rejected with 409 Conflict instead of silently overwriting newer data.

Two consequences are worth remembering:

  • Updates replace the whole document. A plain PUT has no partial-update syntax, so send every field you want to keep.
  • Deletes leave a tombstone. Deleting creates a new revision marked _deleted: true, so replication can pass the deletion on. Compaction later removes the bodies of old revisions to reclaim disk space.

4. Installing CouchDB with Docker

The official couchdb image needs an admin user name and password at start-up; CouchDB 3.x refuses to run without one. The Compose file below also mounts a small configuration file that turns on single-node mode, so CouchDB creates its system databases (_users and _replicator) automatically. The port is bound to 127.0.0.1, so CouchDB is not reachable from other machines.

docker-compose.yml
services:
  couchdb:
    image: couchdb:3.5.3
    container_name: shop-couchdb
    environment:
      COUCHDB_USER: ${COUCHDB_USER}
      COUCHDB_PASSWORD: ${COUCHDB_PASSWORD}
    ports:
      - "127.0.0.1:5984:5984"
    volumes:
      - ./local.ini:/opt/couchdb/etc/local.d/10-single-node.ini
      - couchdb-data:/opt/couchdb/data

volumes:
  couchdb-data:
local.ini
[couchdb]
single_node = true
Tip: The image rewrites files in its configuration folder at start-up, so do not mount local.ini read-only (:ro); the container exits immediately if you do.
Console
export COUCHDB_USER=admin
export COUCHDB_PASSWORD='choose-a-long-random-password'
docker compose up -d

Check that the server is up. The root URL answers without logging in:

curl
curl http://localhost:5984/
HTTP response (uuid differs per server)
HTTP/1.1 200 OK
{"couchdb":"Welcome","version":"3.5.3","git_sha":"7a1f97558","uuid":"4e3bc245e3424ef7ce79a02b91a75a38","features":["access-ready","partitioned","pluggable-storage-engines","reshard","scheduler"],"vendor":{"name":"The Apache Software Foundation"}}

Open http://localhost:5984/_utils in a browser to use Fauxton with the same admin credentials.

5. Working with Documents over HTTP

5.1 Database and ID Conventions

This page uses one database, products, and document IDs made of the document type and a number, separated by a colon: product:1001, product:2002 and so on. Every document also carries "type":"product", which makes queries and views easy to filter. Database names must start with a lowercase letter; IDs can be any string you choose, so pick meaningful ones instead of random UUIDs when you can.

The curl examples read the admin credentials from the environment variables you exported above, so no password appears in the commands.

5.2 Create a Database

curl
curl -i -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/products
HTTP response
HTTP/1.1 201 Created
{"ok":true}

Running it again returns 412 Precondition Failed with {"error":"file_exists","reason":"The database could not be created, the file already exists."}. Since CouchDB 3.0, a new database is admin-only until you set its security (section 15), so a request without credentials gets:

HTTP response
HTTP/1.1 401 Unauthorized
{"error":"unauthorized","reason":"You are not authorized to access this db."}

5.3 Create a Document

PUT to /{database}/{id} creates a document with the ID you choose. (POST to the database URL also works, but then CouchDB generates a random ID.)

curl
curl -i -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/products/product:1001 \
  -H 'Content-Type: application/json' \
  -d '{"type":"product","name":"Wireless Mouse","category":"accessories","price":799.00,"stock":25}'
HTTP response (revision values are examples)
HTTP/1.1 201 Created
{"ok":true,"id":"product:1001","rev":"1-1de3cb4d34c00ac88dad9442db43b83c"}

5.4 Read a Document

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" http://localhost:5984/products/product:1001
HTTP response
HTTP/1.1 200 OK
{"_id":"product:1001","_rev":"1-1de3cb4d34c00ac88dad9442db43b83c","type":"product","name":"Wireless Mouse","category":"accessories","price":799.0,"stock":25}

Notice 799.00 came back as 799.0: JSON numbers do not keep trailing zeros. If exact decimal formatting matters, store money as integer minor units (79900) or as a string.

5.5 Update a Document with Its _rev

Send the whole document again, including the _rev you read:

curl
curl -i -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/products/product:1001 \
  -H 'Content-Type: application/json' \
  -d '{"_rev":"1-1de3cb4d34c00ac88dad9442db43b83c","type":"product","name":"Wireless Mouse","category":"accessories","price":749.00,"stock":25}'
HTTP response
HTTP/1.1 201 Created
{"ok":true,"id":"product:1001","rev":"2-6a116d7089dd3301d6522db0567ad84e"}

5.6 Delete a Document

A delete also needs the current revision, passed as the rev query parameter. Here a discontinued webcam, product:5005, is removed:

curl
curl -i -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X DELETE "http://localhost:5984/products/product:5005?rev=1-a4c14120de1cac6d43040c37b1b76070"
HTTP response
HTTP/1.1 200 OK
{"ok":true,"id":"product:5005","rev":"2-2332a8e147142621c15eaad46851336c"}

The response contains a new revision: that is the tombstone. Reading the document now tells you it was deleted, which is different from a document that never existed:

HTTP response: GET product:5005
HTTP/1.1 404 Object Not Found
{"error":"not_found","reason":"deleted"}
HTTP response: GET product:9999
HTTP/1.1 404 Object Not Found
{"error":"not_found","reason":"missing"}

5.7 Bulk Writes with _bulk_docs

POST /{database}/_bulk_docs writes many documents in one request. It is not a transaction: each document succeeds or fails on its own. In this batch, three new products are created, but the fourth entry tries to change product:1001 without a _rev:

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X POST http://localhost:5984/products/_bulk_docs \
  -H 'Content-Type: application/json' \
  -d '{"docs":[
    {"_id":"product:2002","type":"product","name":"Mechanical Keyboard","category":"accessories","price":3499.00,"stock":12},
    {"_id":"product:3003","type":"product","name":"USB-C Hub","category":"accessories","price":1299.00,"stock":40},
    {"_id":"product:4004","type":"product","name":"27-inch Monitor","category":"displays","price":15999.00,"stock":5},
    {"_id":"product:1001","type":"product","name":"Wireless Mouse","category":"accessories","price":649.00,"stock":25}
  ]}'
HTTP response
HTTP/1.1 201 Created
[{"ok":true,"id":"product:2002","rev":"1-67aa0979e46ac3b1bdd73a2f428e20b3"},{"ok":true,"id":"product:3003","rev":"1-86421def20eefaaaf574025e845aa206"},{"ok":true,"id":"product:4004","rev":"1-cf81248156b72e732981fd7267c22fa4"},{"id":"product:1001","error":"conflict","reason":"Document update conflict."}]

The status is 201 even though one document failed, so always check every entry in the response array.

5.8 Attachments

A document can carry binary attachments, such as a product photo, stored under /{database}/{id}/{attachment-name}. Uploading one is also a write, so it needs the current _rev and creates a new revision. Keep attachments small; large files belong in object storage with only their URL in the document.

6. How to Fix CouchDB 409 Conflict

A 409 Conflict means CouchDB refused your write because it was not based on the latest revision. There are two common causes.

Cause 1: no _rev at all. Updating an existing document without a revision always fails:

HTTP response: PUT product:1001 without _rev
HTTP/1.1 409 Conflict
{"error":"conflict","reason":"Document update conflict."}

Cause 2: a stale _rev. Another client updated the document after you read it. Sending the old 1-1de3cb4d… after the document reached revision 2 gives the same error:

curl
curl -i -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/products/product:1001 \
  -H 'Content-Type: application/json' \
  -d '{"_rev":"1-1de3cb4d34c00ac88dad9442db43b83c","type":"product","name":"Wireless Mouse","category":"accessories","price":699.00,"stock":25}'
HTTP response
HTTP/1.1 409 Conflict
{"error":"conflict","reason":"Document update conflict."}

The fix: read the document again to get the latest _rev and fields, apply your change to that version, and write it back. If the other client's change matters to your decision (for example, stock was reduced), show the conflict to the user instead of overwriting. Never "fix" a 409 by copying the new _rev onto your old data, because that silently throws away the other change.

7. CouchDB Mango Query Examples

Mango is CouchDB's declarative query language. You send a JSON selector to POST /{database}/_find, similar to a WHERE clause. Without an index, CouchDB scans every document and adds a warning:

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X POST http://localhost:5984/products/_find \
  -H 'Content-Type: application/json' \
  -d '{"selector":{"type":"product","category":"accessories","price":{"$lt":2000}},"fields":["_id","name","price"]}'
HTTP response
HTTP/1.1 200 OK
{"docs":[
{"_id":"product:1001","name":"Wireless Mouse","price":749.0},
{"_id":"product:3003","name":"USB-C Hub","price":1299.0}
],
"bookmark": "g1AAAABIeJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYrzFBTlp5Qml1gZGxgYg9RwwNRgyGYBAN_ZFM8",
"warning": "No matching index found, create an index to optimize query time."}

Create an index on the fields the query filters and sorts by. The index is stored in a design document named _design/product-indexes:

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X POST http://localhost:5984/products/_index \
  -H 'Content-Type: application/json' \
  -d '{"index":{"fields":["type","category","price"]},"name":"type-category-price","ddoc":"product-indexes","type":"json"}'
HTTP response
HTTP/1.1 200 OK
{"result":"created","id":"_design/product-indexes","name":"type-category-price"}

Run the query again with a sort that follows the index fields. The warning is gone because the index is used:

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X POST http://localhost:5984/products/_find \
  -H 'Content-Type: application/json' \
  -d '{"selector":{"type":"product","category":"accessories","price":{"$lt":2000}},
       "fields":["_id","name","price"],
       "sort":[{"type":"asc"},{"category":"asc"},{"price":"asc"}]}'
HTTP response
HTTP/1.1 200 OK
{"docs":[
{"_id":"product:1001","name":"Wireless Mouse","price":749.0},
{"_id":"product:3003","name":"USB-C Hub","price":1299.0}
],
"bookmark": "g1AAAABieJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYrzFBTlp5Qml1gZGxgYg9RwwNTkAGWZQUrYoUpAbO7E5OTU4uL8oszUYjeHKT4MIJCVBQA83hsV"}

The bookmark lets you fetch the next page: send it back in the next request together with the same selector. Common operators:

OperatorMeaningExample
$eq (implicit)Equal"category": "accessories"
$lt, $lte, $gt, $gteRange comparisons"price": {"$lt": 2000}
$inValue is in a list"category": {"$in": ["accessories", "displays"]}
$existsField present or absent"discount": {"$exists": true}
$and, $orCombine conditions"$or": [{"stock": 0}, {"price": {"$gt": 10000}}]
$regexRegular expression match (cannot use an index)"name": {"$regex": "^USB"}

8. Map/Reduce Views

A view is an index you define with JavaScript. It lives in a design document, a special document whose ID starts with _design/. The map function runs once per document and emits key-value pairs into a sorted index; an optional reduce function summarises the values. This view totals stock per category:

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/products/_design/catalog \
  -H 'Content-Type: application/json' \
  -d '{"views":{"stock_by_category":{
        "map":"function (doc) { if (doc.type === \"product\") { emit(doc.category, doc.stock); } }",
        "reduce":"_sum"}}}'
HTTP response
HTTP/1.1 201 Created
{"ok":true,"id":"_design/catalog","rev":"1-e15e3b98db67efa0405e0a9459e13fa7"}
Map and reduce for the stock_by_category view Four product documents pass through the map function, which emits the category as key and the stock as value. The sorted index holds accessories 25, accessories 12, accessories 40 and displays 5. The _sum reduce with group=true returns accessories 77 and displays 5. Documents Index (sorted by key) Reduce: _sum product:1001 · accessories · 25product:2002 · accessories · 12product:3003 · accessories · 40product:4004 · displays · 5 "accessories" → 25"accessories" → 12"accessories" → 40"displays" → 5 accessories: 77 displays: 5 map: emit(doc.category, doc.stock) ?group=true
Figure 2: The map function builds a sorted index; the built-in _sum reducer adds the values per key when you query with group=true.
curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" "http://localhost:5984/products/_design/catalog/_view/stock_by_category?group=true"
HTTP response
HTTP/1.1 200 OK
{"rows":[
{"key":"accessories","value":77},
{"key":"displays","value":5}
]}

Add reduce=false to see the individual index rows, for example only the displays:

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" "http://localhost:5984/products/_design/catalog/_view/stock_by_category?reduce=false&key=%22displays%22"
HTTP response
HTTP/1.1 200 OK
{"total_rows":4,"offset":3,"rows":[
{"id":"product:4004","key":"displays","value":5}
]}

Views are updated when you query them, not on every write: the first query after many changes processes those changes before answering, so it can be slow. Query with update=false or update=lazy to get the existing index immediately (possibly slightly stale). Prefer the built-in reducers _sum, _count and _stats over custom JavaScript reduce functions; they are much faster.

Mango (_find)Map/reduce views
Written inJSON selectorsJavaScript functions in a design document
Best forFiltering and sorting on fieldsAggregations, custom keys, computed values
AggregationNoYes, with reduce
IndexCreated with _index; strongly recommendedThe view itself is the index
Learning curveLowHigher

9. The Changes Feed

Every database has a changes feed at /{database}/_changes: a list of the documents that changed, in order, each with a sequence id (seq). Applications use it to update search indexes, send notifications or sync caches, and replication itself is built on it.

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" "http://localhost:5984/products/_changes?limit=2"
HTTP response (sequence values shortened)
HTTP/1.1 200 OK
{"results":[
{"seq":"1-g1AAAABteJzLYWBgYMpgTmHg…","id":"product:2002","changes":[{"rev":"1-67aa0979e46ac3b1bdd73a2f428e20b3"}]},
{"seq":"3-g1AAAACLeJzLYWBgYMpgTmHg…","id":"product:1001","changes":[{"rev":"2-6a116d7089dd3301d6522db0567ad84e"}]}
],
"last_seq":"3-g1AAAACLeJzLYWBgYMpgTmHg…","pending":4}

Sequence values are opaque strings: store last_seq and pass it back as since to continue where you stopped. Use feed=longpoll or feed=continuous to wait for new changes instead of polling, and include_docs=true to receive the documents themselves. Each document appears only with its latest revision, so intermediate edits can be skipped.

10. Replication, Conflicts and Clustering

10.1 Replication

Replication copies documents, revisions and deletions from a source database to a target database. Either side can be on another server, and running it both ways gives multi-master sync: each copy accepts writes, and they converge later. Replication is eventually consistent: copies can differ for a while. A one-off replication:

curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X POST http://localhost:5984/_replicate \
  -H 'Content-Type: application/json' \
  -d "{\"source\":\"http://$COUCHDB_USER:$COUCHDB_PASSWORD@127.0.0.1:5984/products\",
       \"target\":\"http://$COUCHDB_USER:$COUCHDB_PASSWORD@127.0.0.1:5984/products_replica\",
       \"create_target\":true}"
HTTP response (trimmed)
HTTP/1.1 200 OK
{"ok":true,"session_id":"267d2ad1c7986544491cf86bb549d33d","source_last_seq":"8-g1AAAACL…","replication_id_version":4,"history":[{ … "docs_read":6,"docs_written":6,"doc_write_failures":0 … }]}

For replication that keeps running and survives restarts, save a document in the _replicator database instead. Credentials go in an auth object rather than in the URL:

JSON
{
  "source": { "url": "http://127.0.0.1:5984/products",
              "auth": { "basic": { "username": "admin", "password": "<from your secret store>" } } },
  "target": { "url": "http://127.0.0.1:5984/products_replica",
              "auth": { "basic": { "username": "admin", "password": "<from your secret store>" } } },
  "continuous": true
}

Save it with PUT /_replicator/products-to-replica and check its state at /_scheduler/docs/_replicator/products-to-replica, which reports "state":"running" while it syncs.

10.2 Conflicts and How to Resolve Them

When the same document is edited in two copies before they replicate, both edits are kept. Here product:4004 got a new price in products and new stock in products_replica:

Replication creating a conflict on product:4004 Databases products and products_replica both hold product:4004 at revision 1-cf81. The price is changed in products, creating 2-7064, and the stock is changed in products_replica, creating 2-c657. After replication both databases show the same winner, 2-c657, and keep 2-7064 in _conflicts until the application resolves it. products 1-cf81… price 15999, stock 5 2-7064… price 14999 products_replica 1-cf81… price 15999, stock 5 2-c657… stock 3 replication (both ways) After replication, in both databases winner _rev 2-c657… (stock 3) _conflicts: ["2-7064…"] until the app resolves it
Figure 3: Both sides accept their own edit while apart. Replication keeps every revision, picks the same winner everywhere and flags the loser as a conflict.
curl
curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" "http://localhost:5984/products/product:4004?conflicts=true"
HTTP response
HTTP/1.1 200 OK
{"_id":"product:4004","_rev":"2-c657b50ed1759f79e172ab6b524120d9","type":"product","name":"27-inch Monitor","category":"displays","price":15999.0,"stock":3,"_conflicts":["2-7064f807926827a5b2b56a750485c2ae"]}

CouchDB chose a winning revision deterministically (the same choice on every copy: the longest revision history wins, and ties are broken by comparing revision ids), so every reader sees the same document. The losing revision is not lost; it is listed in _conflicts. Your application must resolve it: merge the data, write the result on top of the winner, and delete the losing revision.

curl
# 1. write the merged document (new price AND new stock) on top of the winner
curl -i -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/products/product:4004 \
  -H 'Content-Type: application/json' \
  -d '{"_rev":"2-c657b50ed1759f79e172ab6b524120d9","type":"product","name":"27-inch Monitor","category":"displays","price":14999.00,"stock":3}'

# 2. delete the losing revision
curl -i -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X DELETE "http://localhost:5984/products/product:4004?rev=2-7064f807926827a5b2b56a750485c2ae"
HTTP responses
HTTP/1.1 201 Created
{"ok":true,"id":"product:4004","rev":"3-7ae94174dff9a94901434969301c2e12"}

HTTP/1.1 200 OK
{"ok":true,"id":"product:4004","rev":"3-1bc60ff8a6d02148884a5fc2ae5176bf"}

A final GET …?conflicts=true returns the merged document at 3-7ae94174… with no _conflicts field.

10.3 Clustering: Shards and Replicas

A CouchDB 3.x cluster is several nodes acting as one server. Each database is split into q shards (default 2), and each shard is stored on n nodes as replicas (default 3). Reads and writes go to the replicas of a shard and succeed once a majority (a quorum) answers. On a single node, like the Docker setup here, there is only one copy of each shard. Clustering protects against node failure; replication between databases is a separate feature for sync, backups and offline devices.

11. CouchDB with Spring Boot: Complete Example

There is no Spring Data module for CouchDB, so this example calls the HTTP API with Spring's RestClient. It needs no extra library, and every call maps one-to-one to the curl commands above. The application manages the products database through a small REST API and logs in as shop-app, a database member, not as the server admin.

Client choice: Do not use Spring Data Couchbase or the Couchbase SDK: they are for a different product. Third-party CouchDB clients exist: the IBM Cloudant SDK for Java supports CouchDB 3.x data operations (still a 0.x release), while older libraries such as Ektorp are no longer maintained.

11.1 Database Setup

Creating databases, users, security and indexes needs admin rights, so do it once in a setup script, not in the application. This script creates the database, the shop-app user, gives it member access, and creates the Mango index the application uses:

Console
export COUCHDB_APP_PASSWORD='another-long-random-password'

curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/products

curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/_users/org.couchdb.user:shop-app \
  -H 'Content-Type: application/json' \
  -d "{\"name\":\"shop-app\",\"password\":\"$COUCHDB_APP_PASSWORD\",\"roles\":[],\"type\":\"user\"}"

curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X PUT http://localhost:5984/products/_security \
  -H 'Content-Type: application/json' \
  -d '{"admins":{"names":[],"roles":["_admin"]},"members":{"names":["shop-app"],"roles":[]}}'

curl -u "$COUCHDB_USER:$COUCHDB_PASSWORD" -X POST http://localhost:5984/products/_index \
  -H 'Content-Type: application/json' \
  -d '{"index":{"fields":["type","category","price"]},"name":"type-category-price","ddoc":"product-indexes","type":"json"}'

11.2 Project Setup

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.1</version>
        <relativePath/>
    </parent>

    <groupId>com.javabytechie</groupId>
    <artifactId>shop-couchdb</artifactId>
    <version>1.0.0</version>

    <properties>
        <java.version>21</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-restclient</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>testcontainers-junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Version note: In Spring Boot 4, the auto-configured RestClient.Builder comes from spring-boot-starter-restclient, and Jackson 3 (package tools.jackson) replaces Jackson 2; the annotations such as @JsonProperty keep their com.fasterxml.jackson.annotation package.
application.properties
spring.application.name=shop

# CouchDB connection: the app logs in as a database member, not as the server admin
couchdb.url=http://localhost:5984
couchdb.database=products
couchdb.username=${COUCHDB_APP_USER}
couchdb.password=${COUCHDB_APP_PASSWORD}

11.3 The Product Document and Exceptions

The record maps CouchDB's _id and _rev fields with @JsonProperty. @JsonInclude(NON_NULL) leaves _rev out when creating a new document.

Product.java
package com.javabytechie.shop.product;

import java.math.BigDecimal;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/** A product document. _id and _rev are CouchDB's metadata fields. */
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Product(
        @JsonProperty("_id") String id,
        @JsonProperty("_rev") String rev,
        String type,
        String name,
        String category,
        BigDecimal price,
        int stock) {

    public static Product newProduct(String id, String name, String category, BigDecimal price, int stock) {
        return new Product(id, null, "product", name, category, price, stock);
    }

    public Product withRev(String newRev) {
        return new Product(id, newRev, type, name, category, price, stock);
    }

    public Product withPrice(BigDecimal newPrice) {
        return new Product(id, rev, type, name, category, newPrice, stock);
    }
}
ProductNotFoundException.java
package com.javabytechie.shop.product;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ProductNotFoundException extends RuntimeException {

    public ProductNotFoundException(String id) {
        super("Product " + id + " not found");
    }
}
ProductConflictException.java
package com.javabytechie.shop.product;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.CONFLICT)
public class ProductConflictException extends RuntimeException {

    public ProductConflictException(String id) {
        super("Product " + id + " was changed by someone else; reload it and try again");
    }
}

11.4 Connecting to CouchDB with RestClient

The configuration builds one RestClient with the database URL and Basic authentication, and turns every CouchDB error body into a CouchDbException. Errors the application cannot fix itself (401, 403, 5xx) are logged.

CouchDbProperties.java
package com.javabytechie.shop.couchdb;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("couchdb")
public record CouchDbProperties(String url, String database, String username, String password) {
}
CouchDbException.java
package com.javabytechie.shop.couchdb;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

/** Any CouchDB error the application does not handle itself (401, 403, 5xx ...). */
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public class CouchDbException extends RuntimeException {

    private final int status;
    private final String error;

    public CouchDbException(int status, String error, String reason) {
        super("CouchDB returned " + status + " " + error + ": " + reason);
        this.status = status;
        this.error = error;
    }

    public int status() {
        return status;
    }

    public String error() {
        return error;
    }
}
CouchDbConfig.java
package com.javabytechie.shop.couchdb;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.client.RestClient;

import tools.jackson.databind.JsonNode;
import tools.jackson.databind.json.JsonMapper;

@Configuration
public class CouchDbConfig {

    private static final Logger log = LoggerFactory.getLogger(CouchDbConfig.class);

    @Bean
    RestClient couchDbClient(RestClient.Builder builder, CouchDbProperties props, JsonMapper jsonMapper) {
        return builder
                .baseUrl(props.url() + "/" + props.database())
                .defaultHeaders(headers -> headers.setBasicAuth(props.username(), props.password()))
                .defaultStatusHandler(HttpStatusCode::isError, (request, response) -> {
                    // CouchDB error bodies look like {"error":"conflict","reason":"Document update conflict."}
                    int status = response.getStatusCode().value();
                    JsonNode body = jsonMapper.readTree(response.getBody());
                    CouchDbException ex = new CouchDbException(status,
                            body.path("error").asString(), body.path("reason").asString());
                    if (status == 401 || status == 403 || status >= 500) {
                        log.error("{} {} failed: {}", request.getMethod(), request.getURI().getPath(), ex.getMessage());
                    }
                    throw ex;
                })
                .build();
    }
}

11.5 The Repository

All CouchDB access is in one class. Every update and delete sends the caller's _rev, the price update does read-modify-write because documents are replaced as a whole, and the Mango query matches the index from the setup script.

ProductRepository.java
package com.javabytechie.shop.product;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestClient;

import com.javabytechie.shop.couchdb.CouchDbException;

@Repository
public class ProductRepository {

    private static final Logger log = LoggerFactory.getLogger(ProductRepository.class);

    /** Reply to PUT and DELETE: {"ok":true,"id":"product:1001","rev":"2-..."} */
    record WriteResult(boolean ok, String id, String rev) {
    }

    /** Reply to POST /_find. warning is set when no index matched the query. */
    record FindResult(List<Product> docs, String bookmark, String warning) {
    }

    private final RestClient couch;

    public ProductRepository(RestClient couchDbClient) {
        this.couch = couchDbClient;
    }

    public Optional<Product> findById(String id) {
        try {
            return Optional.ofNullable(couch.get().uri("/{id}", id).retrieve().body(Product.class));
        } catch (CouchDbException ex) {
            if (ex.status() == 404) {
                return Optional.empty();
            }
            throw ex;
        }
    }

    public Product create(Product product) {
        WriteResult result = write(product.id(), () ->
                couch.put().uri("/{id}", product.id()).body(product).retrieve().body(WriteResult.class));
        log.info("Created {} at rev {}", result.id(), result.rev());
        return product.withRev(result.rev());
    }

    /** Documents are replaced as a whole, so we send every field plus the caller's _rev. */
    public Product updatePrice(String id, String rev, BigDecimal newPrice) {
        Product current = findById(id).orElseThrow(() -> new ProductNotFoundException(id));
        Product changed = current.withRev(rev).withPrice(newPrice);
        WriteResult result = write(id, () ->
                couch.put().uri("/{id}", id).body(changed).retrieve().body(WriteResult.class));
        log.info("Updated price of {} to {}, rev {} -> {}", id, newPrice, rev, result.rev());
        return changed.withRev(result.rev());
    }

    public void delete(String id, String rev) {
        WriteResult result = write(id, () ->
                couch.delete().uri("/{id}?rev={rev}", id, rev).retrieve().body(WriteResult.class));
        log.info("Deleted {}, tombstone rev {}", id, result.rev());
    }

    /** Uses the Mango index type-category-price created during database setup. */
    public List<Product> findByCategory(String category, BigDecimal maxPrice) {
        Map<String, Object> query = Map.of(
                "selector", Map.of("type", "product", "category", category, "price", Map.of("$lte", maxPrice)),
                "sort", List.of(Map.of("type", "asc"), Map.of("category", "asc"), Map.of("price", "asc")),
                "limit", 50);
        FindResult result = couch.post().uri("/_find").body(query).retrieve().body(FindResult.class);
        if (result.warning() != null) {
            log.warn("Mango query on category {} is not using an index: {}", category, result.warning());
        }
        return result.docs();
    }

    /** One place that turns CouchDB errors into application exceptions. */
    private WriteResult write(String id, Supplier<WriteResult> call) {
        try {
            return call.get();
        } catch (CouchDbException ex) {
            if (ex.status() == 409) {
                throw new ProductConflictException(id);
            }
            if (ex.status() == 404) {
                throw new ProductNotFoundException(id);
            }
            throw ex;
        }
    }
}
CouchDB statusApplication exceptionAPI status
404 Not FoundProductNotFoundException (or an empty Optional on read)404 Not Found
409 ConflictProductConflictException409 Conflict
401, 403, 5xxCouchDbException (logged as an error)503 Service Unavailable

11.6 The Controller and Application Class

The API returns _rev to clients, and they must send it back with a price change. This carries optimistic concurrency all the way to the browser: two users editing the same product cannot overwrite each other.

ProductController.java
package com.javabytechie.shop.product;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    public record NewProduct(String id, String name, String category, BigDecimal price, int stock) {
    }

    public record PriceUpdate(String rev, BigDecimal price) {
    }

    private final ProductRepository repository;

    public ProductController(ProductRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/{id}")
    public Product get(@PathVariable String id) {
        return repository.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
    }

    @GetMapping
    public List<Product> byCategory(@RequestParam String category, @RequestParam BigDecimal maxPrice) {
        return repository.findByCategory(category, maxPrice);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Product create(@RequestBody NewProduct request) {
        return repository.create(Product.newProduct(
                request.id(), request.name(), request.category(), request.price(), request.stock()));
    }

    @PutMapping("/{id}/price")
    public Product updatePrice(@PathVariable String id, @RequestBody PriceUpdate update) {
        return repository.updatePrice(id, update.rev(), update.price());
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable String id, @RequestParam String rev) {
        repository.delete(id, rev);
    }
}
ShopApplication.java
package com.javabytechie.shop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan
public class ShopApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}

11.7 Run the Example

Console
export COUCHDB_APP_USER=shop-app
export COUCHDB_APP_PASSWORD='another-long-random-password'
mvn spring-boot:run

# in a second terminal
curl -i -X POST http://localhost:8080/api/products -H 'Content-Type: application/json' \
  -d '{"id":"product:1001","name":"Wireless Mouse","category":"accessories","price":799.00,"stock":25}'
curl -i -X PUT http://localhost:8080/api/products/product:1001/price -H 'Content-Type: application/json' \
  -d '{"rev":"1-1de3cb4d34c00ac88dad9442db43b83c","price":749.00}'
curl -i -X PUT http://localhost:8080/api/products/product:1001/price -H 'Content-Type: application/json' \
  -d '{"rev":"1-1de3cb4d34c00ac88dad9442db43b83c","price":699.00}'
curl "http://localhost:8080/api/products?category=accessories&maxPrice=2000"
curl -i -X DELETE "http://localhost:8080/api/products/product:1001?rev=2-6a116d7089dd3301d6522db0567ad84e"
HTTP responses (headers trimmed; product:3003 was created the same way)
HTTP/1.1 201
{"_id":"product:1001","_rev":"1-1de3cb4d34c00ac88dad9442db43b83c","type":"product","name":"Wireless Mouse","category":"accessories","price":799.00,"stock":25}

HTTP/1.1 200
{"_id":"product:1001","_rev":"2-6a116d7089dd3301d6522db0567ad84e","type":"product","name":"Wireless Mouse","category":"accessories","price":749.00,"stock":25}

HTTP/1.1 409
{"timestamp":"2026-11-03T10:29:44.484Z","status":409,"error":"Conflict","path":"/api/products/product:1001/price"}

[{"_id":"product:1001","_rev":"2-6a116d7089dd3301d6522db0567ad84e","type":"product","name":"Wireless Mouse","category":"accessories","price":749.0,"stock":25},{"_id":"product:3003","_rev":"1-86421def20eefaaaf574025e845aa206","type":"product","name":"USB-C Hub","category":"accessories","price":1299.0,"stock":40}]

HTTP/1.1 204
Application log (trimmed)
INFO  c.j.shop.product.ProductRepository : Created product:1001 at rev 1-1de3cb4d34c00ac88dad9442db43b83c
INFO  c.j.shop.product.ProductRepository : Updated price of product:1001 to 749.00, rev 1-1de3cb4d34c00ac88dad9442db43b83c -> 2-6a116d7089dd3301d6522db0567ad84e
INFO  c.j.shop.product.ProductRepository : Deleted product:1001, tombstone rev 3-7153482a163c4217e4c55137f0c6d2eb

The second price change was based on revision 1, so it got 409 and the price stayed at 749. With a wrong COUCHDB_APP_PASSWORD, every request returns 503 and the log explains why:

Application log
ERROR c.j.shop.couchdb.CouchDbConfig : GET /products/product:3003 failed: CouchDB returned 401 unauthorized: Name or password is incorrect.
Tip: As shown in section 11.1, a database member such as shop-app cannot create indexes: CouchDB answers 500 error_saving_ddoc … forbidden. Keep index creation in the admin setup script.

12. Configuration Options

Server settings live in .ini files under /opt/couchdb/etc/local.d/ in the Docker image. They can also be read and changed at run time through /_node/_local/_config (admin only).

Setting (section)Default in 3.5Purpose
single_node ([couchdb])falseCreate the system databases automatically on a one-node server
max_document_size ([couchdb])8,000,000 bytesLargest accepted document body
max_attachment_size ([couchdb])1 GiBLargest accepted attachment
default_security ([couchdb])admin_onlySecurity of newly created databases
q / n ([cluster])2 / 3Shards per database / replicas per shard
bind_address ([chttpd])any in the Docker imageNetwork interface CouchDB listens on
require_valid_user ([chttpd])falseRequire authentication for every request, even the root URL
_revs_limit (per database, via API)1000How many old revision ids are remembered

The Spring Boot application has only four properties of its own:

PropertyExamplePurpose
couchdb.urlhttp://localhost:5984Server URL; use https:// outside local development
couchdb.databaseproductsDatabase name
couchdb.username${COUCHDB_APP_USER}Member user, from the environment
couchdb.password${COUCHDB_APP_PASSWORD}Password, from the environment or a secret store

13. Testing with Testcontainers

The test starts the official couchdb:3.5.3 image, creates the database and index as the setup script does, and checks the revision rules step by step: the document does not exist, is created at revision 1-…, is updated to 2-…, an update with the stale revision fails with a conflict and leaves the data unchanged, and the delete removes it.

ProductRepositoryTest.java
package com.javabytechie.shop.product;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.math.BigDecimal;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.web.client.RestClient;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@SpringBootTest
@Testcontainers
class ProductRepositoryTest {

    private static final String ADMIN = "admin";
    private static final String PASSWORD = "test-secret";

    @Container
    static GenericContainer<?> couchdb = new GenericContainer<>("couchdb:3.5.3")
            .withEnv("COUCHDB_USER", ADMIN)
            .withEnv("COUCHDB_PASSWORD", PASSWORD)
            .withExposedPorts(5984)
            .waitingFor(Wait.forHttp("/").forStatusCode(200));

    static String baseUrl() {
        return "http://" + couchdb.getHost() + ":" + couchdb.getMappedPort(5984);
    }

    @DynamicPropertySource
    static void couchDbProperties(DynamicPropertyRegistry registry) {
        registry.add("couchdb.url", ProductRepositoryTest::baseUrl);
        registry.add("couchdb.username", () -> ADMIN);   // test only: the container's admin user
        registry.add("couchdb.password", () -> PASSWORD);
    }

    @BeforeAll
    static void createDatabaseAndIndex() {
        RestClient admin = RestClient.builder()
                .baseUrl(baseUrl())
                .defaultHeaders(h -> h.setBasicAuth(ADMIN, PASSWORD))
                .build();
        admin.put().uri("/products").retrieve().toBodilessEntity();
        admin.post().uri("/products/_index")
                .contentType(MediaType.APPLICATION_JSON)
                .body("""
                      {"index":{"fields":["type","category","price"]},
                       "name":"type-category-price","ddoc":"product-indexes","type":"json"}""")
                .retrieve().toBodilessEntity();
    }

    @Autowired
    ProductRepository repository;

    @Test
    void revisionsAndConflicts() {
        assertThat(repository.findById("product:1001")).isEmpty();

        Product created = repository.create(Product.newProduct(
                "product:1001", "Wireless Mouse", "accessories", new BigDecimal("799.00"), 25));
        assertThat(created.rev()).startsWith("1-");
        assertThat(repository.findById("product:1001")).get()
                .extracting(Product::rev).isEqualTo(created.rev());

        Product updated = repository.updatePrice("product:1001", created.rev(), new BigDecimal("749.00"));
        assertThat(updated.rev()).startsWith("2-");
        assertThat(repository.findById("product:1001").orElseThrow().price()).isEqualByComparingTo("749");

        // the first revision is stale now
        assertThatThrownBy(() -> repository.updatePrice("product:1001", created.rev(), new BigDecimal("699.00")))
                .isInstanceOf(ProductConflictException.class);
        assertThat(repository.findById("product:1001").orElseThrow().price()).isEqualByComparingTo("749");

        repository.delete("product:1001", updated.rev());
        assertThat(repository.findById("product:1001")).isEmpty();
    }

    @Test
    void mangoQueryUsesTheIndex() {
        repository.create(Product.newProduct("product:2002", "Mechanical Keyboard", "accessories", new BigDecimal("3499.00"), 12));
        repository.create(Product.newProduct("product:3003", "USB-C Hub", "accessories", new BigDecimal("1299.00"), 40));
        repository.create(Product.newProduct("product:4004", "27-inch Monitor", "displays", new BigDecimal("15999.00"), 5));

        assertThat(repository.findByCategory("accessories", new BigDecimal("2000")))
                .extracting(Product::id)
                .containsExactly("product:3003");
    }

    @Test
    void unknownProductIsNotFound() {
        assertThatThrownBy(() -> repository.updatePrice("product:9999", "1-abc", BigDecimal.TEN))
                .isInstanceOf(ProductNotFoundException.class);
    }
}
Console
mvn test
Output (trimmed)
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

The test logs in as the container's admin user for simplicity; that is fine in a throwaway container and is the only place the example uses admin credentials. Docker must be running for Testcontainers.

14. Common Pitfalls

PitfallWhat goes wrongFix
Updating without the current _rev409 ConflictRead, change, write back with the latest _rev
Sending only the changed fieldsEvery other field is deleted from the documentSend the complete document
Treating _bulk_docs as a transactionSome documents are saved and others are notCheck every result entry; design for per-document success
Mango queries without an indexFull scans and the "No matching index found" warningCreate an index for each query shape
Ignoring _conflicts after replicationEdits made on one copy silently loseQuery with conflicts=true and resolve conflicts
Huge documents or attachmentsSlow replication and memory pressureSplit large data; keep files in object storage
Expecting deletes to free space at onceDisk usage stays highLet compaction run; tombstones remain by design
Mounting local.ini read-only in DockerThe container exits at start-upMount it read-write
Using Couchbase librariesNothing connectsUse the HTTP API, RestClient or a CouchDB client

15. Securing CouchDB

  • Admin user is mandatory. CouchDB 3.x requires an admin at setup and no longer offers the old "admin party" mode, in which anyone could act as admin.
  • Per-database security. Each database has a _security object with admins (can change design documents and security) and members (can read and write ordinary documents). New databases are admin-only until you add members.
  • Least privilege for applications. Connect applications as members, like shop-app, never as the server admin.
  • Do not expose CouchDB to the internet. Bind it to private interfaces or 127.0.0.1, put it behind a firewall, and enable TLS (or a TLS-terminating proxy) when traffic leaves the machine.
  • Keep credentials out of code. Use environment variables or a secret store for passwords, including those in _replicator documents.
  • Validate writes with a validate_doc_update function in a design document when several clients write to the same database.

16. When to Use CouchDB and When to Avoid It

Good use casesPoor use cases
Offline-first mobile and field-service apps that sync later (with PouchDB in the browser or app)Workloads that need multi-document transactions, such as payments
Data replicated across sites, stores or edge devicesAd hoc analytics and reports that need joins (use a relational database)
Self-contained documents: product catalogs, customer profiles, formsVery high-rate counters and caches (use Redis)
Simple HTTP access from any language, without special driversMany small partial updates per second to the same document

For an overview of other database families, see the Database Tutorial. For the caching side of an application, see the Redis Tutorial.

17. Best Practices

  • Use meaningful document IDs such as product:1001, and include a type field in every document.
  • Always send the current _rev on updates and deletes, and handle 409 by re-reading instead of overwriting.
  • Send the whole document on every update, using read-modify-write.
  • Create an index for every Mango query and match its fields in the query's selector and sort.
  • Prefer built-in reducers (_sum, _count, _stats) in views.
  • Check each result of _bulk_docs; never assume all-or-nothing.
  • Watch for and resolve conflicts in every replicated database.
  • Connect applications as database members, keep admin rights for setup scripts, and store credentials outside the code.
  • Keep CouchDB private and use TLS outside local development.
  • Test against a real CouchDB with Testcontainers, including the stale-revision case.

18. Summary

In this CouchDB tutorial you ran Apache CouchDB 3.5 in Docker, created a products database and worked with documents over HTTP, learning that every update and delete must carry the current _rev, that a stale revision returns 409 Conflict, and that deletes leave tombstones. You queried with indexed Mango selectors and a map/reduce view, followed the changes feed, replicated a database and resolved a conflict, and saw how shards and replicas work in a cluster. Finally, you built and tested a Spring Boot 4 application that uses RestClient, connects as a least-privilege member and maps CouchDB errors to clear API responses. The main recommendation: choose CouchDB when data must sync between many copies, and design around revisions and conflicts from day one.

References

Official documentation used to check the endpoints, defaults and version notes on this page:

Apache CouchDB documentation

Spring and tooling documentation