How does MongoDB handle transactions?

Instruction: Discuss MongoDB's support for transactions, how it works, and when it should be used.

Context: This question is designed to evaluate the candidate's knowledge of transactions in MongoDB, particularly in the context of its traditional NoSQL characteristics. Discussing the concept of multi-document transactions, the candidate should explain how MongoDB has extended its capabilities to support ACID transactions within a single replica set (and across multiple shards since version 4.2), and under what circumstances transactions might be necessary despite the potential performance trade-offs.

Updated

Official answer

MongoDB updates to a single document are atomic. When an invariant spans documents, a supported replica-set or sharded deployment can use a multi-document transaction. Standalone deployments do not support these transactions. Prefer a suitable document model when it can enforce the invariant with less coordination.

Use a driver session, start a transaction or its supported callback helper, pass that session to every participating operation, then commit or abort. Set transaction-level read/write concerns according to the required guarantees. Distributed commit coordination is relevant to transactions spanning shards; it is incorrect to describe every transaction as a distributed two-phase commit.

For an inventory-and-order workflow, validate inputs, conditionally reserve available stock and create the corresponding order inside the transaction. Check the conditional update result before creating an order. Abort when the invariant cannot be satisfied.

Use the driver's documented retry handling. A transient transaction error may require replaying the transaction; an unknown commit result requires handling the commit uncertainty, not blindly repeating all business effects. A transaction callback can run more than once. Do not send a payment or email directly from a retryable callback; record durable intent and use an idempotent, reconciled delivery mechanism.

Keep transactions short and test conflicts, insufficient stock, exceptions, retry exhaustion and lost commit acknowledgment. Transactions do not remove schema, authorization or recovery requirements.

MongoDB transactions, driver transaction APIs, callback retry specification

Related Questions