Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

Your service uses MongoDB transactions with the Java driver and occasionally fails with a WriteConflict error labelled TransientTransactionError, and long transactions are aborted after about a minute. Explain both and how to handle them.

A WriteConflict happens when two transactions try to modify the same document: MongoDB aborts one of them and labels the error TransientTransactionError, which means the whole transaction can safely be retried from the start, and ClientSession.withTransaction does that automatically, also retrying commits that fail with UnknownTransactionCommitResult. Long transactions are aborted because transactionLifetimeLimitSeconds, 60 seconds by default, caps how long a transaction may stay open, since open transactions pin old data in the cache. The fix is to keep transactions short, with no remote calls inside and few documents touched, and to make the work idempotent so a retry after an unknown commit cannot apply its effects twice.

Why this question is asked

Transactions in MongoDB are reliable, but they behave differently from what developers expect from a relational database with locks. Instead of waiting for another transaction to finish, a conflicting MongoDB transaction fails fast and expects the client to retry. Code that does not retry, or retries the wrong thing, turns a normal event under concurrency into user-facing errors or duplicated effects. Interviewers ask about these two errors because they test whether we understand optimistic concurrency, the error labels, and the cost of open transactions. In this answer, we will recap how conflicts are detected, reproduce a WriteConflict, handle it with withTransaction, explain the 60-second limit and why it exists, and make retries safe with idempotency.

1A Quick Recap: How MongoDB Detects Conflicts

A MongoDB transaction reads from a snapshot, a consistent view of the data as of the moment it started, and buffers its writes until commit. WiredTiger, the storage engine, uses optimistic concurrency: it does not take long-held locks on documents when a transaction reads them. When a transaction tries to write a document that another transaction has already modified but not yet committed, or modified and committed after our snapshot, the write cannot proceed safely. MongoDB reports a WriteConflict and aborts our transaction.

Rather than waiting, MongoDB attaches an error label to the exception: TransientTransactionError. A label is a tag on the error that tells the client what kind of failure it is. This one means 'nothing was committed; running the entire transaction again may well succeed'.

2Reproducing a WriteConflict

Two requests reserve the last seat on a flight at the same time, each in its own transaction that updates the flight document and inserts a booking.

Java
// Transaction T1 // Transaction T2
session1.startTransaction(); session2.startTransaction();
flights.updateOne(session1, eq("_id", "LX318"), inc("seatsLeft", -1));
flights.updateOne(session2, eq("_id", "LX318"),
inc("seatsLeft", -1));
// MongoCommandException: WriteConflict
// hasErrorLabel("TransientTransactionError") -> true
bookings.insertOne(session1, booking1);
session1.commitTransaction(); // T1 commits
Step throughA conflict and the automatic retry
Service AService BMongoDB
T1: update flight LX318
T2: update flight LX318
WriteConflict, TransientTransactionError
T1: insert booking, commit
committed
retry T2 from the start
seatsLeft is 0: no seat, abort cleanly

7 messages in order. Play them, or step through them one at a time.

The retried transaction sees T1's committed result and makes a correct decision.

T2 tried to modify a document that T1 had modified inside an uncommitted transaction, so T2 is aborted at that write. Notice that nothing T2 did is visible anywhere; the transaction is simply gone. The right response is to run T2's whole block again from the beginning: read the flight, check seats, update, insert. Retrying only the failed statement would be wrong, because the transaction no longer exists.

3Handling It With withTransaction

The Java driver's ClientSession.withTransaction implements the retry rules for us. It runs our lambda inside a transaction, commits, and if the lambda or the commit throws an error labelled TransientTransactionError, it starts a new transaction and runs the lambda again. If the commit fails with the UnknownTransactionCommitResult label, meaning the driver cannot tell whether the commit happened, for example because the connection dropped, it retries the commit itself, which is safe because commit is idempotent on the server. It keeps retrying for up to 120 seconds overall.

Java
TransactionOptions opts = TransactionOptions.builder()
.readConcern(ReadConcern.SNAPSHOT)
.writeConcern(WriteConcern.MAJORITY)
.build();
try (ClientSession session = client.startSession()) {
boolean booked = session.withTransaction(() -> {
UpdateResult r = flights.updateOne(session,
and(eq("_id", "LX318"), gt("seatsLeft", 0)), inc("seatsLeft", -1));
if (r.getModifiedCount() == 0) return false; // full: commit nothing
bookings.insertOne(session, booking);
return true;
}, opts);
}

Notice what the lambda must not do: catch and swallow the MongoException, which would stop withTransaction from seeing the label, or perform side effects outside the database, because the lambda may run several times. If we use Spring's @Transactional with MongoTransactionManager instead, Spring does not retry on its own, so we add a retry around the transactional method for exceptions carrying the TransientTransactionError label, for example with Spring Retry.

