Capstone - Offline Field Survey Application

Article · 6:00

Bidirectional replication, deterministic conflict resolution, and a design defended on what it loses as well as what it keeps.

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

The system. An offline field survey application. Collectors use tablets in locations with no connectivity, fill in survey responses with answers and photo metadata, and sync when they reach signal. Reviewers work against the server. The same response may be edited on a device and on the server while disconnected.

Three invariants must hold:

  1. No answer entered on a device is ever lost, including through a conflict.
  2. Conflict resolution is deterministic - the same conflicting revisions resolve to the same document regardless of which replica resolves them or in what order.
  3. The conflict count returns to zero after resolution runs, and every resolution is traceable to the revisions it came from.

Invariant 2 is this capstone's distinguishing requirement. If the device and the server can both resolve, and they resolve differently, their resolutions conflict with each other - an unbounded loop. Determinism means the policy is a pure function of the conflicting revisions, with no dependence on local time, local state or ordering. Prove it: resolve the same conflict set on two replicas independently and show the results are byte-identical.

What is assessed. 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical, 30% capstone. Three things carry the capstone.

Deterministic resolution, demonstrated. Not described - demonstrated, with a test that resolves the same conflicts twice in different orders and compares. And the policy must say what it does with genuinely contradictory data, which is usually "escalate", not "pick one".

Measured sync performance against a declared baseline. Declare it first: document count and size, filter, device connectivity profile, and measured initial sync time, incremental sync time, time to first write after reconnect, and the conflict rate. Sync time, not query latency, is this system's user-facing performance number.

A defensible account of failure modes, operational limits and cost. Compaction must be in the runbook with its space requirement. The device clock problem must be addressed explicitly. And the cost model must include the thing CouchDB deployments get wrong: disk, which is larger than the data because of revisions, tombstones and view indexes.

Deliverables: architecture diagram with the replication topology; data model with the conflict surface argued; source code including the resolution function and the device client; reproducible test dataset; sync benchmark report; security review including the validation function; recovery runbook with measured RPO and RTO; cost model; and a short design defence.

JS Example 1 122 lines
// ================= Invariants, as runnable assertions ==============
// Schedule these. Run after every sync cycle and every restore.

// 1. No answer entered on a device is ever lost. Every answer that
//    ever existed in ANY revision must be present in the current one.
//    This is the invariant that makes the whole system worth building,
//    and the only way to check it is to walk the conflicts:
//    GET /survey/_design/conflicts/_view/all
//    then for each: GET /survey/<id>?open_revs=all
//    and assert the union of answers equals the current answers.

// 2. Conflict count returns to ZERO after resolution.
//   GET /survey/_design/conflicts/_view/all?reduce=true
//   -> {"rows":[{"key":null,"value":0}]}

// 3. Every resolution is traceable.
const traceability = {
  _id: "_design/audit",
  views: { resolutions: { map: function (doc) {
    if (doc.resolvedFrom) emit(doc.resolvedAt, doc.resolvedFrom);
  }.toString() } }
};

