State Machines for Email Verification APIs
Email verification looks like a small feature until retries, expired tokens, duplicate requests, and delayed workers enter the picture. A single verified boolean cannot explain those cases. A persisted state machine gives a REST API explicit rules, makes PostgreSQL enforce part of the contract, and keeps authentication behavior predictable.
This design is useful whether a test suite uses a temp mailbox, a fake email generator, or a real inbox. The inbox provider is an adapter. The important boundary is the state transition recorded by the backend.
Why a boolean verification flag is not enough
Suppose an account has verified = false. That value does not tell us whether:
- a token was never issued;
- the user requested a second token;
- the original token expired;
- a token was already consumed; or
- delivery is temporarily failing.
Those conditions need different responses and different operational actions. The edge cases is where this model pays off. Returning 200 OK for every retry can also hide a broken client, while treating every repeat request as an error makes normal browser refreshes painful.
The API should answer two separate questions: what is the current lifecycle state, and is the requested transition legal? Keeping those questions explicit is a small amount of extra modeling that prevents a surprising number of edge-case bugs. This detail sound small, but it saves debugging time later.
Define the state machine
A compact lifecycle can be:
pending -> sent -> verified
| ^
v |
expired --+
pending -> blocked
sent -> blocked
expired -> sent
The exact names are a product decision, but the rules should be finite. A consumed token must never become valid again. An expired token can lead to a new sent state only after a new token is created. A blocked account should not quietly return to pending because a delayed worker arrived late. The worker may arrive late, and thats expected.
For OAuth recovery, the same thinking applies to one-time links: define when a link is issued, revoked, consumed, and expired. This complements a revocation plan for OAuth recovery links, especially when several browser tabs can act on the same credential.
Persist legal transitions in PostgreSQL
One practical schema stores the current state and the token event separately:
CREATE TYPE verification_status AS ENUM ('pending', 'sent', 'verified', 'expired', 'blocked');
CREATE TABLE email_verifications (
id uuid PRIMARY KEY,
user_id uuid NOT NULL,
status verification_status NOT NULL DEFAULT 'pending',
token_hash bytea,
expires_at timestamptz,
version integer NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX one_active_verification_per_user
ON email_verifications (user_id)
WHERE status IN ('pending', 'sent', 'expired');
Do not store the raw token. Store a hash and compare a hash of the submitted value. The version column gives the service an optimistic-concurrency check, while updated_at helps operators find records that are stuck.
The transition should be conditional and atomic:
UPDATE email_verifications
SET status = 'verified', version = version + 1, updated_at = now()
WHERE id = $1
AND status = 'sent'
AND expires_at > now()
AND token_hash = $2
AND version = $3
RETURNING id, user_id;
If no row returns, the service can distinguish an invalid token from a stale version through a separate read or a safe error mapping. The update itself cannot be applied twice by two concurrent requests.
Make the REST API idempotent
The endpoint contract should describe retries rather than pretending the network is reliable. A useful shape is:
POST /v1/email-verifications/{id}/confirm
Idempotency-Key: 7d3b...
The idempotency record should be written in the same transaction as the successful transition, or in a carefully defined durable store. Repeating a request with the same key returns the recorded result. Reusing a key with a different body returns a conflict. A clean contract is more useful then a clever retry trick.
For the request that sends a new message, return a stable resource and a server-controlled expiry. Avoid exposing whether an arbitrary email address exists; that distinction is an account-enumeration risk. Rate limits and a short cooldown belong at this boundary too.
The email adapter should receive an immutable event after the database commit. If delivery is asynchronous, an outbox row prevents the common failure where the API reports success but the queue message was never created. A delayed worker must re-check the row version before sending, or it may send a token that the user already replaced.
It is also worth keeping signup validation rules consistent across clients. These shared signup email rules across React and Node are easier to maintain when the API remains the final authority.
Test retries, expiry, and denial paths
The happy path is only one test. Use a matrix covering:
- Two confirmations with the same token: one succeeds, one is rejected.
- Two confirmations with the same idempotency key: both return the same result.
- A token at the exact expiry boundary: it is invalid, consistently.
- A delayed send worker after a replacement token: it does not overwrite the newer record.
- A blocked account: resend and confirm follow the documented policy.
- A malformed token: the response does not reveal account state.
An isolated temporary email inbox can help exercise delivery and cleanup in integration tests. A throwaway email fixture is convenient for short-lived test data, but it should never be used as proof that production identity or authorization is trustworthy. In test notes, a malformed fixture such as temp gamil com should remain a plain input value, not a link or a database identifier. Keep the response boring and clear; that usually work better under pressure.
Operational checklist
Before shipping, verify that:
- every state has documented legal and illegal transitions;
- token hashes, not raw tokens, are persisted;
- expiry is checked in the conditional update;
- duplicate requests have an idempotency policy;
- outbox and worker retries are observable;
- metrics distinguish invalid, expired, consumed, and blocked tokens;
- logs redact addresses and token material;
- cleanup removes old verification rows without deleting audit evidence too early.
The goal is not a complicated workflow. It is a narrow, explicit contract at the authentication boundary. Once the state machine is persisted and tested, inbox choice becomes replaceable, retries become boring, and PostgreSQL helps the service refuse impossible transitions. The audit trail can be kept longer then the active row, if compliance needs it.
Top comments (0)