Email verification looks like a small feature until the provider times out after accepting a message, a worker crashes between two writes, or a user clicks “send again” several times. At that point, the real problem is not generating a token. It is making delivery attempts safe to repeat.
The pattern I prefer is an idempotent verification job backed by PostgreSQL. The API records one verification intent, the outbox records one logical delivery, and workers can retry that delivery without creating a new token or an uncontrolled number of messages. The model is simple enough to inspect during an incident, which is important when the failure are intermittent.
This is also where the choice of test inbox matters. A throwaway email address can be useful for a controlled staging check, but it should never become the consistency mechanism for production authentication.
Why idempotency belongs in the data model
An HTTP retry is normal. Mobile clients lose connectivity, reverse proxies retry upstream requests, and users refresh a page. If POST /verifications creates a token every time it is received, one logical action can produce several active tokens.
Give the request a stable idempotency key, or derive a stable verification identity from the account and purpose. Then enforce the rule in the database. Application code can check for an existing row first, but only a unique constraint protects the rule when two requests arrive together.
For example, a verification intent might have a unique key on (user_id, purpose, active_window). The exact window depends on the product. The important decision is that the database knows what “same request” means. Otherwise, duplicate prevention is just a hope in a busy system.
Separate verification intent from delivery attempts
Keep the token lifecycle and the email lifecycle in separate records. A verification_intent row can contain:
-
id,user_id,purpose, and a hash of the token -
expires_at,consumed_at, andcreated_at - an idempotency key or request correlation ID
An email_outbox row can contain:
-
verification_idwith a uniqueness rule for the logical message -
status,attempts,next_attempt_at, andlast_error -
lease_owner,lease_until, andprovider_message_id
This separation prevents a delivery retry from silently minting a new token. It also makes audit queries clearer: “Was the token consumed?” and “Did the provider accept the message?” are different questions.
When reviewing passwordless flows, I also keep inbox boundaries for passwordless OTP explicit. Test messages, user messages, and recovery messages should not share an accidental routing rule.
Claim jobs safely in PostgreSQL
Several workers can poll the same table if claiming is done inside a short transaction. FOR UPDATE SKIP LOCKED lets each worker skip rows already being claimed:
WITH next_jobs AS ( SELECT id FROM email_outbox WHERE status = 'pending' AND next_attempt_at <= now() AND (lease_until IS NULL OR lease_until < now()) ORDER BY next_attempt_at, id FOR UPDATE SKIP LOCKED LIMIT 20 ) UPDATE email_outbox AS job SET status = 'sending', lease_owner = $1, lease_until = now() + interval '90 seconds', attempts = attempts + 1 FROM next_jobs WHERE job.id = next_jobs.id RETURNING job.id, job.verification_id, job.attempts; The transaction should commit before the worker calls the provider. Holding database locks across a network request makes slow provider behavior everybody's problem. A lease gives the worker temporary ownership, and an expired lease makes the row available after a crash.
The lease duration needs a little tuning. It should be longer than the normal provider call plus a margin, but short enough for recovery. A heartbeat can extend it for a genuinely long operation; it should not hide a stuck worker forever.
Make retries and provider ambiguity explicit
Provider timeouts create an ambiguous result. The provider may have accepted the message even though the client did not receive a response. No generic REST API can reliably undo that after the connection is lost.
Treat the attempt as a state transition with an evidence trail. Store the provider message ID when available, classify errors as retryable or terminal, and use exponential backoff with a maximum attempt count. On a timeout, retrying is usually safer than losing the message, but the product should tolerate a rare duplicate.
The worker should also verify its lease before writing a result. If another worker reclaimed an expired job, the old worker must not mark that job as sent. An ownership token or lease version in the UPDATE predicate makes stale writes fail cleanly.
For browser and integration tests, keep the same contract visible at the UI boundary; these email checks without UI drift are easier to debug when job IDs and correlation IDs survive the full flow. A dummy e mail in a fixture is fine, but its lifecycle still need an owner.
Keep the REST API contract stable
The API should return a response that describes the verification intent, not the provider's uncertain state. A practical response can include a verification ID, an expiry time, and a status such as queued.
Do not return “email sent” merely because the outbox insert succeeded. Do not make clients poll provider-specific IDs either. If the product needs status, expose a small state vocabulary such as queued, delivered, expired, and consumed, with documented retry behavior.
The resend endpoint should reuse the same intent when policy allows it, or explicitly expire the old intent before creating a replacement. Rate limits belong at both the account and network level. They protect the provider relationship and reduce the chance that a user turns a temporary error into a message storm.
Operational checklist
Before shipping, I check the following:
- A unique database constraint prevents duplicate logical deliveries.
- Claiming uses a short transaction and an expiring lease.
- Stale workers cannot overwrite a newer owner.
- Retryable and terminal provider errors are separated.
- Attempt counts, lease expiry, and last errors are observable.
- Tokens and email addresses are not printed in ordinary logs.
- Expired intents and dead-letter jobs have a cleanup policy.
The metric I watch first is not only delivery success. It is the age of the oldest pending job, split by retry count. A rising age with normal request volume points to worker capacity or provider latency. A rising retry count with low queue depth suggests a contract or credential problem.
Questions engineers usually ask
Should every resend create a new token?
Not necessarily. Reuse the active intent when the security policy permits it, and create a new one only after the previous intent is expired or explicitly revoked. The decision should be visible in the state model.
Is a PostgreSQL outbox enough for high volume?
It can be a good starting point, especially when the verification write and the outbox insert must be atomic. At higher volume, partitioning, a dedicated queue, or provider webhooks may be appropriate. The idempotency and ownership rules still apply after the transport changes.
Can a free disposable email test prove production reliability?
No. It can prove that a staging flow renders and receives a message. Reliability comes from database constraints, bounded retries, lease behavior, and observable failure states. Even a misspelled test value like “tamp mail com” should be treated as fixture input, never as an operational signal.
Idempotency is less about making email perfect than making failure understandable. Once the verification intent, delivery job, and worker lease have distinct responsibilities, retries become a controlled backend behavior instead of a source of mystery.
