DEV Community

kevindev
kevindev

Posted on

Replay-Safe Verification Tokens in PostgreSQL

Email verification looks like a small feature: create a token, send a message, and mark the account as verified when the user clicks it. In a real REST API, the click can arrive twice, arrive after expiry, or race with a retry from a mobile client. If the endpoint treats every request as a fresh command, the database state becomes hard to explain.

This post describes a replay-safe design for verification tokens in PostgreSQL. The same boundary is useful when a disposable email account is used in an integration test: the test should be able to repeat a request and still get a predictable result.

Why a token endpoint needs a replay policy

A verification token is a capability with a short lifetime. It should normally produce one successful transition:

issued -> consumed
Enter fullscreen mode Exit fullscreen mode

Several other outcomes are possible:

  • The token does not exist.
  • The token has expired.
  • Another request already consumed it.
  • Two requests tried to consume it at nearly the same time.

These outcomes should not be hidden behind a generic 500 response. A client may safely retry a network timeout, but it needs to know whether the first request actually succeeded. An OAuth flow has a similar concern; an OAuth replay boundary is a useful related pattern.

The important decision is to make the state transition authoritative in the database, not in application memory. A process restart, a second API instance, or a slow queue worker should not change the rule.

Model the verification as a database state transition

Keep the token record separate from the user record. This gives the API an audit-friendly place to record when a token was issued, consumed, and rejected.

CREATE TABLE email_verification_tokens (
  id BIGSERIAL PRIMARY KEY,
  user_id BIGINT NOT NULL,
  token_digest BYTEA NOT NULL UNIQUE,
  expires_at TIMESTAMPTZ NOT NULL,
  consumed_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX email_verification_tokens_user_idx
  ON email_verification_tokens (user_id);
Enter fullscreen mode Exit fullscreen mode

Store a digest rather than the raw token. The raw value belongs in the link sent to the user, while a database leak should not immediately turn every unexpired link into a usable credential. The digest column also gives us a stable lookup key.

Do not use a boolean such as is_verified on the token alone. A timestamp tells us when the transition happened and makes support investigations less guessy. The user account can still have its own verified state, updated in the same transaction.

Use PostgreSQL to claim a token once

The consume operation should check validity and claim the row in one statement. A conditional update is often simpler and safer than selecting first and updating later:

UPDATE email_verification_tokens
SET consumed_at = now()
WHERE token_digest = $1
  AND consumed_at IS NULL
  AND expires_at > now()
RETURNING user_id, consumed_at;
Enter fullscreen mode Exit fullscreen mode

If this returns one row, the request won the claim. If it returns zero rows, the API can perform a bounded follow-up lookup to distinguish expired, unknown, and already-consumed states. That lookup is informational; it must not be used to decide whether the token is valid.

Then update the user inside the same transaction:

UPDATE users
SET email_verified_at = COALESCE(email_verified_at, now())
WHERE id = $1;
Enter fullscreen mode Exit fullscreen mode

The COALESCE makes the user update tolerant of an already verified account, while the token claim remains one-time. This is a small but important distinction: verification of the account can be idempotent even though consumption of a particular token is not repeatable.

Make the REST API response deterministic

A useful endpoint contract might be:

POST /v1/email-verifications/consume
Enter fullscreen mode Exit fullscreen mode

Return a success response only when the transaction claimed the token and updated the account. For a second click, use a stable conflict response such as 409 with a machine-readable code:

{
  "error": "verification_token_unavailable",
  "reason": "consumed_or_expired"
}
Enter fullscreen mode Exit fullscreen mode

Avoid exposing whether an arbitrary token belongs to a real account. For unknown, expired, and consumed tokens, a deliberately similar response prevents the endpoint from becoming an account-enumeration oracle. The exact status code can vary with your product contract, but it should be documented and tested.

If the client times out after the commit, a retry may receive the conflict response even though the first request succeeded. That is why the client should refresh account state after an ambiguous result. A request ID and structured logs make this diagnosis much less painfull.

For test environments, isolate inboxes and credentials by run. Run-scoped email test data helps prevent one build from consuming another build's token. A fixture named temp gamil com should be treated as ordinary test input, not as a special case in production validation.

Test concurrency and expiry

The most valuable tests are not only happy-path tests. Add cases for:

  1. A valid token is consumed once and verifies the user.
  2. The same token is submitted twice; exactly one request claims it.
  3. Two concurrent requests use the same digest; one gets success and one gets the documented conflict.
  4. An expired token cannot be claimed, even if the application clock has not yet cleaned it up.
  5. A malformed token does not cause an expensive unbounded database query.
  6. A transaction rollback leaves both the token and user unchanged.

Run the concurrency case against a real PostgreSQL instance. Mocks rarely reproduce row locks, transaction isolation, or the timing around RETURNING. Add a short comment to the test explaining the expected winner behavior; otherwise a future refactor may accidentally turn the race into two successes.

A practical checklist

  • Hash verification tokens before storing them.
  • Put expiry and consumption checks in the conditional update.
  • Update token and account state in one transaction.
  • Return a stable, documented error for replay and expiry.
  • Avoid leaking account existence through token errors.
  • Test concurrent requests against PostgreSQL.
  • Log a request ID, token record ID, and outcome without logging the raw token.
  • Keep email delivery separate from the database claim operation.

The design is not complicated, but the ordering matters. Let PostgreSQL own the one-time state transition, let the REST API expose a predictable contract, and let retries be an expected behavior instead of an incident. That gives backend services a verification flow that remains understandable under duplicate clicks, slow networks, and parallel workers.

Top comments (0)