DEV Community

kevindev
kevindev

Posted on

A Replay Ledger for REST Email Verification

Email verification looks like a small feature: create a token, send a message, and accept the link. In a backend service, it is a stateful authentication workflow with retries, expiry, duplicate requests, and untrusted delivery infrastructure. Treating it as only an email-sending problem makes the REST API harder to reason about.

The result are familiar: a link works twice, a delayed message verifies an old account, or a retry creates several valid tokens. A replay ledger gives the service one durable place to answer a simple question: what happened to this verification attempt?

The missing boundary in email verification

A verification request usually crosses four boundaries:

  1. The client asks the REST API to start verification.
  2. The API records an attempt and queues a message.
  3. A mail provider delivers a link to a mailbox.
  4. The client calls the API with the token from that link.

The mailbox is not the source of truth. It is only a transport for a secret-bearing message. Even a controlled temp mailbox can be delayed, duplicated, or read by the wrong test worker. A temp email generator is useful for isolated staging checks, but it should not decide whether a token is valid.

I prefer to make the database own the lifecycle. The API creates one verification attempt, the worker sends a message for that attempt, and the consume endpoint performs one atomic state transition. That separation makes failures visible without giving the delivery layer extra authority.

For test suites, isolated passwordless email tests are a useful companion pattern. The important idea is the same: keep an inbox scoped to one run and keep verification state scoped to one attempt.

Model the token as a state transition

Do not model a token as just a random string in a users table. Give each request an identity and an explicit state. A small model might contain:

  • id: an internal attempt ID
  • user_id: the account being verified
  • token_digest: a hash of the presented token
  • status: pending, consumed, expired, or revoked
  • expires_at: the server-side deadline
  • consumed_at: when the token was accepted
  • request_key: the client or workflow idempotency key
  • created_at: when the attempt was created

Store a digest rather than the raw token. The link can carry the secret once, while logs, database dumps, and support queries only see a non-reversible value. The token should also be generated with a cryptographic random source and compared in a way that does not create a second validation path.

The request_key matters when a client retries after a timeout. Without it, one user action can create three pending tokens and three messages. With it, the API can return the original attempt, or intentionally reject a key that is being reused for a different user.

Use PostgreSQL to enforce single use

Application checks alone are not enough under concurrency. Two requests can both read pending before either one writes consumed. Let PostgreSQL protect the transition:

UPDATE email_verification_attempts
SET status = 'consumed', consumed_at = now()
WHERE token_digest = $1
  AND status = 'pending'
  AND expires_at > now()
RETURNING id, user_id;
Enter fullscreen mode Exit fullscreen mode

If the query returns one row, the token was consumed by this request. If it returns no rows, the caller receives a generic invalid-or-expired response. Avoid telling an attacker whether the token existed, was already used, or belonged to another account.

Add a unique constraint for the idempotency boundary as well:

CREATE UNIQUE INDEX verification_request_once
ON email_verification_attempts (user_id, request_key);
Enter fullscreen mode Exit fullscreen mode

The exact key columns depend on the product contract. The principle is stable: the database should reject duplicate work even if two API instances receive the request at nearly the same moment. This make the endpoint safe when a load balancer retries or a mobile client reconnects.

Make retries and expiry observable

Email delivery is asynchronous, so the API should return an attempt ID and a clear status rather than pretending delivery is complete. A worker can claim pending attempts with a short lease, send the message, and record the provider message ID. If the worker dies, the lease expires and another worker can try. A lease is not the same as a token validity period; keep those clocks separate.

The ledger should record safe events such as created, send_started, send_accepted, send_failed, consumed, and expired. Do not store the full URL or email body in ordinary logs. Include a correlation ID so an operator can connect the API request, queue job, and provider response. Deployment correlation IDs show the same operational habit applied to another asynchronous workflow.

When a staging flow needs an external inbox, a temporary email account generator can help keep personal addresses out of test data. Use it only for non-production fixtures, check retention rules, and never put provider credentials or verification tokens in the article logs. Test data such as tempail mail may appear in a fixture or search case, but it is plain input, not a domain to trust.

A good failure response is boring and consistent. The logs is where the detail belongs: attempt ID, request key hash, state, expiry result, provider message ID, and a redacted reason. Keep user-facing responses intentionally narrow.

A review checklist for the REST endpoint

Before shipping the flow, check these properties:

  • Is the raw token absent from database records and normal logs?
  • Can exactly one concurrent request consume a pending token?
  • Does a retry return the existing attempt instead of sending duplicate mail?
  • Are token expiry and worker lease expiry separate values?
  • Is the mailbox treated as transport rather than proof of identity?
  • Can an operator trace one attempt across API, queue, and provider logs?
  • Are expired and consumed rows removed or retained under a documented policy?

The boundary become easier to maintain when these rules are encoded in the schema and repository tests, not only in controller code. Test the race directly with concurrent consumers, test a delayed message after expiry, and test a worker crash after claiming a lease. Those cases is where an apparently simple verification feature usually reveals its real behavior.

The main design payoff is clarity. PostgreSQL owns atomic state, the REST API owns the contract, the worker owns delivery retries, and the mailbox remains an untrusted transport. Once those responsibilities are separated, verification becomes easier to scale and much less mysterious during an incident.

Top comments (0)