MVCC, Conflicts and the Changes Feed

Article · 7:00

Revision trees, what a conflict actually is, detecting and resolving them deterministically, and the changes feed in all three modes.

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

Revisions form a tree, not a chain. Normally each update extends a linear branch. But when two replicas each update the same document from the same parent revision and then replicate, the tree branches - and CouchDB keeps both branches. That is a conflict.

A conflict is not an error. CouchDB does not refuse the replication and does not merge the documents. It stores both revisions, picks one deterministically as the winning revision - the one with the longer revision history, and the higher revision hash as the tiebreaker - and lists the other under _conflicts. A GET on the document returns the winner with no indication anything is wrong.

That last sentence is the single most important operational fact in CouchDB. A conflicted document looks completely normal. The losing revision contains data a user entered, on a device, deliberately - and it is invisible unless you ask for it. An application that never checks _conflicts silently discards real work, and nobody notices for months.

So conflict detection must be explicit: ?conflicts=true on a read, or a view that emits documents with conflicts, which is the standard pattern for finding them at scale.

Resolution policies, in increasing order of quality:

  • Last write wins by the winning revision - what you get by doing nothing. Deterministic, and the "winner" is chosen by revision tree shape, which has no relationship to which data is more correct. Almost never right.
  • Last write wins by timestamp - better, and requires a timestamp you trust. Device clocks are not trustworthy; this is a real limitation on offline-first applications.
  • Field-level merge - take each field from whichever revision changed it. Good where fields are independent, and needs a known base revision to tell what changed.
  • Domain merge - apply the business rule. Two devices each added answers, so the union of the answers is correct. Two devices set contradictory review statuses, so escalate to a human.
  • Avoid the conflict structurally - split the document so the two edits touch different documents, or model the data as an append-only log of immutable events and derive the current state. This is the best answer when the domain allows it, and it is a Module 2 decision rather than a Module 3 one.

Resolution means: read all conflicting revisions, compute the resolved document, write it as a new revision on the winner, and delete the losing revisions explicitly. Resolution is not complete until the losers are gone.

The changes feed is CouchDB's event stream: GET /_changes returns every change since a sequence number. feed=normal returns and closes; feed=longpoll holds the connection until something changes; feed=continuous streams indefinitely. With since you resume exactly; with a filter or selector you receive only what you care about. It is the basis of replication and the right way to build reactive features.

Laboratory exercise 3 - produce conflicts, then resolve them.

Build a service against CouchDB and run at least 50 concurrent clients. Measure the 409 rate and show the retry loop handling it.

Then produce real conflicts, which requires two databases: set up a second CouchDB (or PouchDB), replicate, disconnect, update the same document in both with different changes, reconnect and replicate back. Confirm the conflict exists. Then show that a plain GET hides it completely - this demonstration is the point of the module.

Build a conflict-finding view and implement three resolution policies: last-write-wins by timestamp, field-level merge, and a domain merge that unions the answer arrays. Run all three against the same conflict set and compare what each loses.

Finally, build a changes-feed consumer in continuous mode, kill it, and restart it from its stored since sequence, proving nothing was missed.

Deliverable: the service, the 409 rate under load, the conflict creation procedure, evidence that GET hides a conflict, the conflict-finding view, all three resolution policies with a comparison of data lost by each, and the resumable consumer.

JS Example 1 144 lines
// ------------------------------------------------------------------
// How to actually produce a conflict. One server cannot do it - you
// need two databases that diverge.
// ------------------------------------------------------------------
//   1. PUT /survey_a/doc  -> 1-abc
//   2. replicate survey_a -> survey_b    (both now at 1-abc)
//   3. DISCONNECT
//   4. PUT /survey_a/doc  (_rev 1-abc)   -> 2-aaa   answers added
//   5. PUT /survey_b/doc  (_rev 1-abc)   -> 2-bbb   status set
//   6. replicate survey_b -> survey_a
//
// Both 2-aaa and 2-bbb now exist in survey_a. The revision tree has
// BRANCHED. CouchDB stores both, picks a winner, and does not
// complain.

// ------------------------------------------------------------------
// THE MOST IMPORTANT FACT IN COUCHDB: a conflict is INVISIBLE.
// ------------------------------------------------------------------
//   curl -s http://.../survey_a/response:site-14:r001 | jq
//   { "_id": "...", "_rev": "2-bbb...", "status": "reviewed", ... }
//
// Completely normal. No warning. No error. And 2-aaa - containing
// answers a field worker typed on a tablet - is sitting there,
// invisible.
//
// You must ASK:
//   curl -s 'http://.../survey_a/response:site-14:r001?conflicts=true' | jq
const conflicted = {
  _id: "response:site-14:r001",
  _rev: "2-bbb...",                 // the WINNER
  status: "reviewed",
  _conflicts: ["2-aaa..."]          // the LOSER. Real data. Invisible.
};
// The winner is chosen by revision tree shape - longest history, then
// the higher hash. That has NO relationship to which data is more
// correct. An application that never reads _conflicts silently
// discards real work, and nobody notices for months.

