Replication, Offline Sync, Quorum and Backup

Article · 5:00

The replication protocol and its checkpoints, filtered and bidirectional replication, building an offline-first client, cluster `n` and `q`, and backup.

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

Replication is the feature. It is a stateful, resumable process that transfers documents and their revision histories between any two CouchDB-compatible databases over HTTP. It is peer-to-peer - any database can replicate with any other, and a device holding a local database is a full peer, not a cache.

Checkpoints are what make it practical. The replicator records its progress in checkpoint documents on both ends, so a replication interrupted at 80% resumes from 80% rather than starting over. On a mobile connection that is the difference between working and not.

Triggering replication: POST /_replicate is one-shot. Documents in the _replicator database are persistent and survive restarts, which is the production mechanism. continuous: true keeps it running and following the changes feed.

Filtered replication sends only part of a database, which is essential for devices: a tablet should hold the surveys assigned to its collector, not all of them. Filters can be a JavaScript function in a design document, a Mango selector (faster, since it runs natively), or an explicit doc_ids list. A selector filter is the right default.

Offline-first is the pattern this all enables. A local PouchDB in the browser or on the device accepts reads and writes with no network; a continuous bidirectional replication with the server syncs when connectivity allows; and conflicts are resolved by the policy from Module 3. The things that bite:

  • Initial sync size - a device's first sync may be very large. Filter aggressively and consider seeding from a snapshot.
  • Device clock skew - already covered, and it is here that it hurts.
  • Resolution location - decide whether the device or the server resolves conflicts, and be consistent. Both resolving independently produces resolutions that themselves conflict.
  • Purge and deletion - a tombstone replicates, so a document deleted on the server disappears from the device. A document that merely falls outside the filter does not get deleted from the device, which surprises people.

Cluster quorum. A CouchDB cluster shards each database into q shards, each replicated n times (default n=3). Writes need w acknowledgements and reads r, both defaulting to a majority. The visible consequence: a write returns 201 Created when quorum was met and 202 Accepted when the write was durable on fewer than w nodes. A 202 means your write is stored and may not be visible from every node yet - and client libraries that treat any 2xx as success hide this completely.

Backup. The simplest reliable approach is replicating to a separate backup server, which is consistent and incremental by nature. Filesystem snapshots work if taken correctly. Copying .couch files from a running server is not safe. As always, the restore is what you test, and the number is a measured RTO.

Laboratory exercise 5 - sync, break it, recover.

Set up two CouchDB servers and a PouchDB client. Configure continuous bidirectional replication between all three.

Build the offline-first flow: take the client offline, write several documents, bring it back, and confirm they arrive. Then do the hard version - modify the same documents on the server while the client is offline - and show the conflicts, resolved by your Module 3 policy.

Implement filtered replication with a Mango selector so the client holds only one collector's surveys. Then change the filter and observe what happens to documents that no longer match - they stay on the device.

Interrupt a large replication halfway, restart it, and prove from the checkpoint documents that it resumed rather than restarted.

On a three-node cluster, measure the write latency at w=1, w=2 and w=3. Then take a node down and capture a 202 Accepted, showing the write succeeded with reduced durability.

Finally, replicate to a backup server, then simulate the loss of the primary and rebuild from the backup. Record RPO and RTO, measured.

Deliverable: the replication topology, the offline-first demonstration including the conflict case, the filter change observation, the checkpoint evidence of resumption, the w latency table, the 202 Accepted capture, and the rebuild with measured RPO and RTO.

JS Example 1 128 lines
// ------------------------------------------------------------------
// Replication: peer-to-peer, over HTTP, with CHECKPOINTS.
// ------------------------------------------------------------------
// One-shot:
//   POST /_replicate
const oneShot = {
  source: "http://admin:secret@server-a:5984/survey",
  target: "http://admin:secret@server-b:5984/survey",
  create_target: true
};

// PERSISTENT - the production mechanism. Survives restarts.
//   PUT /_replicator/survey-a-to-b
const persistent = {
  _id: "survey-a-to-b",
  source: { url: "http://server-a:5984/survey",
            headers: { Authorization: "Basic ..." } },
  target: { url: "http://server-b:5984/survey",
            headers: { Authorization: "Basic ..." } },
  continuous: true,
  // A SELECTOR filter: runs natively, so it is far faster than a
  // JavaScript filter function. The right default.
  selector: { type: "response", collectorId: { $in: ["field-07"] } }
};

