A database constraint beats an async validator

Two people sign up with dana@acme.example, three milliseconds apart. Maybe it's the same person double-clicking, maybe it's a retry from a flaky mobile connection. Both requests ask "is this email taken?" Both get "no". Both rows are saved.

Your validator was correct both times. The table still has a duplicate.

Heraclitus, as Plato reports him in the Cratylus, said you can't step into the same river twice. Your validator looked at the table once, and by the time the insert arrived it was a different table.

This article shows why a uniqueness check in application code can't guarantee uniqueness, what to do instead, and what to keep from the validator. Examples use ASP.NET Core, EF Core and PostgreSQL, but the reasoning holds for any stack and any database with unique constraints.

The whole argument in 40 seconds.

The version everyone writes first

A validator that asks the database whether the email exists:

public sealed class RegisterUserValidator : AbstractValidator<RegisterUser>
{
    public RegisterUserValidator(AppDbContext db)
    {
        RuleFor(x => x.Email)
            .NotEmpty()
            .EmailAddress()
            .MustAsync(async (email, ct) =>
                !await db.Users.AnyAsync(u => u.Email == email, ct))
            .WithMessage("This email is already registered.");
    }
}

The handler then trusts the validator and inserts:

var user = new User(command.Email, command.Name);
db.Users.Add(user);
await db.SaveChangesAsync(ct);
return TypedResults.Created($"/users/{user.Id}", user.Id);

It passes tests that exercise one request at a time. It works in the demo. It works in production for months, until two requests arrive close enough together.

Why it fails

The check and the insert are two separate moments, and nothing stops another request from running between them:

Timeline of two signups: both checks finish while the table is still empty, then both inserts save a row for the same email.

Time Request A Request B
0 ms SELECT email: not found
1 ms SELECT email: not found
2 ms INSERT dana@acme.example
3 ms INSERT dana@acme.example

Both checks see an empty table, because neither insert has happened yet. This is the classic check-then-act race, and it gets more likely exactly when you least want it: retries, double submits, load tests and traffic spikes.

Two common "fixes" don't close it:

Juvenal asked the right question in his Satires: quis custodiet ipsos custodes?, who will guard the guards themselves? The validator guards the table, but nothing guards the moment between its answer and your insert.

Only one component can enforce a rule across every writer: the database. So the rule has to live there.

The fix: let the database say no

1. Add a unique index

protected override void OnModelCreating(ModelBuilder b)
{
    b.Entity<User>()
        .HasIndex(u => u.Email)
        .IsUnique()
        .HasDatabaseName("ix_users_email");
}

The migration produces something like:

CREATE UNIQUE INDEX ix_users_email ON users (email);

Now the two rows can't both be committed, however close together the requests are. PostgreSQL makes the second insert wait for the first transaction. If that one commits, the waiting insert gets a unique violation; if it rolls back, the waiting insert goes through.

A maxim that goes back to Roman law fits exactly: prior tempore, potior iure, first in time, stronger in right. A unique index applies it to commits: whichever insert commits first holds the value, and the other is refused. That is not always the request that arrived first.

2. Normalise before you store

Dana@Acme.example and dana@acme.example are different strings, so the index would happily store both. This application treats email addresses as case-insensitive account identifiers: it trims surrounding whitespace and stores a lower-case value, in one place, such as the User constructor or a value object, before the value reaches the database.

That is a product decision, not a rule of email. SMTP allows the part before the @ to be case-sensitive, so if you send mail to the address, keep it as the user typed it in a second column. PostgreSQL's citext type or a unique index on lower(email) enforces case-insensitive uniqueness inside the database; neither removes whitespace, so handle that separately.

3. Turn the violation into a clear answer

Without this step the client gets a 500. With Npgsql, a unique violation arrives as a DbUpdateException wrapping a PostgresException with SQL state 23505:

try
{
    await db.SaveChangesAsync(ct);
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException
{
    SqlState: PostgresErrorCodes.UniqueViolation,
    ConstraintName: "ix_users_email"
})
{
    return TypedResults.Problem(
        title: "Email already registered",
        detail: "An account with this email already exists.",
        statusCode: StatusCodes.Status409Conflict);
}

