<< All versions
Skill v1.0.0
currentAutomated scan100/100hieudoanm/hieudoanm.github.io/couchdb
──Details
PublishedNovember 19, 2026 at 04:08 AM
Content Hashsha256:022d0b1bb7a95172...
Git SHA4614597356b3
──Files
Files (1 file, 6.5 KB)
SKILL.md6.5 KBactive
SKILL.md · 137 lines · 6.5 KB
name: "couchdb" description: "CouchDB — source-first JSON document database with HTTP API, multi-master replication, and map/reduce views." tags:
- "programming"
- "database"
- "document-database"
- "couchdb"
when_to_use: "Use when implementing, configuring, evaluating, or troubleshooting optimistic concurrency: create, then always send _rev back on update in a project." prerequisites:
- "Familiarity with the application’s data model and access patterns."
- "For implementation, access to the database environment or representative schema."
related_skills:
- "../couchbase/SKILL.md"
- "../rethinkdb/SKILL.md"
- "../dynamodb/SKILL.md"
avoid_when:
- "When the project does not use this technology or pattern, or the task falls outside its scope; follow the project’s existing stack and conventions."
status: "active" metadata: version: "1.0.0"
CouchDB is a JSON document database with a pure HTTP API, built around master-master replication and an MVCC document model designed for offline-friendly, fault-tolerant applications.
1. Core Concepts
- Documents are JSON objects stored under a unique
_idwith a_rev(revision) token. - Databases are collections of documents; views/indexes are per-database.
- Replication synchronizes databases between nodes or clients continuously or on demand.
- MVCC: document revisions are immutable; conflicts are resolved by application merge logic or by picking the latest valid revision.
- Query via views, defined as map/reduce functions written in JavaScript. Live listing with
_changesand filtering with_selector(Mango).
2. Access via HTTP
- REST API:
GET/PUT/POST/DELETE /db/{docid}. - Maintenance:
GET /_all_dbs,_changesfeed,_compact,_replicate.
bash
# optimistic concurrency: create, then always send _rev back on updatecurl -sS -X PUT "$CB/orders" -H 'Content-Type: application/json' \-d '{"_id":"order:1001","status":"pending","total":99.00}'REV=$(curl -sS "$CB/orders/order:1001" | jq -r ._rev)curl -sS -X PUT "$CB/orders/order:1001" -H 'Content-Type: application/json' \-H "If-Match: $REV" \-d "{\"_rev\":\"$REV\",\"status\":\"paid\",\"total\":99.00}"
bash
services:couchdb:image: couchdb:3.5 # pin a stable version for reproducibilityports:- "5984:5984"environment:COUCHDB_USER: adminCOUCHDB_PASSWORD: StrongPassword123!volumes:- couchdb_data:/opt/couchdb/data
Runnable: `examples/docker/compose/databases/documental/couchdb/docker-compose.yaml`
- Authentication:
Basic,JWT, orCookie(session) vs.PW/Local(DB setup). Use_usersDB for_designdocs? (Create dedicated users.) - Use
ETag/If-Match and_revto implement optimistic concurrency: always send_revon update; a409 Conflictmeans a revision mismatch. - Bulk operations:
_bulk_docswithall_or_nothing; transactions not supported — use independent documents.
3. Views and Indexes
- Design documents (
_design/*) contain view functions; they run against a snapshot of the database (B-tree) and are rebuilt lazily via the_viewendpoints. - Map function:
emit(key, value); reduce optional:sum,count, or custom. - For range lookups pass
startkey/endkey,include_docs=true. - Mango (Query Server) indexes (
_index) provide$eq,$gt,$regex-style selectors; create via_indexendpoint. - Prefer views over full scan for hot paths; sparse views (only emit needed docs) reduce index size.
javascript
// sparse view: only emit for documents that actually matter to this queryfunction ordersByCustomer(doc) {if (doc.type !== 'order' || !doc.customerId) return null; // no emit = not indexedemit([doc.customerId, doc.createdAt], {total: doc.total,status: doc.status,});}
bash
# range read over the view: one customer, all their orderscurl -sS -G "$CB/orders/_design/orders/_view/by-customer" \--data-urlencode 'group=true' \--data-urlencode 'startkey=["cus_42"]' \--data-urlencode 'endkey=["cus_42",{}]' \--data-urlencode 'include_docs=true'
4. Conflicts and Replication
- Replication is asynchronous; each node can have different revision trees.
- Conflicts appear as
_conflictsin a document; resolve by updating the base revision with merged content. - Replicated conflicts must be resolved client-side; design the app to tolerate eventual consistency.
- Use filtered replication with
_selector/filter functions to replicate subsets (e.g., per-user).
5. Operational Practices
- Run at least 3 nodes; use the cluster module (Paxos-based) for automatic sharding.
- Compact databases and views periodically:
_compactand_view_cleanuprelease disk (tombstone overhead). - Monitor via
_stats,_active_tasks, Prometheus (/ _metrics). - Store attachments either inline or in a separate blob store — attachments bloat replication and compaction.
- Backup via replication to a separate CouchDB instance or the snapshot tooling (e.g.,
couchdb-dumps).
6. Common Pitfalls
- Ignoring
_revand generating 409 conflicts — always marshal from latest revision. - Building views that emit for every document — this creates huge indexes and slows replication.
- Using CouchDB as a relational DB with joins and transactions.
- Letting attachment blobs clog the database — prefer external storage or large
_attachmentlimits. - Not resolving conflicts: they silently accumulate and can cause data inconsistency.
General Rules of Thumb
- Design for eventual consistency and conflict resolution first; CouchDB is intentionally final-less.
- Use views for stable, well-defined queries; use Mango for ad-hoc/exploratory filtering.
- Keep documents small and coarse-grained — one JSON document per business entity, not per field.
- Monitor compaction and tombstone growth; schedule compaction off-peak.
Quick-Start Checklist
- [ ] Chose your transport: HTTP API or SDK (e.g.,
pouchdb,couchbaseSDK,nano). - [ ] Set up authentication (users DB, JWT/scoped users) and CORS allowances.
- [ ] Design documents with unique
_ids and a revision-merge strategy. - [ ] Add views/Mango indexes only for actual lookup patterns.
- [ ] Configure replication topology (master-master, filtered) with conflict handling.
- [ ] Plan compaction schedule and backup replication strategy.
- [ ] Enable monitoring for replication lag, disk usage, and tombstone overhead.
- [ ] Test offline behavior and synchronous merge paths before shipping.