Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk10 min

MongoDB Consistency Levels: CAP, PACELC, and Choosing the Right Settings

MongoDB is not simply CP or AP. Understand what its consistency controls guarantee, what happens during partitions, and how to choose settings for your workload.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

MongoDB is not simply “CP” or “AP.” Its replica-set write path generally favors consistency over availability when a majority cannot be reached, while read and write settings let applications trade freshness, durability, availability, and latency for each workload. CAP describes the trade-off during a network partition; PACELC also explains why stronger coordination can cost latency when the cluster is healthy.

What “consistency” means in MongoDB

Consistency is not one switch. It can mean that a read reflects the latest completed write, that related operations remain in causal order, that a multi-document operation sees one coherent snapshot, or that an acknowledged write survives a failure. MongoDB exposes these concerns through different controls, so “strong” or “eventually consistent” alone is too imprecise to guide a deployment.

As an Amazon Associate I earn from qualifying purchases.

  • Linearizability: a read reflects successful writes completed before it began, in real-time order, or the read fails.
  • Causal consistency: related operations respect cause-and-effect order, such as a read following a write it depends on.
  • Read-your-writes and monotonicity: a client sees its own writes, does not move backward to an earlier version on later reads, and has its writes applied in issue order.
  • Snapshot consistency: multiple reads see a coherent point-in-time view.
  • Durability: an acknowledged write is protected against specified failures or rollback.
  • Replica lag: a secondary may temporarily show older data than the primary.

MongoDB’s replica-set architecture centers writes on a primary and replicates them through the oplog. Voting members participate in elections; a primary that cannot maintain a majority cannot continue to provide majority-acknowledged writes. In a sharded cluster, each shard is itself replicated and mongos routes operations, adding cross-shard coordination where an operation spans shards.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

CAP: what happens during a partition

CAP names three properties: consistency (operations behave according to a single-system consistency model), availability (every request to a non-failing node receives a non-error response), and partition tolerance (the system continues to operate despite dropped or delayed communication between nodes). In a distributed deployment, partitions are a failure condition the system must handle; the practical question is whether, during one, an operation is delayed or rejected to preserve a consistent authority, or served with weaker guarantees to remain available.

The familiar “choose two of three” slogan obscures that conditional trade-off. MongoDB’s replica-set majority-write path favors consistency and split-brain avoidance over write availability when a majority is unreachable. But applications can permit stale reads from secondaries or use weaker write concerns, so a one-word CAP classification of the whole product is misleading. The formal CAP result is described by Gilbert and Lynch’s overview and their formal proof.

PACELC: the healthy-cluster trade-off

PACELC extends the CAP framing: if there is a Partition (P), choose between Availability (A) and Consistency (C); Else (E), choose between Latency (L) and Consistency (C). It is useful for MongoDB because choices matter even without a failure. A nearby secondary can lower read latency but return lagged data; a majority write that involves remote members can take longer; and a linearizable read can require coordination. PACELC is an analytical framework, not a MongoDB setting or a promise of specific performance. See Daniel Abadi’s PACELC paper.

Read concern: what data may a read observe?

Read concern defines the consistency and isolation level a read requires. It does not select the member that handles the read.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Level What it permits or guarantees Typical fit and limitation
local Returns data from the member serving the read; data need not be majority committed and can be rolled back after failover. It is the ordinary default absent another configured concern. Low-latency feeds, dashboards, caches, or telemetry that tolerate staleness or rollback exposure. A secondary may also lag.
available Returns locally available data without requiring majority commitment. In sharded deployments, certain metadata transitions can expose orphaned documents. It cannot be used with causally consistent sessions or transactions. Specialized availability-first reads where temporary staleness and transitional results are acceptable; unsuitable for authoritative balances, inventory, or authorization decisions.
majority Returns data acknowledged by a majority. It is not necessarily the newest applied state everywhere: a secondary can be behind the primary. In transactions, the transaction’s commit write concern also matters. Durable business reads and causal sessions when linearizability is unnecessary. It is stronger than local but does not mean “latest on every node.”
linearizable For primary reads whose query uniquely identifies a single document, reflects successful majority-acknowledged writes completed before the read began. It may wait for majority confirmation. One authoritative value such as a lease or account-status flag. More costly, not for broad queries or multi-document isolation; bound waiting with maxTimeMS.
snapshot Provides a consistent snapshot view, notably for reads in multi-document transactions and selected operations outside transactions. Snapshot alone does not establish majority durability. Transactions or workflows requiring a coherent multi-document view; configure commit durability separately.

For example, a bounded linearizable read of one lock document can be written as:

