Replica Sets, Concerns, Transactions and Change Streams

Article · 7:00

Primary and secondaries, elections and step-downs, read and write concerns with their real guarantees, multi-document transactions, and change streams with resume tokens.

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

A replica set is a primary and its secondaries. All writes go to the primary; secondaries apply the primary's oplog. If the primary becomes unreachable, the remaining members hold an election and promote one - typically within 10 to 12 seconds with default settings, during which writes fail. The driver detects the new primary and reconnects automatically, so the application sees a burst of errors and then recovery, which means every write path needs retry handling even without transactions.

Write concern is how durable you want a write to be before it is acknowledged:

  • {w: 1} - the primary has it in memory. Fast. A primary failure immediately after can lose it.
  • {w: "majority"} - a majority of members have it. This is the one that means "will not be lost in a failover", and it is the default in recent versions.
  • {j: true} - written to the journal on disk, so it survives a process crash.
  • {w: "majority", j: true} - both. The strongest, and the slowest.

Read concern is how current and how stable you want a read to be:

  • "local" - whatever this node has. May include writes that are later rolled back.
  • "majority" - only data acknowledged by a majority, so it cannot be rolled back. This is the one that pairs with w: "majority" to give you read-your-writes across a failover.
  • "linearizable" - a real-time guarantee on a single document, at significant cost.
  • "snapshot" - a consistent point-in-time view, used by transactions.

Read preference is where to read: primary, primaryPreferred, secondary, nearest. Reading from secondaries scales reads and gives you eventually consistent data, with replication lag you must measure, not assume.

Multi-document transactions exist and should be rare. MongoDB has supported ACID transactions across documents since 4.0, and they work. But a document model that needs them often for its core writes is usually a relational model wearing BSON - the single-document atomicity you get for free is the point of the design. Transactions also cost: a 60-second default time limit, a conflict-and-retry model, and performance that degrades with the number of documents involved. Use them for genuine cross-entity invariants; do not use them to paper over a model that should have embedded.

Change streams are one of MongoDB's best features. A change stream is a durable, resumable, ordered feed of changes to a collection, database or deployment, built on the oplog and exposed as a cursor. With a resume token you can restart exactly where you left off after a crash - which is what makes it an integration mechanism rather than a notification toy. fullDocument: "updateLookup" includes the document after the change.

Laboratory exercise 3 - a service through a failover.

Build a service that places orders and run at least 100 concurrent clients.

Then step down the primary while the load runs. Measure: how long writes failed, how long the election took, how many requests errored, and - the important one - whether any acknowledged write was lost. Run this twice: once with {w: 1} and once with {w: "majority"}, and record the difference. This is the most instructive single experiment in the course.

Measure replication lag under write load, then read the same document from the primary and from a secondary immediately after a write and show the stale read.

Implement one genuine multi-document transaction (an order placement that decrements inventory in another collection), demonstrate a write conflict and its retry, and then implement the same operation without a transaction by changing the model, and compare.

Build a change-stream consumer that reacts to new orders. Kill it mid-stream and restart it from its stored resume token, proving no event was missed and none processed twice.

Deliverable: the service, the failover measurements for both write concerns, the stale read demonstration with measured lag, the transaction and its no-transaction equivalent with timings, and the resumable consumer with evidence of exactly-once processing.

JS Example 1 124 lines
// ------------------------------------------------------------------
// WRITE CONCERN: the experiment that teaches the most in this course.
// ------------------------------------------------------------------
// {w: 1} - the primary has it IN MEMORY. Fast, and a primary failure
// immediately after can lose it:
db.orders.insertOne(doc, {writeConcern: {w: 1}});

// {w: "majority"} - a majority of members have it. THIS is what
// "will not be lost in a failover" means:
db.orders.insertOne(doc, {writeConcern: {w: "majority", wtimeout: 5000}});

// {j: true} - on disk in the journal; survives a process crash:
db.orders.insertOne(doc, {writeConcern: {w: "majority", j: true}});
//                                                     ^^^^^^^ strongest
//                                                     and slowest

