Skip to lesson

Handling duplicate emails

Two people can try the same e-mail, and so can one person with a double tap. ShopLite must answer clearly, yet never end up with two accounts for one address, however fast the requests arrive.

Checking existsByEmail first, and why it is not enough

Race condition is a bug where the result depends on timing, for example two requests that both pass a check before either one has written its row.

A check before the insert catches the usual repeat. Example 1 shows it, and Example 2 shows what slips past it.

Example 1 · The early check: existsByEmail before saving

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Java
// UserService.register: the early check (first version, no constraint handling yet)@Transactionalpublic UserResponse register(SignUpRequest request) {    String email = Emails.normalise(request.email());    if (users.existsByEmail(email) || customers.existsByEmail(email)) {        throw new DuplicateEmailException(email);    }    Customer customer = customers.save(new Customer(request.fullName(), email, request.phone()));    User user = new User(email, passwordEncoder.encode(request.password()), customer, Role.CUSTOMER);    users.save(user);    return UserResponse.from(user);}
Sample output
$ curl -i -X POST http://localhost:8080/api/v1/auth/register -H "Content-Type: application/json" -d '{"fullName":"Sneha P","email":"SNEHA.PATIL@example.com","password":"another long passphrase","phone":null}'
HTTP/1.1 409
Content-Type: application/problem+json
...

{"type":"https://shoplite.example/problems/already-exists","title":"Resource already exists","status":409,"detail":"An account with e-mail sneha.patil@example.com already exists.","instance":"/api/v1/auth/register"}

$ curl -X POST http://localhost:8080/api/v1/auth/register -H "Content-Type: application/json" -d '{"fullName":"Ravi K","email":"Ravi.Kumar@example.com","password":"another long passphrase","phone":null}'
{"type":"https://shoplite.example/problems/already-exists","title":"Resource already exists","status":409,"detail":"An account with e-mail ravi.kumar@example.com already exists.","instance":"/api/v1/auth/register"}

What this code does

  • SNEHA.PATIL@example.com is normalised first, so it is found as the existing sneha.patil@example.com and the answer is 409, not a second account.
  • Ravi is a seed customer without an account. His e-mail is in customers, so sign-up is refused too: the unique customers.email column would reject the INSERT anyway.
  • The check runs before encode, so a duplicate costs no slow hash.

Example 2 · Race: six sign-ups at once, without the unique constraints

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Terminal
# Six sign-ups with the same e-mail at the same moment (& runs each curl in the background)for i in 1 2 3 4 5 6; do  curl -s -o /dev/null -w "request $i: %{http_code}\n" -X POST http://localhost:8080/api/v1/auth/register \       -H "Content-Type: application/json" \       -d '{"fullName":"Rahul Verma","email":"rahul.verma@example.com","password":"cricket on the hostel terrace"}' &donewait
Sample output
(lab database with uq_customers_email and uq_app_user_email dropped)
request 2: 201
request 3: 201
request 6: 201
request 5: 201
request 4: 201
request 1: 201

mysql> SELECT user_id, email, customer_id FROM app_user WHERE email = 'rahul.verma@example.com';
user_id  email                    customer_id
3        rahul.verma@example.com  9
4        rahul.verma@example.com  13
5        rahul.verma@example.com  11
6        rahul.verma@example.com  14
7        rahul.verma@example.com  12
8        rahul.verma@example.com  10

$ curl -s -o /dev/null -w "sign-in: %{http_code}\n" -u "rahul.verma@example.com:cricket on the hostel terrace" http://localhost:8080/api/v1/customers/9
sign-in: 401

Server log (org.springframework.security=DEBUG):
DEBUG o.s.s.authentication.ProviderManager     : Authentication service failed internally for user 'rahul.verma@example.com'
org.springframework.security.authentication.InternalAuthenticationServiceException: Query did not return a unique result: 6 results were returned
Caused by: org.springframework.dao.IncorrectResultSizeDataAccessException: Query did not return a unique result: 6 results were returned

What this code does

  • All six requests ran existsByEmail before any of them had committed, so all six passed the check. The responses arrive in a random order.
  • Six app_user rows and six customers now share one e-mail. Nothing in the Java code was wrong line by line; the timing was.
  • Sign-in breaks for this address: findByEmail expects one row and gets six, so Spring Security reports an internal error and answers 401. Cleaning such data up by hand is slow and risky.