4Why Long Transactions Are Aborted After About a Minute

The second error comes from a server parameter, transactionLifetimeLimitSeconds, which defaults to 60. A background task aborts any transaction that has been open longer than that. The reason is cache pressure. While a transaction is open, WiredTiger must keep every version of data that its snapshot might need, so the oldest open snapshot pins old versions in the cache. One transaction open for minutes during heavy writes forces the cache to retain more and more history, which slows down the whole server, not just that transaction.

So the 60-second limit is a protection, and raising it is rarely the answer. The question is why a transaction is open that long in the first place. The usual reasons are a call to another service in the middle of the transaction, waiting for user input, or processing thousands of documents in one transaction.

5Keeping Transactions Short

A good MongoDB transaction does all its slow work before it starts and touches few documents.

Java
// Bad: a remote call inside the transaction
session.withTransaction(() -> {
orders.insertOne(session, order);
PaymentResult p = paymentClient.charge(order); // 2 to 30 seconds, may hang
payments.insertOne(session, p.toDocument());
return null;
});
// Better: slow work first, then a short transaction
PaymentResult p = paymentClient.charge(order); // outside, with its own timeout
session.withTransaction(() -> {
orders.insertOne(session, order);
payments.insertOne(session, p.toDocument()); // milliseconds
return null;
});

In the bad version, a slow payment provider keeps the transaction open and makes it a candidate for the 60-second abort; worse, a retry after a WriteConflict would charge the card twice. In the better version the transaction only contains fast database writes. For batch jobs that change thousands of documents, we split the work into small transactions, perhaps a few hundred documents each, or redesign so that each unit of work is one document.

6Making Retries Safe With Idempotency

Retries are only safe if running the work twice has the same effect as running it once. Inside a single transaction that is automatic, because an aborted attempt leaves no trace. The danger is at the edges: a commit whose result is unknown, an application that retries the whole request after a timeout, or effects outside the database.

The standard technique is an idempotency key. The client sends a unique operation id with the request, and the transaction inserts a document with that id into a collection with a unique index. If the same operation runs again after it already committed, the insert fails with a duplicate key error, and we return the original result instead of applying the effects again. For the payment example, the payment provider's own idempotency key does the same job for the external charge.

7Follow-up questions

Should I increase transactionLifetimeLimitSeconds?

Only as a temporary measure while fixing the cause. A higher limit lets long transactions pin more cache and makes conflicts more likely. The better fix is to remove remote calls and large batches from the transaction.

Do retryable writes do the same thing as withTransaction?

Retryable writes, on by default in current drivers, retry a single write once after a network error or failover. They do not retry transactions as a whole; withTransaction handles that. Both rely on the server recognising a repeated operation so it is applied only once.

How can I reduce write conflicts in the first place?

Avoid having many transactions update the same hot document, such as a global counter. Spread the counter over several documents, use single-document atomic updates where the rule fits in one document, and keep transactions short so the window for conflict is small.

8Conclusion

In this answer, we saw that a WriteConflict means two transactions modified the same document and MongoDB aborted one, labelling it TransientTransactionError so the whole transaction can be retried, which withTransaction does automatically, together with commit retries for UnknownTransactionCommitResult. Long transactions are aborted by transactionLifetimeLimitSeconds, 60 seconds by default, because open snapshots pin old data in the cache. We fixed the code by keeping transactions short, with remote calls outside and few documents inside, and by making retried work idempotent with an operation id and a unique index.

What to say in the interviewAbout 80 seconds aloud

Open with

MongoDB transactions use optimistic concurrency. If two transactions try to modify the same document, the second one does not wait; it gets a WriteConflict and its transaction is aborted.

Then, if they want more

The error carries the TransientTransactionError label, which means nothing was committed and the whole transaction can be run again from the start, not just the failed statement.

ClientSession.withTransaction does that for me: it reruns the lambda on transient errors and, if the commit result is unknown, for example after a network drop, it retries the commit, which is safe, for up to two minutes. So I make sure the lambda passes the session to every operation and does not swallow exceptions.

With Spring's @Transactional I add my own retry, because Spring does not retry. The one-minute aborts come from transactionLifetimeLimitSeconds, sixty by default. Open transactions keep their snapshot alive, which pins old versions in the WiredTiger cache, so the server kills long ones.

Rather than raising the limit, I keep transactions short: remote calls like payments happen before the transaction, batches are split, and each transaction touches few documents. Finally, because work can be retried, I make it idempotent, with an operation id stored under a unique index, so a repeat after an unknown commit does not apply the effects twice.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your service uses MongoDB transactions with the Java driver and occasionally fails with...": https://scrivio-interview-library.netlify.app/databases/mongodb/4aecb06b38/