db.locks
  .find({ _id: lockId })
  .readConcern("linearizable")
  .maxTimeMS(5000)

Write concern: when does MongoDB acknowledge a write?

Write concern specifies the acknowledgment condition. The trade-off is between waiting for replication or journaling and returning sooner with more exposure to rollback or loss.

  • { w: 0 } requests no acknowledgment. The application cannot reliably tell whether the write succeeded; network or socket errors may still surface. Avoid for important business writes.
  • { w: 1 } acknowledges at the primary. It is faster in some conditions, but a recently acknowledged write can roll back if the primary fails before replication. It can suit reconstructible metrics or best-effort events.
  • { w: 2 } asks for acknowledgment from two data-bearing members. Numeric write concerns depend on membership and should be selected with the actual replica-set configuration in mind.
  • { w: "majority" } waits for the calculated majority of data-bearing voting members. In a three-voter set, that is normally the primary plus one secondary. It reduces rollback exposure but can wait or return a write-concern error when a majority is unavailable.

In MongoDB 8.0, majority acknowledgment is returned after a majority of data-bearing members durably write the oplog entry; secondaries may apply the operation to their collections asynchronously. Thus an immediate read from a secondary can still miss a majority-acknowledged write.

j: true requests acknowledgment after the relevant member or members write to the on-disk journal. Journaling alone does not prevent replica-set rollback; pair it with a replication acknowledgment appropriate to the failure you need to withstand. wtimeout bounds the wait for the requested concern. A timeout is a write-concern error, not proof that the operation was undone: the primary may already have applied it, and it may later replicate. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
db.orders.insertOne(
  { _id: orderId, customerId, total, status: "paid" },
  { writeConcern: { w: "majority", wtimeout: 5000 } }
)

On an ambiguous timeout, use an idempotency key or deterministic identifier, inspect or reconcile the outcome, and handle a duplicate-key error if a retry encounters a write that already succeeded.

Read preference is different from read concern

Read preference chooses which replica-set member receives a read; read concern sets what state is acceptable at that member. The common modes are primary, primaryPreferred, secondary, secondaryPreferred, and nearest. The default client-level preference is primary.

Consider a user who submits a change. The primary acknowledges it, but the next page request is routed to a secondary that has not yet applied the operation. The user sees the older value. Choosing readConcern: "majority" does not make that secondary current; it constrains the data it returns to majority-committed data available there. For immediate read-after-write behavior, read from the primary or use a causally consistent session with appropriate majority read and write concerns.

const client = new MongoClient(uri, {
  readPreference: "primary",
  readConcern: { level: "majority" },
  writeConcern: { w: "majority" }
});

MongoDB 8.0’s separation of durable oplog propagation from secondary collection application makes this routing distinction especially important.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Causal consistency for related operations

A causally consistent session preserves four relationships across operations issued through that session: read-your-writes, monotonic reads, monotonic writes, and writes following reads. MongoDB documents all four guarantees when the session uses "majority" read and write concerns. Causal metadata can make a later read wait until the chosen member has reached a suitable cluster time; it is not globally synchronous replication.

const session = client.startSession({ causalConsistency: true });

try {
  const orders = client.db("shop").collection("orders");

  await orders.insertOne(
    { _id: orderId, customerId, status: "created" },
    { session, writeConcern: { w: "majority" } }
  );

  const order = await orders.findOne(
    { _id: orderId },
    { session, readConcern: { level: "majority" } }
  );

  console.log(order);
} finally {
  await session.endSession();
}

See MongoDB’s documentation on causal consistency and read/write concerns.

Transactions: atomicity and a coherent view

MongoDB provides atomic single-document writes and multi-document transactions on replica sets, including distributed transactions on sharded clusters. Use a transaction when related changes across documents must commit or abort together; do not treat transactions as a substitute for good document modeling, since transaction overhead can be materially higher than a single-document operation.

Set transaction read concern, write concern, and read preference at transaction start. Reads in transactions use primary read preference, and operations in a transaction must route to the same member. Transaction concerns do not make later secondary reads instantly current.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const session = client.startSession();

try {
  await session.withTransaction(
    async () => {
      const accounts = client.db("bank").collection("accounts");

      await accounts.updateOne(
        { _id: fromAccount },
        { $inc: { balance: -amount } },
        { session }
      );

      await accounts.updateOne(
        { _id: toAccount },
        { $inc: { balance: amount } },
        { session }
      );
    },
    {
      readConcern: { level: "snapshot" },
      writeConcern: { w: "majority" },
      readPreference: "primary"
    }
  );
} finally {
  await session.endSession();
}

