DEV Community

kevindev
kevindev

Posted on

Audit-Friendly Email Verification APIs

A practical design for email verification endpoints that remain explainable when retries, delayed messages, and support questions arrive together.

Email verification looks like a small authentication feature until a production incident asks a simple question: why was this account still unverified after the user clicked the link?

The answer is often spread across an API log, a message provider, a worker queue, and a database row. When each component has a slightly different idea of the current state, the endpoint may work in the happy path but become difficult to operate. My preferred approach is to make the verification workflow an explicit, auditable boundary in the backend.

Why verification APIs become hard to audit

Most implementations begin with three actions:

  1. Create a verification token.
  2. Send an email containing the token.
  3. Mark the user as verified when the token is opened.

The hidden complexity is in the transitions between those actions. A client can retry the create request. A worker can deliver the same message twice. A user can click an old link after requesting a new one. The email can arrive after the token has been revoked. If the system only records verified = true, these cases collapse into one vague outcome.

The useful design question is not “did the email send?” It is “which verification attempt owns this result, and can I prove the transition?”

For engineers maintaining an API, this distinction saves time during support work. It also makes automated tests less dependent on reading an inbox by guesswork. A clear pattern for validating approval emails in CI is useful here: treat the message as evidence for a state transition, not as the state itself.

Model the workflow as a state machine

Give each verification attempt an identifier and a small set of allowed states. For example:

created -> sent -> opened -> accepted
                    \-> expired
                    \-> revoked
Enter fullscreen mode Exit fullscreen mode

The exact names are less important than the ownership rules. An attempt should not move from expired back to accepted, and a second click on an already accepted token should be safe and predictable. This is where many implementations gets vague: they validate the token, then update the user without checking the attempt's current state.

I normally keep these fields together:

  • verification_id: a public correlation identifier
  • user_id: the account being verified
  • token_digest: a hash of the secret, never the raw token
  • state: the current state of the attempt
  • expires_at: the acceptance deadline
  • created_at and updated_at: transition evidence
  • accepted_at: when the account actually became verified

Keep the raw token only long enough to put it in the message. The database needs the digest, so a leaked row does not become a ready-made login link. This small detail is easy to miss during a quick implementation.

Use PostgreSQL as the source of truth

The user record and verification attempt should be updated with a deliberate transaction boundary. A typical acceptance operation is:

  1. Hash the presented token.
  2. Lock the matching attempt row.
  3. Check its state and expiration timestamp.
  4. Transition the attempt to accepted.
  5. Mark the user as verified.
  6. Commit both changes together.

The row lock matters when two requests arrive nearly together. Without it, both requests can observe sent and both can claim success. The second request should instead receive an idempotent result or a clear conflict, depending on your product contract.

An audit table can record verification_id, prior state, next state, request identifier, and a reason code. Do not store the token in that table. The audit record is for explaining behavior, not for reconstructing secrets.

You also want a uniqueness rule for active attempts, or a documented policy for multiple attempts. Replacing the old token without marking it revoked is a common source of “which link should work?” incidents. The database should make the answer unambiguous.

Design the REST API around safe retries

The create endpoint should accept an idempotency key from the client. Store the key with the resulting verification attempt, and return the same response when a request is retried. This keeps a network timeout from creating several valid messages for one user.

The acceptance endpoint can use a response model like this:

{
  "verification_id": "ver_8f2c",
  "status": "accepted",
  "message": "Email verification completed"
}
Enter fullscreen mode Exit fullscreen mode

For an already accepted attempt, returning the same successful status is often friendlier than treating a browser refresh as an error. For an expired or revoked attempt, return a stable application error code, not a detailed explanation of whether a token existed. This reduces information leakage while giving the frontend something actionable.

The logs should connect the request ID, verification ID, and state transition. They should not log the token, full verification URL, or the complete email address. Authentication email design also benefits from setting safer boundaries around authentication emails, especially when links cross browser sessions or providers.

Keep test email data inside an explicit boundary

Integration tests need a mailbox that behaves consistently, but test data should still have a lifecycle. Use a dedicated test domain or temp org mail fixture, tag every message with the test run, and delete or quarantine messages when the run ends. Do not let a shared inbox become an accidental database for tokens.

For tests, assert the important chain rather than only checking that a message exists:

  • the API returns one verification ID for a retried create request;
  • the message contains the expected verification ID;
  • the acceptance request changes exactly one attempt;
  • a second acceptance is safe;
  • an expired token cannot verify the account;
  • the audit record explains each transition.

This test shape catches races that a basic “open email and click link” script will miss. It also makes failures easier to reproduce locally.

A practical implementation checklist

Before shipping an email verification API, check that:

  • token secrets are stored as digests;
  • state transitions are validated inside a transaction;
  • concurrent acceptance requests cannot both perform the first transition;
  • create requests support safe retries;
  • expiration and revocation are explicit states;
  • logs contain correlation IDs but no secrets;
  • test messages have an owner and deletion policy;
  • metrics distinguish sent, opened, accepted, expired, and rejected attempts.

The goal is not to build a complicated workflow engine. It is to make a small authentication boundary honest about state, ownership, and time. When an email is delayed or a client retries, the REST API should still tell one consistent story, and PostgreSQL should be able to prove how that story happened.

Top comments (0)