Lesson 6 of 9 · 28m
Transactions, Write Concerns, and Honest Consistency
Use multi-document transactions sparingly, understand write concern and read concern combinations, and design for retryable writes rather than perfect certainty.
MongoDB supports multi-document ACID transactions, and yes, they are real. They are also not the default answer to every consistency problem. The senior move is to model most invariants into single-document atomic operations, then use transactions where boundaries genuinely span documents. Transactions add coordination cost, increase contention, and make retry behavior impossible to ignore. Use them when they are necessary, not because they feel enterprise-grade.
Single-document atomicity first
Most order workflows can mutate one document atomically:
db.inventory.updateOne(
{ sku: "SKU-1042", available: { $gte: 2 } },
{ $inc: { available: -2, reserved: 2 } }
)If this returns modifiedCount: 0, the reservation did not happen. No transaction is required. The predicate and mutation are part of the same atomic operation. This is the primitive you should reach for before reaching for a session.
A transaction is a consistency boundary across documents
Some workflows really do span documents: debit one account, credit another, append a ledger entry, and record an audit event. A transaction makes the boundary explicit:
const session = client.startSession()
try {
await session.withTransaction(async () => {
await db.accounts.updateOne(
{ _id: from, balance: { $gte: amount } },
{ $inc: { balance: -amount } },
{ session }
)
await db.accounts.updateOne(
{ _id: to },
{ $inc: { balance: amount } },
{ session }
)
await db.ledger.insertOne(
{ from, to, amount, createdAt: new Date() },
{ session }
)
})
} finally {
await session.endSession()
}Notice what this does not solve: business validation if the first update modifies zero documents. Transactions do not replace checking write results. You still need application invariants.
Write concern is durability policy, not ceremony
writeConcern controls how many members must acknowledge a write:
db.orders.insertOne(
{ customerId: c, status: "paid", createdAt: new Date() },
{ writeConcern: { w: "majority", wtimeout: 2500 } }
)w: 1 is fast but can acknowledge before replication. w: "majority" greatly reduces the chance of losing acknowledged writes during failover. There is no free durability. If an operation matters financially, do not accept default settings blindly.
Read concern and read preference shape stale truth
readConcern: "majority" avoids reading data that may later roll back in supported configurations. readPreference controls where reads go. Reading from secondaries can reduce primary load, but replication lag means a user may write on the primary and not immediately see their own write on a secondary. If your product requires read-your-write behavior, pin critical reads to the primary or design explicit synchronization points.
Retries are part of the protocol
Retryable writes are enabled by default in modern drivers for many operations. That does not make every operation idempotent. If a network error occurs after the server commits but before the client receives acknowledgement, retrying blindly can duplicate effects. Use idempotency keys or unique indexes:
db.payments.createIndex({ idempotencyKey: 1 }, { unique: true })Then design retries to treat duplicate-key errors as evidence that the original operation may already have succeeded.
Field notes
- Long transactions increase cache pressure and can hold resources; keep them short and deterministic.
- Do not start a transaction just to update several fields in one document.
majorityis not magic when the application ignores errors or retries incorrectly.- Test failover behavior explicitly. Consistency settings that look right in a quiet staging cluster may behave very differently during elections.
Was this lesson helpful?