users.existsByEmail(email) || customers.existsByEmail(email) at the start of register handles the usual case: someone who forgot they already signed up, or a seed customer like Ravi who has no account yet. If either table has the address, the service throws DuplicateEmailException before it hashes anything.

The check alone is not enough, because there is a gap of a few milliseconds between the check and the INSERT. A double tap on "Sign up", a slow network that resends, or a script puts two requests into that gap. In Example 2, six simultaneous requests on a lab database without the UNIQUE constraints give six 201s and six accounts, and nobody can sign in with that address any more, because findByEmail finds six rows.

Predict the output

Two requests at once

Two sign-ups with the same new e-mail run at the same moment.

Round 1 of 2

There is no UNIQUE constraint. What can happen?

if (users.existsByEmail(email)) {
throw new DuplicateEmailException(email);
}
users.save(newUser);

The unique constraint as the real guard

UNIQUE constraint makes the database itself refuse a second row with the same value, however many requests arrive at once. In ShopLite: uq_app_user_email, and uq_customers_email from Section 12.

The database sees every row, so it is the real guard. register uses saveAndFlush inside a try to catch its refusal. Example 3 is the service.

Two sign-ups with the same e-mail arrive together and both see no row. Request A inserts and gets 201. Request B inserts too, but the UNIQUE constraint refuses it with MySQL error 1062, so the answer is 409 already-exists. The database lets only one insert win.

Example 3 · src/main/java/com/shoplite/user/UserService.java: the constraint as the guard

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

