Database / CouchDB Interview Questions
How does CouchDB replication work and what is the replication protocol?
CouchDB replication is a document-level sync protocol that copies documents from a source database to a target database using standard HTTP. Either or both of source and target can be local or remote CouchDB instances. Replication is initiated by posting a replication document to the _replicator database or to the /_replicate endpoint directly.
The protocol works through these concrete steps:
- Get peer info — the replicator calls
GET /targetto confirm the target is reachable and retrieves its UUID. - Read checkpoint — it reads the last replication checkpoint stored in a
_local/document on both source and target to know the last source sequence number already replicated. - Get changes — it calls
GET /source/_changes?since={last_seq}to fetch all document IDs and their current revisions changed since the last checkpoint. - Check target revisions — it POSTs the changed IDs to
POST /target/_revs_diffto find which revisions the target is missing. - Fetch missing docs — it fetches the missing document bodies from the source (with attachments if any) and POSTs them in bulk to
/target/_bulk_docs. - Save checkpoint — it writes the new sequence number to
_local/docs on both peers so the next replication starts from there.
// Replication document in the _replicator database:
{
"_id": "sync-orders-to-replica",
"source": "http://admin:pass@primary:5984/orders",
"target": "http://admin:pass@replica:5984/orders",
"continuous": false,
"create_target": true
}
The protocol is idempotent: re-running a replication never loses data or creates duplicates. Because it uses standard HTTP and checkpoint documents, any two CouchDB instances can replicate without special network infrastructure — making it practical for cloud-to-edge and offline-mobile scenarios.
More Related questions...