Checking ConstraintName matters once a table has more than one unique index: a clash on a different column deserves a different message. On SQL Server the same check looks at SqlException.Number 2601 or 2627. If you'd rather not write this per database, the EntityFrameworkCore.Exceptions packages translate provider errors into a common UniqueConstraintException.

Why 409 and not 400 or 422? The request is well formed and valid on its own; it conflicts with the current state of the server. That's what 409 Conflict is for. Retrying the request unchanged won't help while that state stays the same.

Keep the validator, change its job

You don't have to delete the async check. It gives a nicer message in the common case, for example on a signup form that checks the email as the user types. Just be clear about what it is:

If the pre-check costs a database round trip on every request and the form doesn't need live feedback, drop it. The constraint alone is enough for correctness, and you skip a query. Leave format rules (not empty, valid email, maximum length) in the validator: those depend only on the request, so there's no race.

When one unique index isn't enough

Real rules are rarely "this column is unique everywhere". Most of them still fit in the database:

Rule Database tool EF Core / SQL
Email unique per tenant Composite unique index HasIndex(u => new { u.TenantId, u.Email }).IsUnique()
Unique among active rows only (soft delete) Filtered (partial) unique index .IsUnique().HasFilter("deleted_at IS NULL")
One active subscription per customer Partial unique index on the status CREATE UNIQUE INDEX ... ON subscriptions (customer_id) WHERE status = 'active'
No overlapping bookings for a room Exclusion constraint EXCLUDE USING gist (room_id WITH =, during WITH &&)
A rule no constraint can express Advisory lock or SELECT ... FOR UPDATE on a parent row Serialise the check and the write for that one key

The last row is the escape hatch, not the default. A lock makes the check-then-act safe by forcing requests for the same key to queue, but you now own the lock's scope, timeouts and deadlocks. Reach for it only when the rule genuinely can't be written as a constraint.

One more option for inserts that may legitimately repeat, such as importing the same record twice: INSERT ... ON CONFLICT DO NOTHING (or DO UPDATE). That turns the duplicate into a no-op instead of an error, which is the right behaviour for idempotent writes and the wrong one for a signup, where the user needs to know.

The rule

  1. Validate shape in code. Format, length and required fields depend only on the request, so a validator can decide them alone.
  2. Enforce uniqueness in the database. A unique index, not a lookup. It's the only place that can enforce the rule across every writer.
  3. Turn the violation into a 409. Catch the specific constraint, return Problem Details, and keep the friendly pre-check only as a convenience.

The general version applies well beyond emails: every invariant you care about should have exactly one place that can't be bypassed. Pappus of Alexandria records Archimedes saying "give me a place to stand, and I will move the earth". Your invariants need the same thing, one fixed place to stand, and for data shared between requests that place is almost always the database.

Run it yourself

The companion sample is a minimal ASP.NET Core API that runs entirely in Docker, next to PostgreSQL. It exposes the same signup twice: POST /naive/users, guarded only by the async validator, and POST /users, guarded by the unique index. A small client fires 20 concurrent signups for the same email at each one, with a fresh address on every run so you can repeat it.

docker compose up -d --build
docker compose run --rm race

The API and the race client both run in containers alongside PostgreSQL, so Docker is the only thing you need installed. The README also shows how to run the API with the .NET SDK against the same database container.

One run on my machine:

POST /naive/users  20 concurrent signups for dana+9acca3dd@acme.example: 18 x 201, 2 x 409
POST /users        20 concurrent signups for dana+9acca3dd@acme.example: 1 x 201, 19 x 409

Eighteen accounts for one email on the naive endpoint, exactly one on the constrained endpoint. The naive numbers change from run to run. The constrained ones stay at one 201 and nineteen 409s as long as every request completes, because the address is new and only one insert can commit. The client adds a 30 ms delay between check and insert on both endpoints to stand in for real work, so the race shows up every time instead of once a month in production.

Further reading


This article is part of Justified Complexity: Building Backends One Decision at a Time.

Updated 2026-11-11: corrected the description of how a unique index resolves competing inserts (it does not guarantee that the first request wins), stated that lower-casing emails is this application's policy, clarified what citext and lower(email) cover, and explained how the validator's duplicate becomes a 409. The companion sample now handles a missing email without an error, and its race client can be rerun. The classical references now link to their sources, and the maxim prior tempore, potior iure is described as going back to Roman law, where it began as a ruling on competing pledges.