UserService.javaJava
package com.shoplite.user;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.dao.DataIntegrityViolationException;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;
/** Accounts: sign-up now; password change and disabling later. */@Servicepublic class UserService {
    private static final Logger log = LoggerFactory.getLogger(UserService.class);
    private final UserRepository users;    private final CustomerRepository customers;    private final PasswordEncoder passwordEncoder;
    UserService(UserRepository users, CustomerRepository customers, PasswordEncoder passwordEncoder) {        this.users = users;        this.customers = customers;        this.passwordEncoder = passwordEncoder;    }
    /** Creates the customer row and its CUSTOMER account together: both are saved, or neither. */    @Transactional    public UserResponse register(SignUpRequest request) {        String email = Emails.normalise(request.email());        if (users.existsByEmail(email) || customers.existsByEmail(email)) {            throw new DuplicateEmailException(email);           // the usual case: a clear, early answer        }        try {            Customer customer = customers.saveAndFlush(new Customer(request.fullName(), email, request.phone()));            User user = new User(email, passwordEncoder.encode(request.password()), customer, Role.CUSTOMER);            users.saveAndFlush(user);            log.info("New customer account {} for customer {}", user.getId(), customer.getId());            return UserResponse.from(user);        } catch (DataIntegrityViolationException e) {            // Another request with the same e-mail committed between our check and our INSERT;            // the UNIQUE constraint stopped this one. Same answer as the early check.            log.info("Sign-up stopped by the unique e-mail constraint (two requests at once)");            throw new DuplicateEmailException(email, e);        }    }}
Sample output
request 3: 201
request 4: 409
request 6: 409
request 1: 409
request 2: 409
request 5: 409

Server log:
INFO  com.shoplite.user.UserService            : New customer account 4 for customer 10
WARN  org.hibernate.orm.jdbc.error             : HHH000247: ErrorCode: 1062, SQLState: 23000
WARN  org.hibernate.orm.jdbc.error             : Duplicate entry 'rahul.verma@example.com' for key 'customers.uq_customers_email'
... (the same two WARN lines for each of the other four requests)
INFO  com.shoplite.user.UserService            : Sign-up stopped by the unique e-mail constraint (two requests at once)
INFO  com.shoplite.user.UserService            : Sign-up stopped by the unique e-mail constraint (two requests at once)
INFO  com.shoplite.user.UserService            : Sign-up stopped by the unique e-mail constraint (two requests at once)
INFO  com.shoplite.user.UserService            : Sign-up stopped by the unique e-mail constraint (two requests at once)
INFO  com.shoplite.user.UserService            : Sign-up stopped by the unique e-mail constraint (two requests at once)

mysql> SELECT user_id, email, customer_id FROM app_user WHERE email = 'rahul.verma@example.com';
user_id  email                    customer_id
4        rahul.verma@example.com  10

What this code does

  • The same six requests against the real schema: one 201, five 409. Five requests still passed the early check, but MySQL refused their INSERT into customers with error 1062.
  • saveAndFlush sends the INSERT at once, inside the try, so DataIntegrityViolationException is caught there and becomes DuplicateEmailException. The transaction rolls back, so no half-made customer is left.
  • The INFO line logs the event without the e-mail address: personal data stays out of the log. The WARN lines come from Hibernate itself.

When the constraint fires, Hibernate gets MySQL error 1062 (Duplicate entry ... for key ...) and Spring turns it into DataIntegrityViolationException. register catches it and throws DuplicateEmailException, so the client gets the same 409 whether the early check or the database caught it. The early check only makes the common case fast and friendly.

What can go wrong: with plain save, the INSERT may only run at commit, after the method has returned, so the catch never sees it and the client gets a 500. The catch also turns every integrity error into "duplicate e-mail"; that is safe here only because the e-mail columns are the only unique values register can break.

DuplicateEmailException mapped to 409 in the global handler

DuplicateEmailException is the exception for a sign-up whose e-mail already has an account. It extends AlreadyExistsException, so the existing handler answers 409 already-exists with no new code.

The exception reuses the Section 15 error mapping, so the service holds no HTTP code. Example 4 shows the classes and what the client receives.

Example 4 · DuplicateEmailException and the existing 409 handler

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

AlreadyExistsException.javaJava
// src/main/java/com/shoplite/common/AlreadyExistsException.javapackage com.shoplite.common;
/** A duplicate of something that must be unique: a SKU, an e-mail, a category name. */public class AlreadyExistsException extends ConflictException {
    public AlreadyExistsException(String message) {        super(message);    }
    public AlreadyExistsException(String message, Throwable cause) {        super(message, cause);    }}
// src/main/java/com/shoplite/user/DuplicateEmailException.javapackage com.shoplite.user;
import com.shoplite.common.AlreadyExistsException;
/** Sign-up with an e-mail that already has an account. The global handler answers 409 already-exists. */public class DuplicateEmailException extends AlreadyExistsException {
    public DuplicateEmailException(String email) {        super(message(email));    }
    public DuplicateEmailException(String email, Throwable cause) {        super(message(email), cause);    }
    private static String message(String email) {        return "An account with e-mail " + email + " already exists.";    }}
// src/main/java/com/shoplite/common/GlobalExceptionHandler.java (the existing handler, unchanged)@ExceptionHandler(AlreadyExistsException.class)public ProblemDetail handleAlreadyExists(AlreadyExistsException ex) {    return ProblemKind.ALREADY_EXISTS.problem(ex.getMessage());}
Sample output
What the repository throws on the duplicate INSERT (printed in a lab run of UserRepositoryIT):
org.springframework.dao.DataIntegrityViolationException: could not execute statement [Duplicate entry 'kiran.staff@shoplite.example' for key 'app_user.uq_app_user_email'] [insert into app_user (customer_id,email,enabled,password_hash) values (?,?,?,?)]; SQL [insert into app_user (customer_id,email,enabled,password_hash) values (?,?,?,?)]; constraint [app_user.uq_app_user_email]
most specific cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'kiran.staff@shoplite.example' for key 'app_user.uq_app_user_email'

What the client receives:
{"type":"https://shoplite.example/problems/already-exists","title":"Resource already exists","status":409,"detail":"An account with e-mail rahul.verma@example.com already exists.","instance":"/api/v1/auth/register"}

What this code does

  • Spring's exception names the constraint (app_user.uq_app_user_email) and holds MySQL's SQLIntegrityConstraintViolationException as the most specific cause; all of this stays in the server.
  • DuplicateEmailException keeps it as the cause and gives the client one safe sentence. No SQL, table names or class names in the response, as the contract demands.
  • Because it is an AlreadyExistsException, the Section 15 handler maps it without any change: one place for every error mapping.

The exception carries the e-mail in its message and, in the race case, the DataIntegrityViolationException as its cause, so the server log keeps the full story. AlreadyExistsException and ConflictException get a second (message, cause) constructor for that; nothing else in common changes.

Why 409 and not 400 or 422? The request itself is fine, field by field. The request clashes with the current state of the data: that is the contract's definition of 409, the same as a duplicate SKU or category name.

Account enumeration: what the error reveals

Account enumeration is an attack where someone learns which e-mail addresses have accounts by watching your answers, then targets those people with phishing or password guessing.

Sign-in and sign-up answer differently. This table compares what each one reveals.

Text
Sign-up, e-mail already used          Sign-in, unknown e-mail or wrong password--------------------------------      -----------------------------------------409 already-exists                    401, the same answer for both cases"An account with e-mail ...           (Spring Security hides which one, Lesson 2) already exists."Reveals: this address has an account  Reveals: nothing

ShopLite's sign-in gives one 401 for a wrong password and for an unknown e-mail, but sign-up says that an address is registered. That is a trade-off, not a bug: a clear message saves real users from confusion, and the address alone does not open the account. The protections go elsewhere: rate limits on sign-up, the same 401 at sign-in, and the brute-force defences in the Common Security Mistakes module.

When the list of members is itself secret (a health or dating app), sign-up answers "Check your e-mail to continue" every time and sends the real result by e-mail. ShopLite has no e-mail sending yet, so it keeps the 409 and writes the decision down in SECURITY.md.

Testing the duplicate case

@DataJpaTest starts only the JPA part of a Spring Boot application, with entities, repositories and a database, and rolls back every test, so a repository can be tested without a web server.

A @DataJpaTest proves the UNIQUE constraint exists, and a @WebMvcTest with a mocked service proves the 409 answer. Examples 5 and 6 are the two tests.

Example 5 · src/test/java/com/shoplite/user/UserRepositoryIT.java: the constraint exists

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Java
package com.shoplite.user;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;import org.springframework.dao.DataIntegrityViolationException;import org.springframework.test.context.ActiveProfiles;
/** The users table on a real MySQL test database. Each test runs in a transaction that is rolled back. */@DataJpaTest@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)   // MySQL, not an in-memory database@ActiveProfiles("test")class UserRepositoryIT {
    @Autowired    private UserRepository users;
    @Test    void savesAUserWithItsRoleAndFindsItByEmail() {        users.saveAndFlush(new User("kiran.staff@shoplite.example", "{bcrypt}$2a$10$hash", null, Role.ADMIN));
        User found = users.findByEmail("kiran.staff@shoplite.example").orElseThrow();
        assertThat(found.getId()).isNotNull();        assertThat(found.getRoles()).containsExactly(Role.ADMIN);        assertThat(found.isEnabled()).isTrue();        assertThat(users.existsByEmail("kiran.staff@shoplite.example")).isTrue();    }
    @Test    void theUniqueConstraintStopsASecondAccountWithTheSameEmail() {        users.saveAndFlush(new User("kiran.staff@shoplite.example", "{bcrypt}$2a$10$first", null, Role.ADMIN));
        User copy = new User("kiran.staff@shoplite.example", "{bcrypt}$2a$10$second", null, Role.ADMIN);
        assertThatThrownBy(() -> users.saveAndFlush(copy))                .isInstanceOf(DataIntegrityViolationException.class)                .hasMessageContaining("uq_app_user_email");    }}
Sample output
$ mvn verify
...
[INFO] --- surefire:3.5.6:test (default-test) @ shoplite-api ---
[INFO] Running com.shoplite.user.AuthControllerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 15.57 s -- in com.shoplite.user.AuthControllerTest
...
[INFO] --- failsafe:3.5.6:integration-test (default) @ shoplite-api ---
[INFO] Running com.shoplite.user.SignUpAndSignInIT
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 32.92 s -- in com.shoplite.user.SignUpAndSignInIT
[INFO] Running com.shoplite.user.UserRepositoryIT
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.211 s -- in com.shoplite.user.UserRepositoryIT
[INFO] Results:
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

What this code does

  • saveAndFlush forces each INSERT to run inside the test, so the second one fails right there and assertThatThrownBy can see it.
  • hasMessageContaining("uq_app_user_email") proves the right constraint fired. If someone deletes it from a migration, this test fails before production does.
  • Both tests pass on the MySQL test database that Flyway built from V1 to V4; the transaction rollback leaves it empty again.

Example 6 · src/test/java/com/shoplite/user/AuthControllerTest.java: the 409 shape

Runs in: the shoplite-api Spring Boot project (Spring Boot 4.1, Spring Security 7, MySQL)

Java
package com.shoplite.user;
import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.any;import static org.mockito.BDDMockito.given;import static org.mockito.Mockito.verifyNoInteractions;
import java.util.List;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;import org.springframework.context.annotation.Import;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.test.web.servlet.assertj.MockMvcTester;
import com.shoplite.common.security.SecurityConfig;
/** POST /api/v1/auth/register through the real security rules and error handler, with a mocked service. */@WebMvcTest(AuthController.class)@Import(SecurityConfig.class)class AuthControllerTest {
    private static final String SNEHA = """            {"fullName": "Sneha Patil", "email": "sneha.patil@example.com",             "password": "my laptop bag arrives at 7 pm", "phone": "9876543209"}            """;
    @Autowired    private MockMvcTester mvc;
    @MockitoBean    private UserService userService;
    @Test    void signUpIsPublicAndAnswers201WithoutThePassword() {        given(userService.register(any())).willReturn(                new UserResponse(3, "sneha.patil@example.com", "Sneha Patil", 9, List.of("CUSTOMER")));
        assertThat(mvc.post().uri("/api/v1/auth/register").contentType(MediaType.APPLICATION_JSON).content(SNEHA))                .hasStatus(HttpStatus.CREATED)                .hasHeader("Location", "http://localhost/api/v1/customers/9")                .bodyJson().isStrictlyEqualTo("""                        {"id": 3, "email": "sneha.patil@example.com", "fullName": "Sneha Patil",                         "customerId": 9, "roles": ["CUSTOMER"]}                        """);    }
    @Test    void duplicateEmailIs409AlreadyExists() {        given(userService.register(any())).willThrow(new DuplicateEmailException("sneha.patil@example.com"));
        assertThat(mvc.post().uri("/api/v1/auth/register").contentType(MediaType.APPLICATION_JSON).content(SNEHA))                .hasStatus(HttpStatus.CONFLICT)                .hasContentType(MediaType.APPLICATION_PROBLEM_JSON)                .bodyJson().isLenientlyEqualTo("""                        {"type": "https://shoplite.example/problems/already-exists",                         "title": "Resource already exists", "status": 409,                         "detail": "An account with e-mail sneha.patil@example.com already exists."}                        """);    }
    @Test    void shortPasswordIs400AndTheServiceIsNeverCalled() {        String body = """                {"fullName": "Sneha Patil", "email": "sneha.patil@example.com", "password": "campus123"}                """;
        assertThat(mvc.post().uri("/api/v1/auth/register").contentType(MediaType.APPLICATION_JSON).content(body))                .hasStatus(HttpStatus.BAD_REQUEST)                .bodyJson().isLenientlyEqualTo("""                        {"type": "https://shoplite.example/problems/validation-failed",                         "errors": [{"field": "password", "message": "must be 15-64 characters"}]}                        """);        verifyNoInteractions(userService);    }}
Sample output
$ mvn test
...
[INFO] Running com.shoplite.user.AuthControllerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 15.57 s -- in com.shoplite.user.AuthControllerTest
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

What this code does

  • @WebMvcTest(AuthController.class) with @Import(SecurityConfig.class) runs the real security rules: the tests also prove that sign-up needs no credentials.
  • duplicateEmailIs409AlreadyExists checks status, application/problem+json and the body leniently: the extra instance field may be there.
  • The service is a @MockitoBean, so this test needs no database and runs in mvn test; the database tests run in mvn verify.

@AutoConfigureTestDatabase(replace = NONE) keeps the MySQL test database instead of an in-memory one, so the test sees the real constraint; Flyway builds the tables on the empty test database. The repository test is named ...IT, so mvn verify runs it with the other database tests.

The race itself is hard to unit-test reliably. The six parallel curl calls of Example 3 are the realistic check, and the constraint test proves the guard exists.

Next step

Check your understanding

12 quick questions