Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 70 ยท Transactions and consistency

Read and Write Concerns

Tune durability and visibility in MongoDB: write concern w, j and wtimeout, majority writes, read concern levels, read preference and causal consistency.

A MongoDB deployment normally keeps several copies of your data on different servers (a replica set, see Replica Sets). That raises two questions every time you touch the data. When I write, how many copies must have it before the server tells me "done"? When I read, which copy do I ask, and how sure can I be that the answer will never be undone? Write concern answers the first question, read concern and read preference answer the second.

These settings are a dial between speed and safety. This lesson shows the real options in mongosh and driver syntax, then uses stand-in simulations written in plain JavaScript to show what each setting protects you from (see The Practice Engine Used in This Tutorial). The simulations are teaching models, not the real replication protocol.

Three dials

Write concern How many copies before "acknowledged".
Read concern How safe the data you read is.
Read preference Which server answers the read.

Faster settings risk stale or rolled-back data.

1 / 2

Write concern: w, j and wtimeout

A write concern is attached to a write (or set as a default on the connection or collection):

JavaScript
db.orders.insertOne(
  { _id: 1, total: 42 },
  { writeConcern: { w: "majority", j: true, wtimeout: 5000 } }
)
  • w is how many members must acknowledge the write. 1 means only the primary; a number such as 2 means that many members; "majority" means a majority of the voting, data-bearing members; 0 means "do not wait at all" (fire and forget, errors are not reported).
  • j: true waits until the write is in the on-disk journal of the acknowledging members, so it survives a process crash or power loss on those machines. Without it, a write may be acknowledged while it is still only in memory.
  • wtimeout (milliseconds) limits how long to wait for the w requirement. If it expires you get a write concern error, but the write may still have been applied. A timeout means "I do not know that enough members have it", not "it failed". Keep writes idempotent so you can safely check or retry.

Recent MongoDB versions default to w: "majority" for most deployments, but check the documentation of your version, because the default depends on the deployment (for example, replica sets with arbiters).

Why does majority matter? A write that reached only the primary can be lost. If the primary fails before its secondaries copy the write, a secondary that does not have the write becomes the new primary, and when the old primary rejoins it has to roll back the unreplicated write. A write acknowledged by a majority is on at least one member of every majority, so any new primary must have it, and it is never rolled back.

The simulation below models three members. Each acknowledged write is copied to as many secondaries as the write concern forced the primary to wait for; the rest "lag". Then the primary crashes, and the most up-to-date survivor takes over.

JS Why w: majority survives a failover

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With w: 1 every acknowledged order vanishes in this model, because no secondary had received it. With a majority concern, nothing acknowledged is lost. The price is latency: the client waits for a network round trip to another member for every write. In the real system, secondaries usually keep up within milliseconds, so the lost-write window for w: 1 is small but real.

Read concern: how safe is what you read?

A read concern chooses the level of durability guarantee for the data returned:

  • local returns the most recent data on the server you asked, even if it has not been replicated. This is the default for reads on the primary. That data could still be rolled back.
  • available is like local but is used for sharded setups that may return orphaned documents, trading correctness for speed. It is rarely what you want.
  • majority returns only data acknowledged by a majority, which cannot be rolled back.
  • linearizable guarantees you see the effects of every majority-acknowledged write that completed before the read began. It is the strongest and slowest, applies to reads on the primary, and works on a single document.
  • snapshot gives a consistent point-in-time view inside multi-document transactions.
JavaScript
db.orders.find({ _id: 1 }).readConcern("majority")

Reading with majority while writing with w: "majority" gives you the strong, familiar behaviour: you never see data that a failover could take away.

Read preference: which member answers?

Read preference chooses the server, not the safety level:

Mode Reads from
primary (default) the primary only
primaryPreferred the primary, or a secondary if no primary is available
secondary secondaries only
secondaryPreferred a secondary, or the primary if none is available
nearest the member with the lowest network latency

Secondaries replicate asynchronously, so reading from them can return stale data. That is acceptable for dashboards and analytics and wrong for "show me the order I just placed". Spreading reads over secondaries does not increase the write capacity, and it can hide a replication problem until it hurts, so use it deliberately.

The next simulation shows how the three ideas combine. A new value is on the primary only; we read it with different settings, then let it replicate.

JS Local, majority and secondary reads

Press Run (or Ctrl + Enter) to see the console output here.

No output.

First the primary's local read returns v2, which a failover could still undo, while majority returns the older but safe v1, and the secondary is simply behind. Once one secondary has v2 it is on a majority: the majority read advances, and the other secondary is still stale until it catches up.

Causal consistency

Sometimes you want a guarantee that sits between "read anything" and "read only the newest": read your own writes, and see writes in the order they happened. A causally consistent session provides it, even when reads go to secondaries. The driver tracks the operation time of your writes and asks the secondary to wait until it has caught up to that point before answering.

JavaScript
const session = client.startSession({ causalConsistency: true });
await orders.insertOne({ _id: 7, total: 10 }, { session, writeConcern: { w: "majority" } });
const doc = await orders.findOne({ _id: 7 }, { session, readPreference: "secondary", readConcern: { level: "majority" } });

For the guarantees to hold, use majority read and write concerns within the session. This is useful for scaling reads while keeping "I just saved it, so I must see it" true for the user who saved it.

Picking settings

  • Money, orders, anything you must not lose: w: "majority" (with j: true if your durability policy asks for it) and readConcern: "majority" where you read it back.
  • High-volume, loss-tolerant data such as metrics or click logs: w: 1 can be a conscious trade for speed.
  • Dashboards and reports: secondary reads with local are usually fine.
  • After a timeout: treat the write as unknown, and re-check or make it idempotent (Atomicity and Single-Document Writes).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What can happen to a write acknowledged with w: 1 if the primary fails right afterwards?

    w: 1 only waits for the primary. If a secondary without the write is elected, the old primary rolls the write back when it rejoins.
  2. 2. What does a wtimeout expiry tell you?

    A write concern timeout is about acknowledgement, not about whether the write happened. That is why retries should be idempotent.
  3. 3. Which read concern returns only data that cannot be rolled back?

    majority returns data acknowledged by a majority of members. local can return data that is still unreplicated, and primary is a read preference, not a concern.
  4. 4. Which statement about read preference is correct?

    Read preference selects the member. Secondaries replicate asynchronously, so their data can lag.
  5. 5. What does a causally consistent session help you do?

    The driver passes along the operation time so a secondary waits until it has caught up before answering, as long as majority read and write concerns are used.

Summary

  • Write concern (w, j, wtimeout) says how many members must acknowledge a write and whether it must be journaled; w: "majority" protects against rollbacks after failover.
  • A wtimeout error means "unconfirmed", not "failed": design for idempotent retries.
  • Read concern (local, majority, linearizable, snapshot) sets how safe the returned data is; read preference sets which member answers and can return stale data from secondaries.
  • A causally consistent session gives read-your-own-writes across members when used with majority concerns.
  • Choose the strong settings for data you cannot lose, and the fast ones for data you can.
  • The TryIts are simplified JavaScript simulations of the ideas, not the real replication protocol.

Next, watch data change in real time with Change Streams and Real-Time Updates.