// Run the failover lab with w:1 and then w:"majority" and count the
// lost acknowledged writes. The difference is the point.
db.adminCommand({replSetStepDown: 60, force: true});
//   writes fail for ~10-12 s while an election runs
//   the driver finds the new primary and reconnects automatically
//   so the application sees a BURST OF ERRORS then recovery
//   -> every write path needs retry handling, transactions or not

// ------------------------------------------------------------------
// READ CONCERN and READ PREFERENCE: different questions.
// ------------------------------------------------------------------
// "majority": only data a majority has, so it CANNOT be rolled back.
// Pair it with w:"majority" for read-your-writes across a failover:
db.orders.find({_id: id}).readConcern("majority");

db.orders.find({}).readPref("secondary");     // scales reads;
                                              // EVENTUALLY consistent
db.orders.find({}).readPref("nearest");       // lowest latency

// Measure the lag. Do not assume it:
rs.status().members.map(m => ({
  name: m.name, state: m.stateStr,
  lagSeconds: m.optimeDate
    ? (rs.status().members.find(x => x.stateStr === "PRIMARY").optimeDate
       - m.optimeDate) / 1000 : null
}));
// Then write, immediately read from a secondary, and show the stale
// result. That is what "eventually consistent" costs, in your
// environment, under your load.

// ------------------------------------------------------------------
// TRANSACTIONS: they work, and they should be RARE.
// ------------------------------------------------------------------
const session = db.getMongo().startSession();
try {
  session.startTransaction({
    readConcern: {level: "snapshot"},
    writeConcern: {w: "majority"},
    maxCommitTimeMS: 5000
  });
  const inv = session.getDatabase("shop").inventory;
  const ord = session.getDatabase("shop").orders;

  const res = inv.updateOne(
    {productId: pid, stock: {$gte: qty}},
    {$inc: {stock: -qty}}
  );
  if (res.modifiedCount === 0) throw new Error("insufficient stock");

  ord.insertOne({customerId: cid, lines: [{productId: pid, quantity: qty}],
                 status: "pending"});
  session.commitTransaction();
} catch (e) {
  session.abortTransaction();
  // TransientTransactionError or UnknownTransactionCommitResult:
  // retry the WHOLE transaction. The driver helper does this:
  //   session.withTransaction(async () => { ... })
  throw e;
} finally { session.endSession(); }
//
// The costs: a 60 s default time limit, a conflict-and-retry model,
// and performance that degrades with the number of documents touched.
// A model that needs transactions for its CORE writes is usually a
// relational model wearing BSON. Single-document atomicity is free
// and is the point of the design.

// The same operation WITHOUT a transaction - by changing the model so
// the invariant lives in one document:
db.product.findOneAndUpdate(
  {_id: pid, "variants.sku": sku, "variants.stock": {$gte: qty}},
  {$inc: {"variants.$.stock": -qty},
   $push: {reservations: {orderId: oid, qty: qty, at: new Date()}}},
  {returnDocument: "after"}
);
// One atomic document update. No session, no retry loop, no time
// limit. Compare the two on latency and throughput in the lab.

// ------------------------------------------------------------------
// CHANGE STREAMS: resumable, ordered, durable. The best feature here.
// ------------------------------------------------------------------
const stream = db.orders.watch([
  { $match: { operationType: {$in: ["insert", "update"]},
              "fullDocument.status": "paid" } }
], {
  fullDocument: "updateLookup",   // the document AFTER the change
  // Restart exactly where we stopped. This is what makes it an
  // integration mechanism rather than a notification toy:
  resumeAfter: storedResumeToken
});

while (stream.hasNext()) {
  const change = stream.next();
  // process(change.fullDocument)
  // PERSIST THE TOKEN with the side effect, ideally in the same
  // transaction, or you get at-least-once instead of exactly-once:
  db.stream_state.updateOne(
    {_id: "orders-notifier"},
    {$set: {token: change._id, at: new Date()}},
    {upsert: true}
  );
}
// Kill the consumer mid-stream, restart from the stored token, and
// prove nothing was missed and nothing processed twice.
//
// One limit: resuming needs the oplog to still contain that point.
// Size the oplog for your worst expected consumer downtime:
db.getSiblingDB("local").oplog.rs.stats().maxSize / 1024 / 1024;
db.adminCommand({replSetResizeOplog: 1, size: 16384});

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.