Replica sets, transactions and consistency

Elections, write concern, read preference, causal consistency, and multi-document transactions and their cost.

12 min read🍃 MongoDB

A single MongoDB node is a development setup. Production is a replica set: several copies of the data with one accepting writes, and everything about durability and consistency is a setting on the write or the read that says how many of those copies must be involved. The defaults are safer than they were; the settings still decide whether a confirmed write can vanish and whether a read can see it.

Replica set basics

A replica set is one primary and, typically, two secondaries, plus an optional arbiter that votes but holds no data.

Every write goes to the primary and is recorded in its oplog, an ordered log of operations. Secondaries tail the oplog and apply it. It is the same shape as the SQL course's replication lesson, with the same lag.

When the primary stops answering heartbeats (the default timeout is ten seconds), the remaining members hold an election, and a secondary with a majority of votes becomes primary. The old primary, when it returns, steps down and rolls back any writes the new primary never received, writing them to a file for a human to look at.

Two consequences follow for a Java service.

  • The driver takes the seed list and discovers the topology itself. So the connection string names the set (replicaSet=rs0), and the driver follows the primary through an election. It retries a write once (retryWrites=true, the default), so that a failover in the middle of an insertOne is not an error the application sees.
  • An odd number of voting members matters. Two data nodes cannot elect anyone when one is gone, which is why the arbiter exists and why a three-member set is the minimum that survives a node.

Write concern: how many copies before "done"

java
collection.withWriteConcern(WriteConcern.MAJORITY).insertOne(order);

The write concern says how many members must have the write before the driver returns. w: 1 is the primary only — fast, and a write the primary acknowledged can be rolled back if it fails before a secondary copied it. w: "majority" (the default since 5.0) waits for a majority of voting members to have it in their journal, which is the point at which an election cannot lose it; it costs a round trip to the secondaries per write. w: 0 does not wait for anything and is for metrics you can lose. j: true adds a journal flush on the members counted. Set it per operation for the writes that are money and per collection for the rest; and set wtimeout, because a majority write with a secondary down waits forever otherwise.

The SQL course's "commit" was one machine's fsync. Here "committed" has a number in it, and the number is what a durability review asks for.

Read preference and read concern

Read preference is which member answers: primary (the default; every read sees the latest write), primaryPreferred, secondary, secondaryPreferred, nearest. Reading from secondaries scales reads and offloads the primary, at the cost the replication lesson named: lag, so a read may return a state from seconds ago, and a client that writes then reads its own write from a secondary may not find it. Route analytical and report queries to secondaries; keep anything a user just changed on the primary.

Read concern is how settled the data must be:

  • local returns whatever the member has, including writes that may still be rolled back.
  • majority returns only data acknowledged by a majority, so a read can never show a write that later disappears.
  • linearizable on the primary additionally confirms the member still is the primary. Use it for the read-then-decide case where a stale primary would be catastrophic (a lease check, a uniqueness check outside a unique index).

majority reads and majority writes together give the guarantee most services want: what you read was durable, and what you wrote will be seen.

Causal consistency ties the two across a session. With a ClientSession, reads after a write in the same session are guaranteed to see that write, even from a secondary. The driver sends the write's timestamp along, and the secondary waits until it has caught up. That is read-your-own-writes as a session property rather than a routing rule.

Multi-document transactions, and their cost

A single-document write is atomic on its own — every field, every embedded array, one document, all or nothing — and the document-modelling lesson's advice to put what changes together in one document is what makes most applications need no transaction at all. When two documents must change together (a ledger and a balance in separate collections, a transfer between two accounts), MongoDB 4.0+ has multi-document transactions on a replica set:

java
try (ClientSession session = client.startSession()) {
    session.withTransaction(() -> {
        accounts.updateOne(session, eq("_id", from), inc("balancePaise", -amount));
        accounts.updateOne(session, eq("_id", to), inc("balancePaise", amount));
        ledger.insertOne(session, entry);
        return null;
    }, TransactionOptions.builder().writeConcern(WriteConcern.MAJORITY).build());
}

They are real ACID transactions, and they are not free:

  • snapshot isolation across the documents;
  • locks on the documents written (a concurrent write to the same document aborts with a transient error that withTransaction retries);
  • a default 60-second lifetime;
  • a throughput cost that makes a transactional workload on MongoDB slower than the same workload on PostgreSQL.

Spring Data's @Transactional with a MongoTransactionManager wraps the same session. Use transactions for the few writes that genuinely span documents, and keep them short. Treat "we need transactions everywhere" as the signal that the model is relational and the store choice should be revisited. That is the data-store lesson's question, asked late.

Sharded clusters, in one section

When a replica set's data or write load outgrows one primary, a sharded cluster splits a collection across several replica sets by a shard key. mongos routers sit in front, and config servers hold the map.

Everything the replication-and-sharding lesson in the system-design course said applies:

  • The shard key decides whether a query goes to one shard (targeted, fast) or all of them (scatter-gather, slow).
  • A monotonically increasing key (ObjectId, a timestamp) sends every insert to one shard.
  • A key with low cardinality cannot spread.
  • The key cannot be changed without rewriting the collection (5.0 allows resharding, expensively).

