Skip to content

MongoDB ACID transactions: read concern, write concern, and the cost

Run multi-document ACID transactions in MongoDB — when to use them, the read/write concern combination that gives you serializable behaviour, and the cost you accept versus single-document writes.

MongoDB has had multi-document ACID transactions since 4.0 on replica-sets and 4.2 on sharded clusters. They behave like transactions in PostgreSQL or SQL Server: a session opens, multiple operations execute, the session commits or aborts atomically. But MongoDB transactions are not free — they take locks, hold oplog space, and impose a window in which writes are not visible to other readers. This article covers when to reach for them, when to design around them, and the read/write concern combination that gives the semantics you actually want.

How to verify

Run a transaction from mongosh and look at the session metrics:

mongosh --host primary.example.internal:27017
use shop
const session = db.getMongo().startSession({ causalConsistency: true })
session.startTransaction({ readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } })
session.getDatabase("shop").orders.insertOne({ sku: "X-100", qty: 1 })
session.getDatabase("shop").inventory.updateOne({ sku: "X-100" }, { $inc: { qty: -1 } })
session.commitTransaction()
db.serverStatus().transactions

db.serverStatus().transactions exposes counters — totalStarted, totalCommitted, totalAborted, currentActive — that tell you whether transactions are succeeding at the expected rate.

What’s happening

A MongoDB transaction is a session-level construct. The driver issues startTransaction, all operations within that session are buffered server-side under a snapshot, and the session commits or aborts as a unit. Under the hood, MongoDB uses snapshot isolation: every read within the transaction sees the same point-in-time snapshot of the data, even if other writers commit changes in the meantime. Conflicts at commit time trigger a WriteConflict error and the application must retry.

The right semantics come from pairing read concern: snapshot with write concern: majority. Snapshot read concern gives you a consistent point-in-time view across the entire transaction. Majority write concern guarantees that the commit is replicated to a majority of voting members before acknowledged — without it, a primary failure can roll back the transaction’s writes even after the application thought they succeeded. Causal consistency on the session adds happens-before semantics across multiple operations within the same client.

Transactions have hard limits. By default a transaction must complete within 60 seconds (transactionLifetimeLimitSeconds); after that, the server aborts it. A transaction’s oplog entries cannot exceed 16 MiB total. Long-running or wide transactions starve readers on the affected documents and consume cache. The MongoDB transaction model is designed for short, focused operations spanning a few documents — not for analytical work or batch updates.

The procedure

  1. Decide whether you need a transaction at all. MongoDB’s document model is intentionally designed to colocate related data; if you can express the operation as a single-document update with subdocuments or arrays, the single-document operation is already atomic and orders of magnitude cheaper.

  2. Pick the read and write concern. For correctness-critical multi-document work:

    session.startTransaction({
      readConcern: { level: "snapshot" },
      writeConcern: { w: "majority", wtimeout: 5000 }
    })
  3. Wrap the transaction body in retry logic. Transient errors — WriteConflict, TransientTransactionError — should be retried; non-transient errors (constraint violations, schema errors) should propagate.

    function runTx(session, body) {
      while (true) {
        try {
          session.startTransaction({ readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } })
          body(session)
          session.commitTransaction()
          return
        } catch (e) {
          session.abortTransaction()
          if (e.hasErrorLabel("TransientTransactionError")) continue
          throw e
        }
      }
    }
  4. Bound the transaction’s scope tightly. Read what you need, write what you need, commit. Do not include external HTTP calls, file IO, or anything else that could exceed the lifetime limit.

  5. Set transactionLifetimeLimitSeconds if your workload genuinely needs it. The default is 60 seconds; raising it accepts longer write-blocking windows on the affected documents.

    db.adminCommand({ setParameter: 1, transactionLifetimeLimitSeconds: 120 })
  6. Monitor transaction metrics. currentActive should not spike — a spike indicates a backlog of stuck transactions, usually from application bugs.

    db.serverStatus().transactions
    db.currentOp({ "command.startTransaction": { $exists: true } })

Operational notes

  • Single-document operations are atomic without transactions. findOneAndUpdate, updateMany (per document), and array operators are atomic by default. Reach for transactions only when atomicity must span documents.
  • Read concern majority alone is not snapshot isolation. Two separate reads at majority can see different points in time. Use snapshot read concern inside transactions for cross-operation consistency.
  • Sharded transactions are slower. Cross-shard transactions involve a two-phase commit protocol and are an order of magnitude more expensive than single-shard transactions. Design schemas to keep transactional work on one shard when possible.
  • Long-running transactions stall the storage engine cache. WiredTiger’s snapshot retention keeps copies of changed data until all open snapshots release them; a single long transaction can balloon cache pressure across the cluster.
  • Retries amplify conflicting workloads. A hot document under contention will keep producing WriteConflict errors; rethink the schema (e.g., add a tenant-level shard key prefix) rather than retrying harder.

Stack Harbor coaches application teams on the trade-off between transactions and document modelling — often, what looks like a transaction requirement reduces to a schema change that makes the operation single-document. When transactions are genuinely required, we tune concerns, bound the scope, and instrument the metrics that catch retry storms. See /en/services/managed-operations/ for how this fits into the operating model.