Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 70 ยท Transactions and consistency

Multi-Document Transactions

Learn how multi-document ACID transactions work in MongoDB: sessions, withTransaction, retrying TransientTransactionError, the cost and limits, and when to avoid them.

Sometimes a business rule really does touch several documents: moving money from one account to another, creating an order while reducing stock in another collection, or removing a user together with their data. A single-document write is atomic (Atomicity and Single-Document Writes), but two separate updateOne calls are not: if the second fails after the first succeeded, your data is inconsistent. A multi-document transaction groups the writes so that they all succeed or all disappear.

MongoDB supports ACID transactions across documents, collections and (on sharded clusters) shards. This lesson shows the real driver code, explains what the guarantees and the costs are, and walks through the retry rules. The code in js fences marked read-only is real MongoDB; the TryIts are JavaScript stand-ins that imitate commit, abort and retry on plain arrays (see The Practice Engine Used in This Tutorial).

ACID in one line each

Atomicity All writes apply, or none do.
Consistency Rules like validators still hold.
Isolation Other clients do not see half-done work.
Durability A committed result survives failures.
1 / 2

The real code

Transactions run inside a session. In the Node.js driver the recommended form is withTransaction, which starts the transaction, runs your function, commits, and retries when it is safe to do so:

JavaScript
const session = client.startSession();
try {
  await session.withTransaction(async () => {
    const accounts = client.db("bank").collection("accounts");
    const from = await accounts.findOne({ _id: "A" }, { session });
    if (from.balance < 100) throw new Error("insufficient funds");   // aborts the transaction

    await accounts.updateOne({ _id: "A" }, { $inc: { balance: -100 } }, { session });
    await accounts.updateOne({ _id: "B" }, { $inc: { balance: +100 } }, { session });
  }, {
    readConcern: { level: "snapshot" },
    writeConcern: { w: "majority" }
  });
} finally {
  await session.endSession();
}

Three rules matter here. First, every operation must be given the same session; an operation without it runs outside the transaction and is not rolled back. Second, throwing from the callback aborts the transaction. Third, the callback may run more than once, so it must not have side effects outside the database (sending an email, charging a card) that you cannot repeat safely.

mongosh offers the same idea with session.startTransaction(), session.commitTransaction() and session.abortTransaction(), which you will use when you need manual control.

What you get, and what it requires

Inside a transaction, you read from a snapshot: a consistent view taken when the transaction starts, so you do not see other clients' changes mid-flight, and other clients do not see yours until you commit. If two transactions try to change the same document, one of them fails with a write conflict and has to retry; MongoDB does not make it wait for the other for long.

Transactions need a replica set or a sharded cluster; a standalone mongod does not support them. Atlas clusters and Docker setups started as a one-node replica set work. See Replica Sets.

Cost and limits

Transactions are not free, and they are not the default tool:

  • Time. A transaction is meant to be short. The server aborts one that runs longer than a time limit (60 seconds by default, controlled by transactionLifetimeLimitSeconds).
  • Size. Large transactions create large oplog entries and hold resources; keep the number of documents small, and split big batch jobs into several transactions.
  • Contention. Long transactions that touch popular documents cause write conflicts and retries.
  • Latency. Commit waits on the write concern (often majority), so each transaction costs more than a single write.
  • Careful with DDL. Creating collections and indexes inside transactions has restrictions that depend on the server version; check the documentation for yours.

A good rule: if you can model the data so the writes hit one document, do that. Use transactions for the cases where you genuinely cannot.

Commit and abort in a stand-in

The stand-in below keeps accounts in an array. startTransaction takes a snapshot copy of the data; commit keeps the changes and abort restores the copy. It is a simplification (the real server uses MVCC and per-document conflict detection, and does not copy anything), but it shows what the application sees.

JS Commit and abort

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

No output.

In the second transfer the debit on A had already been applied when the check failed. Without a transaction, A would be left with a negative balance; with one, the abort puts everything back.

Retrying: TransientTransactionError

Some failures are temporary and the right response is to run the whole transaction again: a write conflict with another transaction, a primary election in progress, a brief network problem. The server marks such errors with the label TransientTransactionError. There is a second label, UnknownTransactionCommitResult, which means "the commit was sent but you did not hear whether it worked"; in that case you retry only the commit, not the work.

withTransaction implements both loops for you (with a time limit on the retrying). If you use the manual API you must write them yourself:

JavaScript
async function runWithRetry(session, txnFn) {
  while (true) {
    try {
      session.startTransaction();
      await txnFn(session);
      while (true) {
        try { await session.commitTransaction(); return; }
        catch (e) {
          if (e.hasErrorLabel("UnknownTransactionCommitResult")) continue;  // retry commit only
          throw e;
        }
      }
    } catch (e) {
      await session.abortTransaction();
      if (e.hasErrorLabel("TransientTransactionError")) continue;           // retry whole transaction
      throw e;
    }
  }
}

Errors without those labels (validation failures, duplicate keys, your own "insufficient funds") are not retried: running again would fail the same way. The stand-in below simulates a write conflict on the first attempt to show the retry flow.

JS Retry on TransientTransactionError

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

No output.

The conflict on attempt 1 is retried and succeeds, and the stock is only decremented once. The business-rule failure is not retried, and its partial change is rolled back.

The life of a transaction: states

Database theory describes every transaction as moving through a small set of states, and MongoDB's behavior follows the same shape. Knowing the states helps you read driver errors and decide what to do after a failure.

State What it means in MongoDB
Active startTransaction has run; your reads and writes execute against a snapshot and nothing is visible to others yet.
Partially committed Your last operation is done and you called commitTransaction; the server is making the changes durable according to the write concern.
Committed The commit was acknowledged. All changes become visible at once and cannot be undone.
Failed An operation raised an error (a write conflict, a duplicate key, a timeout) or the application hit a business-rule failure. The transaction cannot continue.
Aborted (terminated) The server discarded every change; the database is back to how it was before the transaction began. The application may retry or give up.

Committed and aborted are the two terminal states: a transaction never leaves them. A failed transaction always ends up aborted. The stand-in below enforces the legal moves, so an illegal call (committing after an abort, or writing after a commit) is rejected the way a driver would reject it.

JS Transaction states

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

No output.

Advantages and disadvantages

Advantages. Transactions give you all-or-nothing updates across several documents, collections or even shards, a consistent snapshot to read from, and the same ACID guarantees relational developers already rely on. That makes ports from SQL systems and multi-step business flows (transfers, order placement, inventory moves) much easier to get right.

Disadvantages. They are slower than single-document writes, hold resources while open, can fail with write conflicts that your code must retry, need a replica set or cluster, and add code complexity: you manage a session, pass it to every operation, and handle TransientTransactionError and UnknownTransactionCommitResult. A model that keeps related data in one document avoids most of this.

When not to use transactions

  • When one document is enough. Embed, and use atomic operators and conditional updates.
  • For long-running work. Break batch jobs into short transactions, or make them idempotent and resumable.
  • For hot documents. A counter touched by every transaction becomes a bottleneck; shard the counter or use an atomic $inc outside a transaction.
  • When approximate or eventual consistency is fine. A like count that is off by one for a second does not need ACID.
  • For side effects outside the database. Use the outbox pattern: write the intent to a collection inside the transaction, and let a separate worker send the email.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A transaction callback runs updateOne without passing the session option. What happens to that write?

    Only operations given the session take part in the transaction. Forgetting it is a common bug that leaves partial changes behind.
  2. 2. Which error label tells you to retry the entire transaction?

    TransientTransactionError marks temporary failures such as write conflicts or elections. UnknownTransactionCommitResult means retry only the commit.
  3. 3. Why should the withTransaction callback avoid sending emails or charging cards?

    Retries rerun the callback from the start. Do external side effects after the commit or through an outbox written inside the transaction.
  4. 4. Where do multi-document transactions work?

    Transactions need a replica set or sharded cluster. A standalone server cannot run them, although a one-node replica set can.
  5. 5. What is the best first choice when two writes must be consistent?

    A single-document write is already atomic and cheaper, so use transactions when you cannot remodel.

Summary

  • A multi-document transaction makes writes to several documents or collections all-or-nothing, with snapshot reads inside it.
  • Use a session, pass it to every operation, and prefer withTransaction, which commits and retries for you.
  • Throwing from the callback aborts; the callback may run more than once, so keep it free of external side effects.
  • Retry the whole transaction on TransientTransactionError, retry only the commit on UnknownTransactionCommitResult, and never retry ordinary errors.
  • Keep transactions short and small; they need a replica set or sharded cluster and cost more than single writes.
  • Prefer remodeling into one document, atomic operators or an outbox when they fit.
  • The TryIts are JavaScript stand-ins for the behaviour; the driver code is real MongoDB.

Next, see how acknowledgement and visibility are tuned in Read and Write Concerns.