Choose the key from the access patterns: the field every frequent query filters on. Hash it if the queries are equality-only and the writes must spread. Know that transactions across shards and $lookup across shards are possible and slower still. Most services never need sharding. A replica set with a well-modelled schema serves far more than teams expect.

Under the hood: the oplog's actual shape, and how a stale primary's writes are undone

The oplog is not a generic transaction log. It is an ordinary MongoDB collection, local.oplog.rs, and it is capped: a fixed maximum size, allocated up front, where the oldest entries are overwritten once it is full. It is the same bounded-and-evicted shape the redis-and-caching course covers for a cache, applied here to a log instead.

That fixed size is what makes "how far behind can a secondary fall before it can no longer catch up" a real, measurable number. The span of time the oplog currently covers is the deadline (rs.printReplicationInfo() reports it as the oplog window).

A secondary that is disconnected longer than that window returns and finds the entries it needs have already been overwritten. It cannot replay forward from where it left off, and it must resync from scratch, copying every collection over again.

Sizing the oplog (or, since 4.4, letting it grow to a configured minimum retention in hours) is capacity planning for exactly this scenario. It is the kind of setting that is invisible until the one night a secondary is offline for maintenance longer than expected.

The entries themselves are not a copy of the operation you issued. They are its idempotent equivalent. An application calls updateOne({_id}, {$inc: {balancePaise: -500}}), but the oplog does not record "decrement by 500". For most operators it records the operation applied to a specific document, in a form that is safe to apply more than once. (For a document targeted by _id, an update on a single field is stored in a way that reapplying it never double-counts. The detail intentionally is not "replay the exact literal command.")

This matters for a specific, real failure mode. Replication is at-least-once, not exactly-once, so a secondary can see the same oplog entry twice after a network retry or a resync that overlaps already-applied entries. Idempotence is the only reason that does not silently apply $inc twice.

It is also why the document-modelling lesson's caution about save() replacing the whole document is a replication concern too, not just a concurrency one. A whole-document replace is trivially idempotent (writing the same full document twice leaves it the same), where a naive, non-idempotent encoding of $inc would not be.

w: "majority" does not simply mean "wait until a majority of secondaries have copied this oplog entry". It means wait until the entry is at or before the majority commit point. That is a position in the oplog that the primary tracks as the highest point acknowledged, in their own oplogs, by a majority of voting members (journaled, since j is implied by majority by default).

The primary advances that point continuously as secondaries report their progress. readConcern: "majority" reads are served from a snapshot taken at the majority commit point, not from "whatever the local node currently has". That is the actual mechanism behind "a majority read can never see a write that later rolls back": it reads data the storage engine still has available from before the write in question, if that write has not yet crossed the commit point.

Causal consistency layers on top of this same position. Every write and read carries a cluster time, a logical timestamp the whole replica set agrees on and gossips between members on every message. A ClientSession sends the cluster time of your last operation along with the next one. The node you read from can then block until its own applied position has caught up to at least that timestamp, before answering. The session, not the query, is what carries the causal guarantee.

Try it yourself

Reason through an oplog window incident

A replica set's oplog covers eight hours of writes (rs.printReplicationInfo()). A secondary goes offline for maintenance at 10:00 and the operator plans to bring it back at 17:00 — nine hours later.

What actually happens when it reconnects, and why "it'll just catch up" is the wrong assumption here

The secondary went offline for nine hours, and the oplog only retains eight hours of history. By 17:00, the operations from roughly 10:00 to 11:00 have already been overwritten by newer entries, because the capped collection recycled that space to make room for everything written since.

When the secondary reconnects, it asks to resume replication from the last operation it applied (around 10:00), and that operation is no longer in the oplog. It cannot pick up where it left off. The driver-visible symptom is the secondary entering the RECOVERING state and starting an initial sync. That copies every collection from another member from scratch, which is far more expensive than replaying an hour of missed writes would have been, and it holds that member out of the read pool for the duration.

The fix is not something the returning secondary can do differently. It is capacity planning ahead of time: an oplog window comfortably longer than any planned maintenance window, checked with rs.printReplicationInfo() before the maintenance, not during it.

Misconceptions

  • "The oplog is a literal record of the commands the application sent." It stores an idempotent, per-document equivalent of each write, not the original command. A $inc is not replayed as "decrement again", because replication can and does deliver the same entry more than once (a retry, a resync that overlaps), and only an idempotent log makes that safe.
  • "readConcern: majority means every member of the set agrees on the data right now." It means the primary is serving a snapshot from the majority commit point — data durable enough to never roll back. It says nothing about what a secondary read (a different setting, read preference) returns, and it does not by itself confirm the node answering is still the current primary; that stronger guarantee is readConcern: linearizable.

Sources

  • MongoDB Manual, "Replication" (the oplog, local.oplog.rs, the oplog size and window, initial sync).
  • MongoDB Manual, "Read Concern" and "Write Concern" (the majority commit point, j, wtimeout).
  • MongoDB Manual, "Causal Consistency and Read Concern" (cluster time, ClientSession causal guarantees).
Progress is saved on this device and to your account when signed in.