Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A Spring Boot service with @Indexed(unique = true) on an email field allows duplicate emails in production but not in a developer's local setup. Why?

Since Spring Data MongoDB 3.0, the mapping annotations such as @Indexed no longer create indexes automatically; that happens only when auto-index-creation is switched on. The developer most likely enabled spring.data.mongodb.auto-index-creation=true locally or created the index by hand, while production never got a unique index, so MongoDB had nothing to enforce. The fix is to create the index explicitly in production, after cleaning existing duplicates, through a migration or a controlled startup step.

Why this question is asked

This bug is unsettling because the code says unique, the tests pass, and still production holds duplicate users. It shows a gap between what an annotation describes and what the database actually enforces. Interviewers ask it to check whether we know that MongoDB only enforces what exists as an index on the server, and whether we know how Spring Data's defaults changed. In this answer, we will recap how unique indexes work, see why the annotation does nothing by default, find out why the developer's machine behaves differently, and then fix production safely.

1A Quick Recap of Unique Indexes

MongoDB itself has no idea what our Java class looks like. Uniqueness is enforced only by a unique index on the collection: when an insert or update would create a second document with the same indexed value, the server refuses it with a duplicate key error, code 11000. Without that index, two documents with the same email are perfectly valid as far as MongoDB is concerned.

@Indexed(unique = true) is a Spring Data mapping annotation. It is metadata in our Java code that describes an index we would like. Something has to turn that description into a createIndexes command on the server, and the question is what does that, and when.

Java
// What the database actually has in production
db.users.getIndexes()
// [ { v: 2, key: { _id: 1 }, name: "_id_" } ] only the default _id index
// And what that allows
db.users.countDocuments({ email: "ana@example.com" }) // 2

2Why the Annotation Does Nothing by Default

In Spring Data MongoDB 2.x, the mapping context created indexes for annotated entities automatically when it first saw them. Version 3.0 turned this off by default. The reason was that creating indexes from application startup is risky: building an index on a large collection takes time and resources, a unique index fails if duplicates already exist, and every instance of a service racing to create indexes on deploy is a poor way to manage a production schema.

So in Spring Boot 3 and 4, the annotation is read but no index is created unless we opt in. The property for that is spring.data.mongodb.auto-index-creation=true, or overriding autoIndexCreation() in a custom MongoDB configuration class (check your version for the exact property name, as Boot has been reorganising its MongoDB properties).

Java
@Document("users")
public class User {
@Id String id;
@Indexed(unique = true) // describes an index; does not create it by default
String email;
}
// application.yml on the developer's machine
spring:
data:
mongodb:
auto-index-creation: true // only here does Spring create the index at startup

Notice that nothing fails when the index is missing. Spring does not warn us at startup that an annotated index is absent, so the gap stays invisible until duplicate data appears.

3Why the Developer's Machine Is Different

There are two common reasons the local setup refuses duplicates. The developer may have set auto-index-creation=true in a local profile, perhaps copied from an old tutorial, so Spring created the index when the app first started against an empty database. Or the developer once created the index by hand in the local database, or a test container init script does it. Either way, the local database holds a unique index that production never received.

We can confirm this in a minute by running getIndexes() on both databases and comparing, and by checking which profile properties each environment loads. The difference in behaviour comes from the database state, not from the code.

Same code, different databases
Developer machineProduction
@Indexed(unique = true) on emailpresentpresent
auto-index-creationtrue in local profiledefault false
Index on email in the databaseunique index existsmissing
Second insert with the same emailE11000 duplicate key erroraccepted
MongoDB enforces only the indexes that exist on the server.

4Fixing Production Safely

We cannot simply create the unique index in production, because the duplicates already exist and the build would fail with a duplicate key error. So the first step is to find them and decide, with the business, which record of each pair survives: usually the one with the most recent login, with related data merged into it.