//   GET /_scheduler/docs    <- state of every replication
//   GET /_scheduler/jobs    <- what is running right now
const schedulerDoc = {
  database: "_replicator", doc_id: "survey-a-to-b",
  state: "running",            // or crashing, failed, completed
  info: { revisions_checked: 184203,
          missing_revisions_found: 1204,
          docs_written: 1204,
          doc_write_failures: 0,     // > 0: investigate NOW
          changes_pending: 0,
          checkpointed_source_seq: "184203-g1AAAA..." },
  last_updated: "2026-11-30T09:14:00Z"
};
// CHECKPOINTS are what make this practical: an interruption at 80%
// resumes from 80%. On a mobile connection that is the difference
// between working and not. Find them with:
//   GET /survey/_local_docs            <- _local/<checkpoint id>

// ------------------------------------------------------------------
// OFFLINE-FIRST: a local database that is a full PEER, not a cache.
// ------------------------------------------------------------------
// const PouchDB = require('pouchdb');
// const local  = new PouchDB('survey-local');
// const remote = new PouchDB('http://server:5984/survey');
//
// const sync = local.sync(remote, {
//   live: true, retry: true,
//   // Pull only this collector's work. A device's FIRST sync can be
//   // very large - filter aggressively.
//   selector: { type: { $in: ['response','review'] }, collectorId: 'field-07' }
// })
// .on('change',   i => console.log(i.direction, i.change.docs.length))
// .on('paused',   e => console.log(e ? 'offline' : 'caught up'))
// .on('active',   () => console.log('syncing'))
// .on('denied',   e => console.error('REJECTED BY VALIDATION', e))
// .on('error',    e => console.error('sync error', e));
//
// Writes work with no network at all:
// await local.put({_id: 'site-14:response:r099', type: 'response', ...});

// The four things that bite, in practice:
//   1. INITIAL SYNC SIZE. Filter hard; consider seeding from a dump.
//   2. DEVICE CLOCK SKEW. A fast tablet wins every timestamp
//      conflict forever. Server-stamp on push.
//   3. WHERE RESOLUTION HAPPENS. Pick device OR server and be
//      consistent. Both resolving independently produces resolutions
//      that THEMSELVES conflict.
//   4. A TOMBSTONE REPLICATES; FALLING OUT OF A FILTER DOES NOT.
//      Delete on the server -> gone from the device. Change the
//      filter so a document no longer matches -> it STAYS on the
//      device, forever. This surprises everyone once.

// ------------------------------------------------------------------
// CLUSTER QUORUM, and the 202 that client libraries hide.
// ------------------------------------------------------------------
//   q = shards per database       (default 2 in 3.x, often set to 8)
//   n = replicas per shard        (default 3)
//   w = write quorum              (default majority of n)
//   r = read quorum               (default majority of n)
//
//   PUT /survey?q=8&n=3
//   GET /survey/_shards
//   GET /survey/_shards/response:site-14:r001   <- which nodes hold it

//   PUT /survey/doc?w=3
//   HTTP/1.1 201 Created    <- quorum MET
//
//   ... with a node down:
//   HTTP/1.1 202 Accepted   <- STORED, on FEWER than w nodes
//   {"ok":true,"id":"doc","rev":"1-..."}
//
// 202 means durable on fewer replicas than you asked for, and perhaps
// not yet visible from every node. A client library that treats any
// 2xx as success HIDES THIS COMPLETELY. Check the status code.

//   GET /_membership
//   GET /_up                 <- load balancer health check
//   GET /_node/_local/_system

// ------------------------------------------------------------------
// BACKUP: replicate to a backup server. Consistent and incremental.
// ------------------------------------------------------------------
//   PUT /_replicator/survey-backup
const backup = {
  _id: "survey-backup",
  source: "http://admin:secret@primary:5984/survey",
  target: "http://admin:secret@backup:5984/survey",
  continuous: true, create_target: true
};
// Consistent and incremental BY NATURE - it is the same protocol.
//
// Filesystem snapshots work if taken correctly.
// COPYING .couch FILES FROM A RUNNING SERVER IS NOT SAFE. The
// append-only format means you may copy a torn write.
//
// For a logical dump: couchbackup, or stream _all_docs with
// include_docs and re-POST to _bulk_docs with new_edits=false to
// preserve revisions.

// Verify with assertions, not with "the server responded":
//   curl -s http://restored:5984/survey | jq '.doc_count, .doc_del_count'
//   curl -s 'http://restored:5984/survey/_design/conflicts/_view/all?reduce=true'
//   ... and your three capstone invariants.

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.