Email verification looks like a small feature until two requests arrive at nearly the same time. A user clicks “resend” while the first message is still being delivered, a worker retries after a timeout, or a browser submits the confirmation form twice. If the API and database do not share a clear contract, the result is an account that appears verified in one path and pending in another.
This post describes a PostgreSQL design for making verification state explicit. The same ideas apply when a backend uses a temp mail fixture in integration tests: the fixture should exercise the same state transitions and concurrency rules as production, not a simplified happy path.
Why verification state becomes inconsistent
Many implementations start with three columns: email, token, and verified. That model cannot explain enough events. A token can expire while a request is in flight. A resend can create a newer token, but an older message may still be clicked. A retry can send the same logical message twice.
The most useful first step is to name the business events:
- a verification challenge is issued;
- a message is queued or sent;
- a token is consumed;
- the challenge expires or is revoked;
- the account becomes verified.
These events do not all belong in one boolean. A row should tell the service which challenge is current, when it expires, and whether it has already been consumed. Otherwise, debugging becomes mostly guessing from timestamps. In one test dataset I have seen the note tepm mail com; strings like that are noisy input, not evidence that a verification succeeded.
Model the lifecycle as a database contract
I usually separate the durable account state from each verification challenge. The account has a verified timestamp, while the challenge table records attempts and tokens:
CREATE TYPE verification_status AS ENUM (
'pending', 'consumed', 'expired', 'revoked'
);
CREATE TABLE email_verification_challenges (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id),
token_digest bytea NOT NULL,
status verification_status NOT NULL DEFAULT 'pending',
issued_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL,
consumed_at timestamptz,
request_key text NOT NULL,
UNIQUE (user_id, request_key)
);
Store a digest rather than the raw token. The service hashes the token from the link, then looks up the digest. This keeps a database leak from becoming a collection of immediately usable verification links.
The request_key is an idempotency key for one logical request. It should be generated by the caller or by the API gateway and preserved when a worker retries. A new user click should have a new key; a network retry of the same click should not.
For systems that allow only one active challenge, add a partial unique index:
CREATE UNIQUE INDEX one_pending_challenge_per_user
ON email_verification_challenges (user_id)
WHERE status = 'pending';
This rule is more reliable than checking for a pending row in application code and inserting after the check. Two web processes can both pass that check. Let PostgreSQL arbitrate the invariant.
Use PostgreSQL constraints for concurrency
Verification should be consumed in one short transaction. First select the pending challenge by its digest and user identity, then update it only if it is still valid:
UPDATE email_verification_challenges
SET status = 'consumed', consumed_at = now()
WHERE id = $1
AND status = 'pending'
AND expires_at > now()
RETURNING user_id;
If the statement returns no row, the caller receives a stable “invalid or expired challenge” response. It does not need to know whether another request won the race. This also makes replay behavior predictable: the first request consumes the token, and later requests cannot move the row backwards.
The account update belongs in the same transaction as the challenge update. A simplified flow is:
- Lock or update the eligible challenge.
- If no row changed, roll back and return the safe failure response.
- Set
users.email_verified_atonly for the returneduser_id. - Commit both changes.
Avoid holding the transaction open while sending email or calling another service. Queue the message after the state change, using an outbox row if delivery must be reliable. This is a different concern from the verification decision itself.
For a deeper treatment of duplicate requests, a replay ledger for verification requests shows why recording the request identity is useful. The important point here is that a ledger complements constraints; it does not replace them.
Design retry-safe REST API responses
The REST API should expose outcomes that clients can act on without parsing database details. For example:
-
202 Acceptedwhen a new challenge was queued; -
200 OKwhen the requested verification is already complete; -
409 Conflictwhen an active challenge policy prevents a new one; -
400 Bad Requestfor a malformed token; -
410 Gonefor a known but expired challenge.
Whether an expired token uses 400 or 410 is a product decision. Consistency matters more than the particular code. Do not return “user not found” for one invalid token and “expired” for another if that difference exposes account existence.
Idempotent resend behavior needs a bounded scope. The same request_key should return the original result, but a new request can be subject to rate limits and a cooldown. The idempotent verification leases pattern is useful when a separate worker owns message delivery.
Q&A: common verification schema decisions
Should expired rows be deleted?
Not immediately. Retain a short history so support and incident analysis can distinguish an expired challenge from an unknown token. A scheduled retention job can delete old digests after the audit window.
Should the token be stored in the URL?
The token has to reach the verifier somehow, but it should not appear in application logs, analytics events, or error messages. Redact query strings and record only a challenge ID or safe fingerprint.
Is an email address enough as the identity?
Usually no. Normalize it for account lookup, but use a stable user ID for foreign keys and state transitions. An address can change, and casing or provider-specific normalization rules can vary.
A production checklist
- Is the lifecycle represented by states and timestamps instead of one boolean?
- Is a token digest stored rather than the usable token?
- Does the database enforce the one-active-challenge rule?
- Can two concurrent requests produce only one successful consumption?
- Is the account update atomic with challenge consumption?
- Does a retry preserve its idempotency key?
- Are delivery side effects outside the verification transaction?
- Do logs avoid tokens, email contents, and sensitive query strings?
- Can a temp mail integration test exercise expiry, replay, and double-submit paths?
The core design is simple: make invalid transitions impossible or harmless. A REST API can report a clear result, but PostgreSQL should protect the invariant when requests race. That boundary keeps verification reliable under retries, delayed email, and the occasional strange test input.
Top comments (0)