// ================= DETERMINISM: the capstone's real problem ========
// If the device and the server both resolve, and resolve DIFFERENTLY,
// their resolutions CONFLICT WITH EACH OTHER - an unbounded loop.
//
// Determinism means the policy is a PURE FUNCTION of the conflicting
// revisions: no local time, no local state, no dependence on order.
function resolveDeterministic(revisions) {
  // 1. SORT the input. Without this, the output depends on the order
  //    the revisions happened to arrive, which differs per replica.
  const revs = [...revisions].sort((a, b) => a._rev < b._rev ? -1 : 1);

  // 2. Merge answers by questionId. Tie-break on a field in the DATA,
  //    never on Date.now() and never on local clock time.
  const byQ = new Map();
  for (const r of revs) {
    for (const a of r.answers || []) {
      const prev = byQ.get(a.questionId);
      if (!prev ||
          a.answeredAt > prev.answeredAt ||
          (a.answeredAt === prev.answeredAt && a.deviceId > prev.deviceId)) {
        byQ.set(a.questionId, a);        // deviceId breaks exact ties
      }                                  // deterministically
    }
  }

  // 3. Contradictions ESCALATE. Do not guess.
  const statuses = [...new Set(revs.map(r => r.reviewStatus).filter(Boolean))];

  return {
    ...revs[0],
    answers: [...byQ.values()].sort((a, b) =>
      a.questionId.localeCompare(b.questionId)),   // sorted OUTPUT too
    reviewStatus: statuses.length > 1 ? "needs_human_review" : statuses[0],
    resolvedFrom: revs.map(r => r._rev).sort(),
    // resolvedAt is derived from the DATA, not from the clock, or the
    // two replicas produce different documents:
    resolvedAt: revs.map(r => r.collectedAt).sort().slice(-1)[0]
  };
}

// PROVE IT. This test is the deliverable:
//   const a = resolveDeterministic([r1, r2, r3]);
//   const b = resolveDeterministic([r3, r1, r2]);
//   assert(JSON.stringify(a) === JSON.stringify(b));
// Then run it on TWO REPLICAS independently and compare byte for byte.

// ================= Declare the baseline BEFORE measuring ===========
//
//   Topology:  1 server cluster (n=3, q=8) + 20 PouchDB devices
//   Filter:    selector on collectorId, per device
//   Dataset:   50,000 responses, ~4 KB each, ~2,500 per device
//   Device:    offline 8 h, then 4G
//
//   Claim - and note that SYNC TIME, not query latency, is this
//   system's user-facing performance number:
//     initial device sync          < 90 s
//     incremental sync (8 h work)  < 15 s
//     time to first local write    <  1 s   (must be instant: offline)
//     conflict rate                <  2% of synced documents
//     resolution pass (1,000)      < 10 s
//     restore RTO                  < 20 min, measured
//
//   GET /_scheduler/docs | .info      <- revisions_checked, docs_written
//   PouchDB: sync.on('change', i => ...) timings

// ================= Cost: disk is bigger than the data ==============
//   live JSON                 180 MB
//   + old revisions           x2 to x4 until compaction
//   + tombstones              grow forever under churn
//   + view indexes            often as large as the data again
//   + compaction headroom     needs free space = live data size
//   -> provision SEVERAL TIMES the data size. This is the single
//      thing CouchDB deployments get wrong.
//   GET /survey  -> sizes.file, sizes.active, doc_del_count

// ================= Failure modes ==================================
//   conflict nobody resolves   SILENT DATA LOSS. A plain GET looks
//                              normal. Monitor the conflict count;
//                              this is alarm number one.
//   device clock 2 days fast   wins every timestamp conflict forever.
//                              Server-stamp on push, or use a
//                              logical clock.
//   both ends resolve          resolutions conflict with each other.
//                              ONE location, or a pure function.
//   filter changed             documents that no longer match STAY on
//                              the device. Forever.
//   compaction cannot run      disk full enough to block compaction
//                              stays full. Monitor the RATIO.
//   view map function edited   full rebuild, hours. Blue-green the
//                              design document.
//   node down                  writes return 202 Accepted, not 201.
//                              Check the status code.
//   oplog-equivalent: none     CouchDB's changes feed is retained as
//                              long as the database, so a consumer
//                              can always resume. One fewer worry
//                              than most systems.
//
// Verify after EVERY sync cycle and restore with the three assertions
// above. "Replication says running" is not verification.

Open this example in the editor and change it. Nothing you type is saved.

Where to go from here

Longer reading about this subject, written alongside the course.

Course guide How to work through this course Why you need two databases from Module 3, the demonstration that changes how you think, what to skip, and when CouchDB is the right answer. 3 min read

Discussion

No questions on this topic yet. Sign in to ask the first one.