Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring Data MongoDB transaction: keep every write in one client session

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A MongoDB transaction depends on a client session and an explicit transaction manager; an annotation alone is not enough.

Name the unit of work

A transfer changes two wallet documents and writes one transfer record. A single-document update is atomic, but these three writes need a multi-document transaction if the product promises all-or-nothing state. Register MongoTransactionManager for imperative operations, use the same MongoDatabaseFactory in the template, and enter through a Spring-managed service proxy. MongoDB transactions require a suitable replica set or sharded deployment; a standalone local server is not a valid proof.

Keep I/O inside the session

MongoTemplate participates in the bound session. A raw driver collection obtained separately may need the ClientSession passed explicitly; otherwise the write can escape the intended transaction. Do not send a broker message or remote HTTP call before commit and call that atomic. An outbox records a later delivery obligation in the transaction. Worker threads do not inherit the imperative session.

Test rollback on the real topology

Cause the third write to fail after the first two have executed. Assert neither wallet changed and no transfer record exists. Repeat with a direct-driver write to catch an accidental escape from the session. The code is the service boundary; repository methods and transaction manager wiring must be verified in an application integration test.

Implementation sketch

Java
@Transactional
public void transfer(TransferCommand command) {
    wallets.debit(command.sourceWallet(), command.units());
    wallets.credit(command.targetWallet(), command.units());
    transfers.insert(command.id(), command.units());
}

Cost and verification

A multi-document transaction holds session resources and can increase contention. Prefer an atomic single-document update when the business invariant fits one document.

Common Mistakes

  • Do not assume @Transactional activates MongoDB transactions without a Mongo transaction manager.
  • Do not mix a session-aware template with an unrelated raw driver write.
  • Do not hold the transaction open across a broker or HTTP call.

Read next

Spring Data MongoDB optimistic locking: save the version you read, Spring imperative transaction: a worker thread does not inherit it, Spring outbox transaction boundaries: where atomicity ends, Spring reactive transaction: subscription owns the context, not a thread.

spring
spring-boot
data-transactions
mongodb-transaction-session
Storage details