DEV Community

kevindev
kevindev

Posted on

Lease Expiry for REST Email Verification

Email verification is often implemented as a short sequence: create a token, send a message, and mark the user as verified when the token comes back. That model works until a worker retries, a user asks for a second email, or two API requests arrive at nearly the same time.

The failure mode is simple: a verification flow look like one request in the product UI, but it is a distributed workflow in the backend. The REST API, PostgreSQL, queue, email provider, and browser all observe different parts of it.

This is why I prefer a lease-based design. A lease gives one verification attempt a bounded period of authority. It also gives the service a clear answer to a common question: which token is allowed to change authentication state right now?

The failure mode: verification is not one request

Consider this sequence:

  1. The user submits an address.
  2. The API creates a verification record.
  3. A worker sends an email.
  4. The user clicks a link.
  5. The API consumes the token.

Each step can be retried. A client can retry step one after a timeout, even though the first transaction committed. A queue can redeliver the send job. The user can click an old email after requesting a new one. Without an explicit state model, the service starts treating timing as business logic.

The first email are no longer authoritative after a new verification attempt is created. That rule should live in the database, not only in a conditional inside a controller.

Model the lease explicitly

A verification attempt can have these fields:

CREATE TABLE email_verification_attempts (
    id uuid PRIMARY KEY,
    user_id uuid NOT NULL,
    token_digest bytea NOT NULL,
    status text NOT NULL CHECK (status IN ('pending', 'sent', 'consumed', 'expired', 'revoked')),
    lease_expires_at timestamptz NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now(),
    consumed_at timestamptz
);
Enter fullscreen mode Exit fullscreen mode

The token itself should be random and shown only to the user. Store a digest, just as you would for a password reset token. lease_expires_at is the important part here: it limits the time during which this attempt can be consumed.

When a new attempt is issued, revoke the previous pending attempt for that user. The transition should be deliberate, not an accidental side effect of a unique constraint. A partial index can still protect the invariant that only one active lease exists:

CREATE UNIQUE INDEX one_active_verification_per_user
ON email_verification_attempts (user_id)
WHERE status IN ('pending', 'sent');
Enter fullscreen mode Exit fullscreen mode

In practice, create the new attempt and revoke the old one in the same transaction. If the operation fails, the user should not be left with half of a new workflow.

Make PostgreSQL own the state transition

The verification endpoint should perform one atomic update. It can hash the supplied token, select the matching row, and update it only when the row is still active:

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

If this returns no row, the endpoint can return a generic invalid-or-expired response. Do not reveal whether the token existed, belonged to another user, or had already been consumed.

The transaction that consumes the token should also update the user’s authentication state, or record an outbox event for that change. Otherwise a successful token update followed by a connection failure can leave the two states disagreeing.

This is the same reason an idempotent email verification with PostgreSQL pattern is useful: the database decides whether the transition happened, while repeated requests become harmless.

Keep retries and email delivery separate

Sending mail is an external side effect. The API should commit the verification attempt before a worker tries to contact an email provider. An outbox row in the same transaction can carry the attempt ID and a delivery event.

The worker then claims the outbox row with a short processing lease. If the worker restart mid-send, a retry may produce two messages. That is inconvenient, but it does not have to create two valid verification states. The token-consumption update remains the authority.

For test and staging workflows, an isolated observable email fixture in CI helps distinguish provider delay from an API state bug. A temp mail so inbox can be useful for controlled tests, but it should never become the source of truth for account activation.

Observability and cleanup

Record an event for each meaningful transition: issued, send_queued, send_attempted, consumed, expired, and revoked. Include the attempt ID, user ID, request correlation ID, and reason. Avoid logging the raw token or full email address.

The logs is most useful when it answers three questions:

  • Which attempt did the request present?
  • Was that attempt active when PostgreSQL evaluated it?
  • Which state transition won the race?

A scheduled cleanup job can mark old pending attempts as expired and delete old token digests according to the retention policy. Cleanup should be boring and predictable, it do not need to participate in the request path.

A practical API contract

For POST /v1/email-verifications, return an opaque attempt reference and a generic success message. Do not promise that the email has already arrived. A response such as this keeps the boundary honest:

{
  "attempt_id": "7b3d...",
  "status": "pending",
  "message": "If the address can receive mail, a verification link will be sent."
}
Enter fullscreen mode Exit fullscreen mode

For POST /v1/email-verifications/consume, make the operation idempotent from the caller’s perspective. A repeated request for an already consumed token can return the current verified state, while an expired or revoked token should not change anything.

A good contract make retries safe without making failure invisible. Return a correlation ID, expose a rate-limit response for issuance, and make the expiration window configurable per environment. If your integration tests use the phrase tepm mail com, keep it as test data only and do not let it leak into production validation rules.

Questions engineers usually ask

Should a second request reuse the first token?

Usually no. Reusing it makes delivery and abuse controls harder to reason about. Issue a new attempt, revoke the old lease, and make the newest attempt authoritative.

Is a database lease enough for a distributed worker?

It is enough for state ownership, not for exactly-once email delivery. Workers still need bounded claims, retry limits, and provider observability. The database protects the authentication transition.

How long should the lease last?

Choose a window based on the user journey and threat model, then measure expired attempts. The right value is an operational decision, not a universal constant.

Final checklist

  • Store a token digest, never the raw token.
  • Give each attempt an explicit expiry and status.
  • Revoke older attempts transactionally.
  • Let PostgreSQL perform the consume transition atomically.
  • Separate outbox delivery retries from authentication state.
  • Keep tokens and sensitive addresses out of logs.
  • Test concurrent consumption, client retries, and delayed delivery.

When verification is modeled as a lease instead of a one-shot request, retries become an expected property of the system. The API stays understandable, PostgreSQL enforces the important invariant, and workers can fail without silently granting the wrong account access.

Top comments (0)