Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

How would you implement optimistic locking for concurrent edits of a document in Spring Data MongoDB, and what happens on conflict?

We add a @Version Long version field to the document class. Spring Data then saves with a filter on the expected version and increments it, so if another writer changed the document first, no document matches and Spring throws OptimisticLockingFailureException. We handle that by reloading and retrying when the change can be reapplied, or by returning 409 Conflict with the current state, and for simple counters we use atomic update operators instead.

Why this question is asked

Two support agents open the same customer record, both edit it, and both press save. Without protection, the second save silently erases the first agent's work. Optimistic locking is the standard way to detect this, and interviewers ask about it to see whether we understand what Spring actually sends to MongoDB, what the failure looks like, and how we turn that failure into good behaviour for the user. In this answer, we will recap what optimistic locking means, add it to a document, follow the update that Spring sends, reproduce a conflict, and then look at how to handle it and when to avoid it.

1A Quick Recap of Optimistic Locking

There are two broad ways to protect concurrent edits. Pessimistic locking takes a lock before reading, so others must wait. Optimistic locking takes no lock at all: it assumes conflicts are rare, lets everyone read freely, and checks at write time whether the data changed since it was read. If it did, the write is refused.

The check needs something that changes on every write. That is the version field: a number stored in the document and increased by one each time it is saved. A writer remembers the version it read, and its update only succeeds if the document still has that version.

2Adding @Version to the Document

In Spring Data MongoDB, optimistic locking is switched on simply by adding a field annotated with @Version from org.springframework.data.annotation.

Java
@Document("customers")
public class Customer {
@Id private String id;
private String name;
private String phone;
@Version private Long version; // null for a new document, 0 after the first insert
// getters and setters
}
Customer c = repository.save(new Customer("Ana Lima", "555-0100"));
// c.getVersion() -> 0
c.setPhone("555-0199");
c = repository.save(c);
// c.getVersion() -> 1

Notice that we use the wrapper type Long. A null version tells Spring the entity is new and must be inserted; a value tells it to update. With a primitive long the starting value is 0, so check your version's rules for primitives, but the wrapper type keeps the intent obvious.

3What save() Sends to MongoDB

When we save a document that has a version, Spring does not just replace it by id. It replaces it by id and expected version, and writes the new version at the same time. In shell terms, it is close to this:

Java
// Saving the customer we loaded with version 1
db.customers.replaceOne(
{ _id: ObjectId("6730..."), version: 1 }, // filter: id AND the version we read
{ _id: ObjectId("6730..."), name: "Ana Lima", phone: "555-0123", version: 2 }
)
// { matchedCount: 1, modifiedCount: 1 } nobody else wrote, so it succeeds
// The same replace when someone already moved the version to 2
// { matchedCount: 0, modifiedCount: 0 } no document matches the filter

The check and the write happen in one atomic single-document operation, so there is no gap between them. When the match count is 0, Spring knows the document changed, or was deleted, since we read it, and throws OptimisticLockingFailureException instead of quietly doing nothing.

4Reproducing a Conflict

Here are the two agents from the introduction, written as code.

Java
Customer forAna = repository.findById(id).orElseThrow(); // version 1
Customer forBen = repository.findById(id).orElseThrow(); // version 1
forAna.setPhone("555-0123");
repository.save(forAna); // ok, version now 2
forBen.setName("Ana Lima-Souza");
repository.save(forBen);
// throws OptimisticLockingFailureException:
// filter { _id: ..., version: 1 } matched nothing
Step throughTwo edits of the same customer
Agent AnaMongoDBAgent Ben
read customer
version 1
read customer
version 1
replace where version = 1, set version 2
matched 1
replace where version = 1, set version 2
matched 0 -> OptimisticLockingFailureException

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

The second writer is refused because the version it read is gone.

Without the version field, Ben's save would replace the whole document with his copy, which still holds the old phone number, and Ana's change would be lost without a trace. With it, Ben's save fails loudly, which is what we want: a conflict we can see and handle.

5Handling the Conflict

What we do next depends on who made the change. If the change is something the system can safely reapply, such as a background job setting a status, we reload the document, apply the change again on the fresh copy and retry a few times. Spring Retry's @Retryable or a simple loop works well for this.

Java
@Retryable(retryFor = OptimisticLockingFailureException.class, maxAttempts = 3)
public void markVerified(String id) {
Customer c = repository.findById(id).orElseThrow(); // fresh copy on every attempt
c.setVerified(true);
repository.save(c);
}

If the change came from a person editing a form, an automatic retry would simply overwrite the other person's work with a different timing. Here we return 409 Conflict with the current state of the document, so the client can show what changed and let the user decide. A common REST pattern is to send the version to the client as an ETag, receive it back in an If-Match header, and return 409 or 412 when it no longer matches.

But there is a catch for counters and similar fields. If many requests increment a likes count, optimistic locking makes most of them conflict and retry under load. An atomic update such as new Update().inc("likes", 1) with updateFirst() needs no version check at all, because the server computes the new value itself. Optimistic locking is for edits that replace a document based on what the writer saw; atomic operators are for changes that do not depend on it.

6Follow-up questions

Does @Version work with MongoTemplate updates?

Only for the methods that save whole entities, such as save() on the template or the repository. A hand-written updateFirst() with an Update does not check or increment the version unless we add the version to the query and an inc("version", 1) to the update ourselves, which is a valid way to get the same protection on a partial update.

Why not use a multi-document transaction instead?

A transaction makes several writes atomic, but it does not stop two users from reading the same state and later overwriting each other in separate requests. Edits that span a user's think time cannot hold a transaction open. The version check is what detects that the data changed between the read in one request and the write in another.

What happens if the document was deleted?

The filter on id and version matches nothing, so Spring throws the same OptimisticLockingFailureException. If the difference matters to the user, we can reload by id after the failure: an empty result means it was deleted, and a newer version means it was edited.

7Conclusion

In this answer, we saw that optimistic locking takes no locks and detects conflicts at write time. Adding a @Version Long field makes Spring Data MongoDB save with a filter on the id and the expected version and increment the version in the same atomic operation. When another writer got there first, nothing matches and Spring throws OptimisticLockingFailureException. We retry by reloading when the change can be reapplied, return 409 Conflict with the current state when a person made the edit, and use atomic operators such as $inc for counters.

What to say in the interviewAbout 80 seconds aloud

Open with

I would add a @Version Long version field to the document class. With that, Spring Data MongoDB inserts new documents with version 0, and every save becomes a replace filtered on the id and the version I originally read, with the version incremented in the same operation.

Then, if they want more

Because that is one atomic single-document write, there is no race between the check and the update. If someone else saved in between, the version in the database has moved on, the filter matches nothing, and Spring throws OptimisticLockingFailureException instead of silently overwriting their change. How I handle it depends on the change.

For system changes that can be reapplied, like setting a status, I reload the document and retry a few times, for example with @Retryable. For user edits, I return 409 Conflict with the current state, often using the version as an ETag with If-Match, so the user can review and resubmit rather than overwrite.

And for simple counters I would not use versioning at all: an atomic update with $inc through updateFirst needs no version check and never conflicts, while optimistic locking would cause many retries under load.

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 "How would you implement optimistic locking for concurrent edits of a document in Spring...": https://scrivio-interview-library.netlify.app/databases/mongodb/8e8be09f89/