// Find them at scale - the standard pattern:
const conflictView = {
  _id: "_design/conflicts",
  views: { all: { map: function (doc) {
    if (doc._conflicts) { emit(doc._id, doc._conflicts.length); }
  }.toString(), reduce: "_count" } }
};
//   GET /survey/_design/conflicts/_view/all
//   GET /survey/_design/conflicts/_view/all?reduce=true   <- the count
// PUT THIS IN MONITORING. A rising conflict count is an incident.

// ------------------------------------------------------------------
// Resolution. Read all revisions, compute, write, DELETE THE LOSERS.
// ------------------------------------------------------------------
//   GET /survey/response:site-14:r001?rev=2-aaa...
//   GET /survey/response:site-14:r001?rev=2-bbb...
//   or all at once:
//   GET /survey/response:site-14:r001?open_revs=["2-aaa...","2-bbb..."]

// POLICY 1 - last write wins by TIMESTAMP.
function resolveByTimestamp(revisions) {
  return revisions.reduce((a, b) =>
    (a.updatedAt > b.updatedAt) ? a : b);
}
// Better than doing nothing, and it needs a timestamp you TRUST.
// DEVICE CLOCKS ARE NOT TRUSTWORTHY - a tablet whose clock is two
// days fast wins every conflict forever. This is a real limitation
// on offline-first applications and your design must say how it
// handles it (server-stamped on push, or a logical clock).

// POLICY 2 - FIELD-LEVEL MERGE. Needs a known base revision.
function mergeFields(base, a, b) {
  const out = {...base};
  for (const k of Object.keys({...a, ...b})) {
    if (k.startsWith("_")) continue;
    const changedInA = JSON.stringify(a[k]) !== JSON.stringify(base[k]);
    const changedInB = JSON.stringify(b[k]) !== JSON.stringify(base[k]);
    if (changedInA && !changedInB) out[k] = a[k];
    else if (changedInB && !changedInA) out[k] = b[k];
    else if (changedInA && changedInB) out[k] = pickByRule(k, a[k], b[k]);
  }
  return out;
}
// Good where fields are independent, which is exactly the case
// Model B in Module 2 engineered away.

// POLICY 3 - DOMAIN MERGE. The best general answer: apply the rule.
function resolveSurveyResponse(revisions) {
  const byId = new Map();
  for (const rev of revisions) {
    for (const ans of rev.answers || []) {
      const prev = byId.get(ans.questionId);
      // Two devices each ADDED answers -> the UNION is correct. This
      // is a domain fact no generic merge could know.
      if (!prev || ans.answeredAt > prev.answeredAt) byId.set(ans.questionId, ans);
    }
  }
  const statuses = new Set(revisions.map(r => r.reviewStatus).filter(Boolean));
  return {
    ...revisions[0],
    answers: [...byId.values()].sort((x, y) =>
      x.questionId.localeCompare(y.questionId)),
    // CONTRADICTORY statuses: do NOT guess. Escalate to a human.
    reviewStatus: statuses.size > 1 ? "needs_human_review" : [...statuses][0],
    resolvedFrom: revisions.map(r => r._rev),   // audit trail
    resolvedAt: new Date().toISOString()
  };
}

// Writing the resolution. NOT COMPLETE until the losers are deleted:
//   POST /survey/_bulk_docs
const resolution = {
  docs: [
    { ...resolved, _id: "response:site-14:r001", _rev: "2-bbb..." },  // winner
    { _id: "response:site-14:r001", _rev: "2-aaa...", _deleted: true } // loser
  ]
};
// Skip the deletion and the conflict stays in _conflicts forever,
// your monitoring stays red, and the next resolution sees it again.

// ------------------------------------------------------------------
// THE CHANGES FEED: three modes, all resumable.
// ------------------------------------------------------------------
//   GET /survey/_changes?since=0&limit=100
//       -> returns and closes. `last_seq` is where you resume.
//
//   GET /survey/_changes?feed=longpoll&since=200000-g1A&timeout=60000
//       -> holds the connection until something changes
//
//   GET /survey/_changes?feed=continuous&since=200000-g1A&heartbeat=10000
//       -> streams indefinitely, one JSON object per line.
//          heartbeat keeps proxies from closing an idle connection -
//          omit it and a quiet feed dies silently at the load balancer.
const change = {
  seq: "200001-g1AAAA...",
  id: "response:site-14:r001",
  changes: [{ rev: "3-ccc..." }],
  doc: { /* with include_docs=true */ },
  deleted: true                     // present only for tombstones
};
// PERSIST last_seq WITH the side effect, or you get at-least-once.
// Same problem, same two answers, as every other change feed.

// Server-side filtering - a selector is faster than a JS filter:
//   POST /survey/_changes?filter=_selector&since=...
//   { "selector": { "type": "response", "surveyId": "site-14" } }

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.