View indexing is the main performance subject. A view's index is built incrementally: when a document changes, the map function runs for it and the B-tree is updated. The cost you feel is the first query after a batch of writes, which by default waits for the indexer to catch up. On a bulk load of a million documents, the first view query can take minutes.
The controls: update=false returns immediately from the current index, however stale - correct for a dashboard, wrong for a correctness check. update=lazy returns stale and triggers a build. And a warming strategy - querying every view after a load, or on a schedule - moves the cost off the user's request. In production, warm your views deliberately rather than letting a user discover the cost.
Two things that invalidate a view index entirely: changing the map function (the whole index rebuilds from scratch, which on a large database is hours) and, in older versions, upgrading. So treat a design document change as a deployment event with a rebuild window, and consider deploying the new view under a new design document name, warming it, then switching - a blue-green deployment for indexes.
Compaction is not optional. CouchDB is append-only: every update writes a new revision and leaves the old data in the file. Without compaction, the file grows without bound - a database holding 180 MB of live JSON can occupy several gigabytes. POST /_compact rewrites the file keeping only current revisions; POST /_compact/<ddoc> compacts a view index. CouchDB 3 has an automatic compaction daemon configured by default, and you must confirm it is running and keeping up - the symptom of failure is a disk that fills.
Compaction needs free space roughly equal to the live data size to work, which produces the worst failure mode in CouchDB operations: a disk so full that compaction cannot run, so the disk stays full. Monitor the ratio of sizes.file to sizes.active and act on it long before the disk is full.
Attachments store binary data alongside a document. They work, they replicate, and large attachments make replication slow and compaction expensive. For anything beyond small files, store the binary in object storage and keep a reference.
Partitioned databases (CouchDB 3+) place documents sharing a partition key on the same shard, with ids of the form partition:docid. A query scoped to one partition reads one shard rather than all q of them, which is a large win for a naturally partitioned workload - per-survey, per-tenant, per-device. The constraints: the partition must be chosen at database creation, cannot be changed, and global queries across partitions are more expensive. It is the right choice when your dominant access pattern is "everything for one X".
Laboratory exercise 4 - a measured improvement.
Load at least one million documents. Declare a baseline: five queries with p50, p95 and p99, plus the _info output for each view and the database sizes before and after.
Measure the first-query-after-load cost explicitly: load in bulk, then time the first view query and the second. Record both. Then implement warming and show the user-facing cost disappear.
Apply techniques one at a time and re-measure: a Mango index against the equivalent view, update=false for a dashboard query, a built-in reduce against a JavaScript one, and a partitioned database against an unpartitioned one for a per-survey query.
Demonstrate the compaction failure mode safely: fill a small volume with repeated updates until sizes.file is several times sizes.active, show compaction recovering it, and record how much free space it needed.
Deliverable: the benchmark report with all percentiles at each step, every _info output, the first-query measurement with and without warming, the partition comparison, the compaction demonstration with the space figures, and one change that did not help.
// ------------------------------------------------------------------
// The cost you actually feel: THE FIRST QUERY AFTER A WRITE BATCH.
// ------------------------------------------------------------------
// POST /survey/_bulk_docs (1,000,000 documents)
// time curl 'http://.../survey/_design/reports/_view/counts_by_site_date?group_level=2'
// real 3m41.882s <- the indexer, on the user's request
// time curl '...same...'
// real 0m0.094s <- warm
//
// A default view query WAITS for the indexer. On a bulk load that
// is minutes, and the person who discovers it is a user.
// ?update=false return NOW from the current index, however stale
// -> correct for a dashboard
// -> wrong for a correctness check
// ?update=lazy return stale AND trigger a build
// ?stable=true read from a consistent shard set
// WARMING: move the cost off the user's request. Do this after every
// load and on a schedule:
// for v in by_survey_time counts_by_site_date unreviewed; do
// curl -s "http://.../survey/_design/reports/_view/$v?limit=1" >/dev/null
// done
// curl -s http://.../survey/_design/reports/_info | jq .view_index
const info = {
update_seq: 998000, updater_running: true,
updates_pending: { total: 2000 }, // documents behind
sizes: { file: 512000000, active: 460000000 },
waiting_clients: 3 // requests BLOCKED right now
};
// waiting_clients > 0 means users are waiting on the indexer.
// ------------------------------------------------------------------
// CHANGING A MAP FUNCTION REBUILDS THE WHOLE INDEX. From scratch.
// ------------------------------------------------------------------
// On a large database that is hours, during which queries against
// that view block or return stale data. So: deploy the new view under
// a NEW design document name, warm it, then switch the application
// over. A blue-green deployment, for indexes.
// PUT /survey/_design/reports_v2 (new map function)
// ... warm it ...
// ... switch the application ...
// DELETE /survey/_design/reports
// Treat any design document change as a deployment event with a
// rebuild window. It is not a config tweak.
// ------------------------------------------------------------------
// COMPACTION IS NOT OPTIONAL. CouchDB is append-only.
// ------------------------------------------------------------------
// curl -s http://.../survey | jq .sizes
// { "file": 4100000000, <- 4.1 GB on disk
// "external": 180000000, <- 180 MB of actual JSON
// "active": 195000000 } <- 195 MB live
//
// Every update left the old revision in the file. 21x bloat, and it
// grows without bound.
// curl -X POST http://.../survey/_compact -H 'Content-Type: application/json'
// curl -X POST http://.../survey/_compact/reports <- a view index
// curl -s http://.../survey | jq '.compact_running'
// THE WORST FAILURE MODE IN COUCHDB OPERATIONS:
// Compaction needs free space roughly equal to the LIVE DATA SIZE,
// because it writes a new file and then swaps. So a disk full enough
// that compaction cannot run STAYS FULL. There is no way out that
// does not involve adding storage or moving the database.
//
// Monitor the RATIO, and act long before the disk is full:
// bloat = sizes.file / sizes.active
// > 2 compaction is behind
// > 4 act now
// > 10 you may already be unable to compact
// CouchDB 3 has an automatic compaction daemon ON by default. CONFIRM
// IT IS RUNNING AND KEEPING UP - the symptom of failure is a full disk.
// curl -s http://.../_node/_local/_config/compaction_daemon | jq
// curl -s http://.../_node/_local/_config/compactions | jq
// { "_default": "[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"},
// {from, \"23:00\"}, {to, \"04:00\"}]" }
// ------------------------------------------------------------------
// ATTACHMENTS: they work. Be careful.
// ------------------------------------------------------------------
// PUT /survey/response:...:r001/front.jpg?rev=3-ccc \
// -H 'Content-Type: image/jpeg' --data-binary @front.jpg
//
// They replicate, which is sometimes exactly what you want on a
// device. And large attachments make replication slow and compaction
// expensive, because the binary is rewritten every time. Beyond small
// files: object storage, and keep a reference in the document.
// GET /survey/response:...:r001?attachments=true (base64 inline)
// GET /survey/response:...:r001?att_encoding_info=true
// ------------------------------------------------------------------
// PARTITIONED DATABASES: one shard instead of all q.
// ------------------------------------------------------------------
// curl -X PUT 'http://.../survey_p?partitioned=true&q=8'
//
// Document ids become partition:docid
const partitionedDoc = {
_id: "site-14:response:r001", // partition : document
type: "response", surveyId: "site-14"
};
// A PARTITIONED query reads ONE shard, not all 8:
// GET /survey_p/_partition/site-14/_design/reports/_view/by_survey_time
// POST /survey_p/_partition/site-14/_find
// GET /survey_p/_partition/site-14 <- partition info
// The constraints, all real:
// * chosen at CREATION, cannot be changed afterwards
// * global queries ACROSS partitions are more expensive
// * a partition should not exceed ~10 GB
// * no partition may be wildly larger than the others
//
// Right when the dominant access pattern is "everything for one X" -
// per survey, per tenant, per device. Wrong when most queries are
// global.
// curl -s http://.../survey_p/_partition/site-14 | jq
// { "partition": "site-14", "doc_count": 14208,
// "sizes": {"active": 18400000, "external": 17200000} }
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.