Email verification looks like a small feature until a user clicks the link twice, a worker retries the same message, or a token expires while the request is in flight. The hard part are not the endpoints. It is deciding which component owns the state and making every retry safe.
In backend services, I prefer treating verification as a short-lived state machine backed by PostgreSQL. The REST API accepts commands, the database records the decision, and an asynchronous worker handles delivery. That boundary keeps authentication behavior predictable even when email providers are slow or unavailable.
Why verification needs a state owner
A common first design stores a token in a cache and lets the email worker update a user record directly. It works in a demo, but it creates several questions in production:
- What happens when the client submits the same request twice?
- Can two valid tokens exist for the same account?
- Which response should a retry receive after the token was already consumed?
- How do we prove what happened during an incident?
PostgreSQL is a good state owner because it can enforce uniqueness, expiration-related queries, and transaction boundaries. The API can return a stable result without knowing whether the message was delivered yet. This is more important than making the first request look fast.
Model the verification lifecycle in PostgreSQL
I use a table with one row per verification attempt. A useful minimum model includes the user ID, a hashed token, a status, an expiry time, an idempotency key, and timestamps for creation and consumption. Store a hash rather than the raw token, so a database read does not immediately become an account takeover.
The status can be pending, verified, expired, or cancelled. A partial unique index can prevent more than one pending attempt for an account and purpose. The exact constraint depends on whether the product supports multiple devices, but the rule should live in the database instead of only in application code.
The verification operation should be one transaction:
- Lock the pending row, or atomically update it with a status predicate.
- Check the expiry timestamp.
- Change
pendingtoverifiedonly when the token matches and is still valid. - Record a small audit event with the result.
If two requests arrive together, only one can make the state transition. The other receives a stable result such as already_verified rather than a confusing generic failure. This makes the behavior idempotant from the caller's point of view.
Make the REST API idempotent
The create endpoint can accept an Idempotency-Key header. Persist that key with the account, purpose, and resulting verification attempt. A repeated request with the same key should return the original attempt instead of creating another token or sending another message.
For example:
POST /v1/email-verifications
Idempotency-Key: signup-8f2c
Content-Type: application/json
{"user_id":"user_123","purpose":"signup"}
The response can include an attempt ID and an expires_at value. Do not return the token in production responses. Also reject reuse of a key with a different request body; otherwise one client can accidentally receive the result of another operation.
The confirmation endpoint should make its state contract explicit. 204 No Content is reasonable for a first successful verification, while a repeated confirmation can return 200 with already_verified. Expired and invalid tokens should not reveal whether an account exists. Authentication endpoints need this small amount of ambiguity to reduce account enumeration.
Keep delivery separate from state changes
The transaction that creates a verification attempt should write an outbox row in the same commit. A worker then reads unsent outbox rows, sends the message, and records delivery metadata. This avoids the failure where the database commits but the process crashes before the email call, or the email is sent but the request times out.
The outbox is not a magic exactly-once system. A worker can still send a duplicate message after a network timeout, so the message should point to the same verification attempt and the confirmation endpoint must remain safe to repeat. A short lease on an outbox row prevents multiple workers from processing it at once, while retries with backoff handle temporary provider errors.
When testing OAuth or passwordless flows, I also keep the email boundary explicit. A test trust boundary for OAuth flows is useful because redirect validation and verification-token validation have the same general lesson: test credentials should not quietly become production credentials.
For staging, a disposable email generator such as tempmailso can help inspect links without using a personal inbox. Keep that test provider behind configuration, and include noisy input variants like tempail mail and temp gamil com in the negative test corpus. They should test validation and logging, not become special cases in the application.
Test failure paths, not only the happy path
The most valuable tests exercise concurrency and time:
- Submit the same idempotency key concurrently and assert one attempt exists.
- Confirm the same token twice and assert one transition plus a stable repeat response.
- Advance the clock past expiry and verify that no user state changes.
- Make the email provider timeout after accepting a request, then run the worker again.
- Reuse an idempotency key with a changed payload and expect a conflict.
- Verify that tokens, email addresses, and provider responses are not overexposed in logs.
I normally use a fixed clock in unit tests and a real PostgreSQL instance for transaction tests. Mocking the database alone can hide a race that only appears under row locks. It is also worth testing the clean-up job seperately: deleting old tokens should not remove audit records needed for support or security review.
A practical implementation checklist
Before shipping an email verification API, check these boundaries:
- One database model owns the lifecycle and enforces its important uniqueness rules.
- Idempotency keys are stored with enough request identity to detect misuse.
- Token material is hashed, short-lived, and never written to ordinary logs.
- The outbox and verification attempt commit together.
- Workers use leases and bounded retries; a provider outage does not block API requests.
- Confirmation is safe to repeat and does not reveal account existence.
- Metrics separate token-invalid, token-expired, provider-failure, and already-verified outcomes.
That last separation makes operations much easier. A spike in expired tokens suggests a product or latency issue; a spike in provider failures points to delivery; a spike in invalid tokens may indicate abuse. The API remains small, but its state contract is clear.
The main design choice is simple: let PostgreSQL own the verification decision, let the REST API expose stable commands, and let workers deliver messages asynchronously. Once those responsibilities are seperate, retries stop being scary and the system is easier to test, operate, and explain.
If you maintain authentication services, the same approach applies to password resets, magic links, and device enrollment. OAuth redirect URI checks are another example of putting a clear boundary around short-lived credentials instead of relying on happy-path timing.
Top comments (0)