MongoDB Transactions Explained
On this page
When you need a MongoDB transaction
Updating an order and its embedded lines is atomic without any transaction, because it's one document (Day 1). Moving credit from account A to account B touches two documents. If the process crashes between the debit and the credit, money disappears. That needs a multi-document transaction: all changes commit together, or none do.
MongoDB has supported multi-document ACID transactions on replica sets since 4.0 and on sharded clusters since 4.2. A standalone mongod doesn't support them; run at least a single-node replica set, even in development.
The transaction callback API with retries
Drivers provide a with_transaction (or withTransaction) helper that starts the transaction, runs your function, commits, and retries automatically on transient errors such as a write conflict or a primary failover:
# transfer.py: move credit between two accounts atomically
from pymongo import MongoClient, ReturnDocument
from pymongo.read_concern import ReadConcern
from pymongo.write_concern import WriteConcern
client = MongoClient("mongodb://localhost:27017/?replicaSet=rs0")
accounts = client.bank.accounts
def transfer(session, src: str, dst: str, amount: int) -> None:
debited = accounts.find_one_and_update(
{"_id": src, "balance": {"$gte": amount}}, # only if there's enough
{"$inc": {"balance": -amount}},
session=session, return_document=ReturnDocument.AFTER)
if debited is None:
raise ValueError("insufficient funds") # aborts the transaction
accounts.update_one({"_id": dst}, {"$inc": {"balance": amount}}, session=session)
with client.start_session() as session:
session.with_transaction(lambda s: transfer(s, "A", "B", 30),
read_concern=ReadConcern("snapshot"),
write_concern=WriteConcern("majority"))Run against MongoDB 9 with A at 100 and B at 0, a transfer of 30 left A at 70 and B at 30. A second transfer of 500 raised "insufficient funds", the transaction aborted, and both balances stayed exactly as they were.
The same transfer with the C# driver uses WithTransactionAsync, which retries the same way:
// accounts is an IMongoCollection<Account>, where Account has a string Id and an int Balance
using var session = await client.StartSessionAsync();
await session.WithTransactionAsync(async (s, ct) =>
{
var debit = await accounts.UpdateOneAsync(s,
a => a.Id == "A" && a.Balance >= 30, // only if there's enough
Builders<Account>.Update.Inc(a => a.Balance, -30), cancellationToken: ct);
if (debit.ModifiedCount == 0)
throw new InvalidOperationException("insufficient funds"); // aborts the transaction
await accounts.UpdateOneAsync(s, a => a.Id == "B",
Builders<Account>.Update.Inc(a => a.Balance, 30), cancellationToken: ct);
return true;
});Every operation must pass the session. An operation without it runs outside the transaction, a common bug that silently breaks atomicity.
Snapshot isolation and write conflicts
A transaction reads a consistent snapshot of the data as of its start (with readConcern: "snapshot"). If two transactions modify the same document, one gets a write conflict and is retried by the callback API. Hot documents updated by many concurrent transactions cause repeated retries; design to spread writes.
Costs and limits of MongoDB transactions
- Transactions hold resources and add coordination; they're slower than single-document writes, especially across shards.
- They should be short. By default a transaction is aborted after 60 seconds (
transactionLifetimeLimitSeconds). - Keep them small: very large transactions put pressure on the cache and the oplog.
- Avoid user interaction or slow external calls inside a transaction.
Prefer designs that don't need them
Before reaching for a transaction, ask if the data that changes together should live in one document. Order and lines: embed. Inventory reservation with an order: maybe a single conditional update ($inc with a $gte check) suffices. Transactions are for real cross-document cases, like transfers between accounts, which is why MongoDB's guidance is that most applications need them occasionally, not everywhere.
Check yourself
No. Writes to a single document are atomic on their own, including updates to several fields, nested objects and array elements in one operation. Transactions are only needed when a change must span several documents atomically.
The operation wasn't given the session, so it ran outside the transaction and committed immediately. Every read and write that should be part of the transaction must pass the same session object.
It retries the whole transaction on transient errors, such as write conflicts or a primary failover, and retries the commit when its outcome is unknown. Hand-written start and commit code usually misses some of these cases.
The second one hits a write conflict and aborts with a transient error. With the callback API it's retried automatically against the updated data.
By default they must finish within 60 seconds, they hold resources and cache while open, and very large transactions hurt performance. Keep them short and touch few documents.