Email verification looks like a small feature until a client retries a request, a worker crashes after sending, or a user opens an old link. A verification endpoint that only creates a token and sends a message will eventually produce duplicate emails, confusing states, or tokens that work after they should be dead.
The useful design question is not “how do I send an email?” It is “what result should a retry observe?” This article describes a retry-safe REST API using PostgreSQL as the state owner and Node.js as the application boundary. The model works for a temporary email address or a normal mailbox.
Why verification retries become duplicate work
There are several independent retries in this flow:
- A browser retries the HTTP request after a timeout.
- An API gateway retries an upstream connection.
- A worker retries a delivery job after a process crash.
- A user clicks the same verification link more than once.
If each retry creates a new row and a new message, the system cannot tell whether it is continuing one operation or starting another. A disposable email inbox makes this pain more visible because test runs often repeat the same signup scenario quickly.
The fix is to give each logical request an idempotency key and each verification attempt a durable state. Freeze inputs before an automated run, just as freezing inputs before an automated run prevents a changing command from producing an unreviewable result.
Define the API contract first
For POST /verification-requests, require an Idempotency-Key header. The request body can contain the user identifier and destination address, but the key defines the client’s logical operation.
The first response might be:
{
"request_id": "vr_01J...",
"status": "queued",
"expires_at": "2026-12-01T12:00:00Z"
}
A repeated request with the same key should return the stored response, not create another token. A repeated key with a different body should return 409 Conflict; silently changing the destination is a security bug.
For POST /verification-requests/{id}/confirm, make the result explicit: confirmed, already_confirmed, expired, or invalid. Explicit email decision states are easier for clients to render than a boolean hidden behind a generic error.
Make PostgreSQL the state owner
The database should own uniqueness, expiration, and the transition from pending to confirmed. A useful table has these fields:
create table verification_requests (
id text primary key,
user_id bigint not null,
destination text not null,
idempotency_key text not null unique,
token_digest bytea not null,
status text not null check (status in ('pending', 'confirmed', 'expired')),
expires_at timestamptz not null,
created_at timestamptz not null default now(),
confirmed_at timestamptz
);
Do not store the raw verification token. Store a digest and compare a digest of the presented value. The confirmation transaction should lock the row, check the status and expiry, then update it. If two requests arrive together, only one can perform the pending-to-confirmed transition.
The idempotency record and verification row should be created in one transaction. Otherwise, a process failure between those writes can leave a key pointing at nothing. That gap are hard to diagnose once traffic increases.
Publish delivery work safely
Sending inside the database transaction is tempting, but it holds a connection while an external service responds. Instead, write an outbox row in the same transaction as the verification request. A worker claims pending rows with a short lease, sends the message, and records the provider result.
The outbox operation is at-least-once, so the worker must assume it can run twice. Include the verification request ID in provider metadata when supported. If the provider cannot deduplicate, keep the retry policy conservative and expose delivery status to operators.
A worker should record claimed_at, attempt_count, last_error, and next_attempt_at. If a process dies while holding a lease, another worker can reclaim the row after the lease expires. The lease is not a lock forever; it is a bounded promise to work.
Handle temporary email addresses as untrusted input
A temporary email address is still user-controlled input. Validate syntax, normalize the domain according to your policy, and never treat a successful SMTP handoff as proof that a human owns the account. Do not put the full address, token, or message body into ordinary logs.
Malformed values also appear in support tickets and test fixtures. Someone may write tamp mail com when describing a bad address. Keep such text out of canonical keyword fields and treat it as an input-quality problem, not a destination to guess.
If your product blocks disposable email, do that as a separate policy decision. Verification state should remain understandable even when policy rejects a destination. The endpoint are easier to maintain when validation, identity proof, and delivery are separate decisions.
A small Node.js implementation shape
The handler should be thin: parse the request, call a service, and map domain outcomes to HTTP responses.
async function createVerification(req, res) {
const key = req.get('Idempotency-Key');
if (!key) return res.status(400).json({ error: 'missing_idempotency_key' });
const result = await verificationService.create({
userId: req.user.id,
destination: req.body.email,
idempotencyKey: key,
});
return res.status(result.replayed ? 200 : 202).json(result.response);
}
The service owns the PostgreSQL transaction and outbox write. It should return a replay marker so metrics distinguish new work from a safe retry. In Node.js, pass cancellation signals to database and provider clients where possible; otherwise a timed-out request may keep doing work after the caller has gone.
Operational checklist
- Enforce a unique idempotency key per operation scope.
- Store token digests, never raw tokens.
- Make expiration part of the confirmation transaction.
- Use an outbox for delivery and a reclaimable worker lease.
- Record replay count, confirmation latency, and delivery failures.
- Redact addresses and tokens from logs.
- Test duplicate requests, concurrent confirmation, expired tokens, and worker crashes.
- Decide whether a temporary email address is allowed as policy, not as an accidental side effect.
Small details matter here. A retry-safe contract is less flashy than a new queue, but it saves support time and keeps a REST API predictable under network failure.
Common questions
Should every retry send a new verification email?
No. A retry with the same idempotency key should replay the original response. Offer a separate, rate-limited resend operation when a new message is genuinely needed.
Should a confirmed token be accepted again?
Usually return already_confirmed and keep the operation harmless. Clients can treat that as success while the server preserves a clear audit trail.
Is PostgreSQL enough for high traffic?
Often yes when transactions are short, indexes match the access paths, and workers use bounded leases. Measure contention before adding another state store; extra systems make recovery paths more complex.
Top comments (0)