Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Two instances of a Spring Boot service sometimes create duplicate accounts for the same email because they first SELECT, then INSERT. Show a correct approach using the database and handle the error in Java.

The SELECT-then-INSERT race cannot be closed in the application, because two transactions can both see 'no row' before either inserts. We put the rule where all inserts meet: a unique index on the normalised email, lower(email). Then we either insert with INSERT ... ON CONFLICT ((lower(email))) DO NOTHING RETURNING id in PostgreSQL (INSERT IGNORE or ON DUPLICATE KEY UPDATE in MySQL), or insert normally and translate a DataIntegrityViolationException for our named constraint into a 409 or an 'already exists' result.

Why this question is asked

Duplicate accounts are a classic production bug that every test passes. With one instance and one user it never happens; with two instances and a double-clicked sign-up button, it happens a few times a week. Interviewers ask this coding question because the right answer moves the responsibility from Java code to the database and then handles the database's answer properly in Java. In this answer, we will reproduce the race, see why transactions do not prevent it, add the unique index, write the PostgreSQL and MySQL inserts, handle the error with Spring and JPA, and make the operation safe to retry.

1Reproducing the Race

The current code checks for an existing account and inserts if there is none. Two requests for the same email arrive at the same moment, one on each instance.

Java
@Transactional
public Account register(String email) {
if (repo.existsByEmail(email)) { // A: false B: false
throw new AlreadyExistsException(email);
}
return repo.save(new Account(email)); // A: inserts B: inserts -> two accounts
}
Step throughCheck-then-insert race
Instance ADatabaseInstance B
SELECT ... WHERE email = 'ann@x.io'
SELECT ... WHERE email = 'ann@x.io'
no row
no row
INSERT ann@x.io, COMMIT
INSERT ann@x.io, COMMIT
without a unique index: second account created

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

Both requests run the SELECT before either INSERT commits, so both see no row and both insert. The @Transactional annotation does not help. At READ COMMITTED, the default isolation level in PostgreSQL, each transaction sees only committed data, and neither insert is committed when the other one checks. REPEATABLE READ, the default in MySQL InnoDB, behaves the same here: both snapshots show no row. Only SERIALIZABLE in PostgreSQL would detect the conflict, by failing one transaction with a serialization error that we must retry, which is heavier than the real fix. The application simply cannot see the other instance's uncommitted work; the database can.

2Putting the Rule in the Database

A unique index is checked inside the database at the moment of insert, and it sees all concurrent inserts, including uncommitted ones: if two transactions insert the same key, the second waits for the first, and fails if the first commits. We index the normalised email, so Ann@x.io and ann@x.io count as the same, and we give it a clear name so code can recognise it.

SQL
CREATE UNIQUE INDEX CONCURRENTLY accounts_email_lower_uq ON accounts (lower(email));
-- existing duplicates make this fail: find and merge them first
-- SELECT lower(email), count(*) FROM accounts GROUP BY 1 HAVING count(*) > 1;

3Option 1: Insert With ON CONFLICT

PostgreSQL's INSERT ... ON CONFLICT lets the insert itself decide what to do when the unique index already holds the key. With DO NOTHING, a conflicting insert simply inserts nothing. RETURNING id then returns the new id when a row was inserted and no row when it was not, which tells us which case happened. The conflict target names the index expression in an extra pair of parentheses.

Java
Long id = jdbc.query("""
INSERT INTO accounts (email) VALUES (?)
ON CONFLICT ((lower(email))) DO NOTHING
RETURNING id""",
rs -> rs.next() ? rs.getLong(1) : null, email);
if (id == null) { // 'ann@x.io' already existed
throw new AlreadyExistsException(email); // mapped to 409 Conflict
}
return id; // 1042, a new account
// MySQL equivalents, with a unique index on a functional key part or generated column:
// INSERT IGNORE INTO accounts (email) VALUES (?) -> 0 rows affected on duplicate
// INSERT INTO accounts (email) VALUES (?) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)
// -> LAST_INSERT_ID() is the existing id

This is the cleanest option for plain JDBC, because the duplicate is a normal outcome rather than an exception, and the transaction is not aborted. In MySQL, INSERT IGNORE turns the duplicate into a warning, but it also ignores some other errors, so ON DUPLICATE KEY UPDATE with the LAST_INSERT_ID trick, which returns the existing row's id, is often preferred.

4Option 2: Insert Normally and Translate the Error