Java
// Find the duplicate emails
db.users.aggregate([
{ $group: { _id: "$email", ids: { $push: "$_id" }, n: { $sum: 1 } } },
{ $match: { n: { $gt: 1 } } }
])
// { _id: "ana@example.com", ids: [ObjectId("...a1"), ObjectId("...b7")], n: 2 }
// After merging and removing duplicates, create the index explicitly
db.users.createIndex({ email: 1 }, { unique: true, name: "ux_users_email" })
// "ux_users_email"
Step throughMaking the unique rule real in production
  1. Compare getIndexes() in each environmentconfirms the index is missing
  2. Find duplicates with an aggregationgroup by email, count above 1
  3. Merge or remove duplicatesrule agreed with the business
  4. Create the unique index in a migrationMongock change unit or a script
  5. Catch DuplicateKeyException in the codereturn 409 or a clear message

5 steps in order. Play them, or step through them one at a time.

Then we make index creation part of how the schema is managed, not a side effect of startup. A migration tool such as Mongock runs versioned change units, records which ones ran, and lets us review index changes like any other code. Alternatively, a small startup component can call IndexOperations.ensureIndex() for a known list of indexes, which is explicit and visible, though it still builds the index from the application.

On large collections we plan the build. Since MongoDB 4.2 index builds hold an exclusive lock only briefly at the start and end, but they still consume CPU, memory and disk I/O, so we run them during quiet hours and watch replication lag. That is exactly why automatic creation on every deploy is a risk on big collections.

5Handling the Error in Spring

Once the index exists, a duplicate insert throws. Spring translates the MongoDB error into org.springframework.dao.DuplicateKeyException, so our registration code can turn it into a proper response instead of a server error.

Java
try {
userRepository.insert(new User(null, "ana@example.com"));
} catch (DuplicateKeyException e) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "email already registered"); // 409
}

Notice that checking existsByEmail() before inserting is not a replacement. Two registrations at the same moment can both see no user and both insert. Only the index closes that race.

6Follow-up questions

Should we just turn auto-index-creation on in production?

It would create the index on the next start, but it would fail on the existing duplicates, and on a large collection the build would start from application startup on every instance during a deploy. For small collections in a young service it can be acceptable, but explicit, reviewed migrations give us control over when and how indexes are built.

How do we stop this from happening again?

Add a test or a startup check that compares the indexes the entities declare with the indexes that exist, and fails or alerts when one is missing. Keep index definitions in migrations that run in every environment, including local, so every database gets the same indexes in the same way.

Does a unique index treat missing emails as duplicates?

Yes. A unique index stores a missing field as null, so two documents without email collide. If email is optional, we use a partial index with partialFilterExpression: { email: { $exists: true } }, or a sparse index, so that only documents that have the field are checked.

7Conclusion

In this answer, we saw that MongoDB enforces uniqueness only through a unique index on the server, and that since Spring Data MongoDB 3.0 @Indexed does not create one unless auto index creation is enabled. The developer's database got the index from that setting or from a manual step, production did not, so duplicates were accepted. We fixed it by finding and cleaning duplicates, creating the index explicitly through a migration or an IndexOperations step, and handling DuplicateKeyException in the code, while planning index builds on large collections carefully.

What to say in the interviewAbout 80 seconds aloud

Open with

The annotation alone does not create anything in the database. Since Spring Data MongoDB 3.0, automatic index creation from mapping annotations like @Indexed is off by default, so unless spring.data.mongodb.auto-index-creation is true, no unique index is ever built, and MongoDB happily accepts duplicate emails.

Then, if they want more

On the developer's machine the index probably exists because they enabled that property in a local profile, or created the index by hand or in a container init script. I would confirm it by running getIndexes on both databases.

To fix production, I first find the duplicates with an aggregation grouping by email, agree with the business which record wins, merge and remove the others, because creating a unique index fails while duplicates exist. Then I create the index explicitly, ideally through a migration tool such as Mongock, or an IndexOperations ensureIndex step that is visible and reviewed.

I would not rely on auto creation at startup for big collections, because index builds take time, CPU and I/O, and every instance would try it during a deploy. Finally, I catch DuplicateKeyException in the registration code and return a 409, and I add a check that declared and actual indexes match.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3
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 "A Spring Boot service with @Indexed(unique = true) on an email field allows duplicate...": https://scrivio-interview-library.netlify.app/databases/mongodb/641392656b/