DEV Community

kevindev
kevindev

Posted on

Email Verification Needs a Lease-Based API

An implementation guide for preventing duplicate workers, delayed messages, and token races from producing contradictory verification results.

Email verification is usually described as a token problem. In a production REST API, it is more useful to treat it as an ownership problem.

One request creates an attempt. A background worker sends the message. A browser later presents the token. Meanwhile, the client may retry, the worker may time out after sending, and the user may request another email. If no component can say which process owns the current attempt, the system starts making guesses.

The pattern I use for this case is a short-lived lease around each verification attempt. The lease does not replace a token or a queue. It gives the backend an explicit answer to a more practical question: who is allowed to advance this attempt right now?

Why email verification needs ownership

Consider a POST /verification-attempts request that reaches the API twice because the first response was lost. Without an idempotency key, two rows and two messages may be created. Now add a worker that claims the first row, sends the email, and crashes before recording sent. A retry can claim it again.

The user experiences this as duplicate messages or a link that works only sometimes. Support sees a confusing timeline. The database contains several plausible rows, but no clear explanation of which one should win.

My previous notes on designing a verification token inbox focus on the message evidence itself. A lease adds the missing ownership layer: a worker can hold a claim for a bounded time, and another worker can recover the work only after that claim expires.

Define the lease and its states

Keep the verification attempt and its lease fields in one authoritative record, or make the relationship explicit with a separate lease table. A useful attempt model includes:

  • verification_id, user_id, and a token digest;
  • state, such as created, sending, sent, accepted, expired, or revoked;
  • lease_owner and lease_expires_at;
  • idempotency_key for the create request;
  • created_at, updated_at, and accepted_at.

The lease should be short enough to recover a stuck job, but long enough for the worker to finish one provider call. Do not make token expiration and lease expiration the same thing. A worker lease controls processing ownership; a token deadline controls whether a user may verify an account. Mixing those clocks is easy to do, and hard to debug later.

The important part are the transition rules. A worker may move created to sending only when the lease is available. It may renew the lease while doing bounded work. If the provider call times out, the next worker can inspect the attempt and decide whether sending might already have happened. It should not blindly produce a second message.

Make PostgreSQL the arbitration point

Application-level checks are not enough when two workers wake at the same time. Claim the row in a transaction and let PostgreSQL serialize the decision:

UPDATE verification_attempts
SET state = 'sending',
    lease_owner = $1,
    lease_expires_at = now() + interval '30 seconds',
    updated_at = now()
WHERE verification_id = $2
  AND state = 'created'
  AND (lease_expires_at IS NULL OR lease_expires_at < now())
RETURNING verification_id, token_digest, lease_expires_at;
Enter fullscreen mode Exit fullscreen mode

If no row returns, the worker did not acquire the attempt. That is a normal outcome, not necessarily an error. The worker can reload the current state and choose between waiting, recording a provider uncertainty, or abandoning the job.

For acceptance, lock the attempt, check the token digest and user-facing expiration, then update the attempt and user in one transaction. A second click should return a stable result for an already accepted attempt. An expired or revoked attempt should return a generic application error, without revealing whether a submitted token was ever valid.

Design REST endpoints for retries

The create endpoint should accept an idempotency key and return the same verification_id for a replay with the same request meaning. Store a request fingerprint too, so the server can reject a reused key with different input instead of silently changing the operation.

The worker-facing endpoint can be internal, for example:

POST /internal/verification-attempts/{id}/lease
POST /internal/verification-attempts/{id}/lease/renew
POST /internal/verification-attempts/{id}/delivery-result
Enter fullscreen mode Exit fullscreen mode

Each call needs an owner check. A late result from an old worker must not overwrite a newer lease or change an accepted attempt back to sent. This is the same trust-boundary thinking useful for a safe trust boundary for OAuth verification: the message, worker, and browser are inputs, while the database transition is the decision.

Keep test mail inside a bounded workflow

Integration tests should exercise lease expiry and provider uncertainty, not only the happy path. Give each run a correlation ID, use a controlled mailbox, and assert that a retry produces one attempt and one accepted transition.

If a team uses a disposable temporary email address for a short-lived test, the fixture still needs an owner and cleanup deadline. Never put real customer data in that path. A test label may contain strings such as dummy e mail or tem email; those are input values, not special cases that should alter the API state machine.

Useful failure scenarios include:

  • the worker crashes after the provider accepts the message;
  • the lease expires while the provider response is unknown;
  • two workers try to claim one attempt;
  • a user clicks an old token after a newer attempt exists;
  • the acceptance request is retried after its transaction commits.

The test report should show the attempt ID, lease owner, state transitions, and provider correlation ID. It makes failures much more actionable then a screenshot of an inbox.

Operational checklist

Before shipping a lease-based verification flow, verify that:

  • create requests are idempotent;
  • lease claims are conditional database updates;
  • lease and token deadlines are separate;
  • workers have bounded retries and a clear uncertainty state;
  • late provider results cannot overwrite newer state;
  • raw tokens and full verification URLs stay out of logs;
  • metrics distinguish claim conflicts, lease expirations, delivery uncertainty, and user acceptance;
  • cleanup removes old attempts and test mail on a known schedule.

A lease does not make email delivery reliable. It makes the unreliable parts visible and gives the REST API a consistent owner for each decision. That is enough to turn duplicate sends and delayed callbacks from mysterious incidents into states the backend can explain.

Top comments (0)