With JPA, we usually keep save() and handle the violation. The catch is timing: JPA may delay the INSERT until flush or commit, so the exception would appear outside our method. saveAndFlush forces the insert immediately. Spring translates the driver's error into a DataIntegrityViolationException, and we check which constraint failed before deciding it is a duplicate.

Java
public Account register(String email) {
try {
return repo.saveAndFlush(new Account(email.strip()));
} catch (DataIntegrityViolationException e) {
if (isConstraint(e, "accounts_email_lower_uq")) {
throw new AlreadyExistsException(email); // 409 Conflict
}
throw e; // some other rule failed: a real bug
}
}
static boolean isConstraint(Throwable e, String name) {
for (Throwable t = e; t != null; t = t.getCause()) {
if (t instanceof org.hibernate.exception.ConstraintViolationException c
&& name.equalsIgnoreCase(c.getConstraintName())) return true;
}
return false;
}

Notice why the constraint name matters. A table may have several unique indexes and NOT NULL or foreign key rules, all of which surface as DataIntegrityViolationException. Treating every one as 'email already exists' would hide real bugs. Naming the index explicitly makes the check reliable. Also note that in PostgreSQL a failed statement aborts the whole transaction, so after catching the exception we must not run further SQL in it; the method should end, and the transaction roll back.

5Making It Safe for Retries

Clients and gateways retry requests on timeouts, so the same sign-up may arrive twice even from one user. With the unique index, the second attempt cannot create a duplicate, but it returns 409 although the first attempt succeeded. To make the operation idempotent, meaning a repeated request gives the same result, the client sends an idempotency key, a unique request id. The server stores the key with the result in the same transaction as the account, under its own unique index, and a repeated key returns the stored result instead of a 409.

6Follow-up questions

How would you make this idempotent for retries?

Have the client generate an idempotency key per sign-up attempt and send it in a header. The server inserts the key into an idempotency table with a unique index, in the same transaction as the account, and stores the response, such as the new account id. If the same key arrives again, the insert conflicts, and the server returns the stored response with the original status. Without a key, a simpler rule works for sign-up: if the email exists and was created in the last few minutes from the same client, return the existing account's result instead of 409. Keys are cleaned up after a retention period, such as 24 hours.

Why not use a distributed lock around the check and insert?

A lock in Redis or similar adds another system and its own failure modes, such as expired locks during long pauses, and still depends on every code path taking it. The unique index is enforced by the database for every insert, from every service, script and migration, and it costs one index lookup. Locks are for coordinating work, not for guaranteeing data rules the database can enforce.

7Conclusion

In this answer, we saw why a SELECT-then-INSERT cannot prevent duplicate accounts across instances: at READ COMMITTED both transactions see no row before either insert commits. A unique index on lower(email) puts the rule where every insert meets. We then either inserted with ON CONFLICT ((lower(email))) DO NOTHING RETURNING id, or INSERT IGNORE or ON DUPLICATE KEY UPDATE in MySQL, or inserted with saveAndFlush and translated a DataIntegrityViolationException for the named constraint into a 409. Idempotency keys make retries return the original result.

What to say in the interviewAbout 90 seconds aloud

Open with

The check-then-insert can never be correct across two instances, because both transactions can run the SELECT before either INSERT commits, so both see no row and both insert.

Then, if they want more

A transaction at READ COMMITTED does not help, since neither can see the other's uncommitted row. The only place that sees all concurrent inserts is the database, so I would add a unique index on the normalised email, lower of email, with an explicit name like accounts_email_lower_uq, after cleaning up existing duplicates. Then in PostgreSQL I would write INSERT ...

ON CONFLICT on the lower email expression DO NOTHING RETURNING id. If I get an id back, the account is new; if I get no row, it already existed and I return 409 or an 'already exists' result. In MySQL the equivalents are INSERT IGNORE or ON DUPLICATE KEY UPDATE.

If the code uses JPA, I would call saveAndFlush so the insert happens inside my method, catch DataIntegrityViolationException, and check the constraint name in the cause chain, so only this specific violation becomes a 409 and other integrity errors still surface as bugs.

For retries, I would add an idempotency key from the client, stored with a unique index in the same transaction, so a repeated request gets the original response instead of a conflict.

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.
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 "Two instances of a Spring Boot service sometimes create duplicate accounts for the same...": https://scrivio-interview-library.netlify.app/databases/indexing/797f536452/