Transaction read concern is set when the transaction starts; do not override it with operation-level concerns after beginning. Elections and transient failures can still abort transactions and require application-level retry handling. See the MongoDB transaction documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What changes during common failures?

Healthy three-member replica set

The primary accepts writes. A majority write normally waits for the primary and one other voting, data-bearing member to durably write the oplog entry. Primary reads avoid ordinary secondary lag; secondary reads can distribute load or reduce geographic distance but may be stale.

Primary isolated from the majority

The majority side can elect or retain a primary and continue majority-acknowledged writes. The minority side must not remain an authoritative write leader. A former primary may transiently believe it is primary under some partitions, but at most one node can complete majority writes. Majority acknowledgment is therefore the safer authority boundary, not a guarantee that every node is current.

No majority reachable

Majority writes cannot be acknowledged. Clients may see a timeout or write-concern error. Applications can fail closed, queue work for later, retry with bounded backoff, or use a weaker concern only for data whose loss or ambiguity is acceptable. Explicitly permitted secondary reads may remain possible, but are not authoritative current state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Election in progress

Writes can fail temporarily while a new primary is selected. Drivers’ server discovery and retryable writes can reduce disruption, but do not eliminate every transient error. Use idempotent operations and bounded retries; do not assume a read from a former primary is authoritative.

Secondary lag or a regional partition

A delayed or geographically distant member may be behind even when the majority is healthy. A majority write does not wait for every replica-set member, and a remote majority can add WAN round trips. Multi-region durability therefore has a cost in latency and operational complexity; topology and concern settings determine the actual behavior.

Choose settings by the cost of being wrong

Requirement Starting approach Main trade-off
Payments and balances Primary writes with w: "majority"; primary or causal reads; use a transaction for coupled multi-document changes. More waiting and reduced write availability when a majority is lost, in exchange for less rollback exposure and clearer read-after-write behavior.
Inventory and authorization Authoritative primary access with majority acknowledgment; consider linearizable reads for a uniquely identified single-document decision that truly requires real-time ordering. Stronger coordination costs latency and may fail when majority confirmation is unavailable.
User profiles and settings Majority writes; primary reads for immediate post-update screens, or causal sessions across related requests. Secondary locality is possible only if the interface tolerates staleness or has a freshness mechanism.
Social feeds and approximate analytics Secondary-oriented reads with local or, where appropriate, available concern. Lower latency or read distribution, but versions can vary by member and may lag.
Telemetry, caches, rebuildable indexes Consider w: 1 or weaker settings when loss, rollback, or regeneration is acceptable. Lower coordination burden in exchange for weaker durability or freshness.
Distributed locks or leases Primary read of a uniquely identified document with linearizable concern and bounded maxTimeMS. Limited applicability and increased wait; it is not a general query or transaction-isolation setting.

These are starting patterns, not universal prescriptions. MongoDB’s read isolation, consistency, and recency guidance can help map a specific endpoint’s freshness requirement to a concern.

A practical production baseline and verification

For critical business data, a reasonable starting point is majority writes and primary reads, with bounded write waiting. It reduces rollback exposure and supports authoritative follow-up reads, but does not guarantee zero downtime, linearizable semantics for every query, or immediate application on secondaries.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const client = new MongoClient(uri, {
  readPreference: "primary",
  readConcern: { level: "majority" },
  writeConcern: {
    w: "majority",
    wtimeout: 5000
  }
});

For a stale-tolerant workload that values read locality, a weaker alternative is:

const client = new MongoClient(uri, {
  readPreference: "secondaryPreferred",
  readConcern: { level: "local" },
  writeConcern: { w: 1 }
});

Use that only when stale reads, differences between members, and rollback of recently acknowledged writes are acceptable. To inspect configured global defaults, run:

db.adminCommand({ getDefaultRWConcern: 1 });

Effective behavior also depends on server version, deployment type, global defaults, client and session options, transaction options, replica-set membership, and driver behavior. Make critical-operation concerns explicit rather than assuming a generic default.

Operational checklist

  • Write down whether each endpoint can tolerate stale, missing, duplicate, or rolled-back data.
  • Use primary reads or causal sessions where users expect read-your-writes; do not direct authoritative decisions to secondaries without a freshness design.
  • Bound waits with wtimeout for writes and maxTimeMS for reads that can wait for stronger guarantees.
  • Make retries idempotent, and treat write-concern timeouts as ambiguous outcomes that may require reconciliation.
  • Monitor replication lag and test elections and network partitions under the deployment’s actual topology.
  • Use transactions only where multi-document atomicity or a coherent transaction view is required; preserve schema designs that can safely use single-document atomicity.
  • Document which service endpoints may return stale data and how clients recover after failover.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.