Email verification is often treated as a single API call: create a token, call a provider, and tell the user to check the inbox. That model breaks when the provider slows down or returns intermittent errors. A request timeout can turn into a retry storm, duplicate messages, and a registration flow that is impossible to explain.
A circuit breaker gives the delivery dependency an explicit failure policy. It does not make an email provider reliable. It keeps provider trouble from becoming application-wide trouble, while preserving enough state to resume delivery safely.
This pattern is useful whether the recipient uses a normal mailbox or a use and throw email for a short-lived workflow.
Why verification email delivery needs a circuit breaker
A circuit breaker separates provider rejection, lost responses, and slow responses into explicit states:
- Closed: requests flow normally and failures are counted.
- Open: new delivery attempts fail fast for a cooldown period.
- Half-open: one or a few probe attempts test whether the dependency recovered.
The user-facing API should not expose provider details. Return a documented status such as 202 Accepted for queued work or 503 when the service cannot accept more work.
Model delivery states separately from account state
Do not store “email sent” as a boolean on the user row. Account activation and delivery are related, but they have different lifecycles. A verification request can be pending while the circuit is open, and a previously delivered message can still be valid after a later resend fails.
A compact delivery record might contain:
CREATE TABLE verification_deliveries (
id uuid PRIMARY KEY,
user_id uuid NOT NULL,
request_key text NOT NULL UNIQUE,
token_digest text NOT NULL,
status text NOT NULL,
attempts integer NOT NULL DEFAULT 0,
next_attempt_at timestamptz,
last_error_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
The request_key is an idempotency boundary. If the client retries after losing a response, the server can return the existing delivery instead of creating a second token and job. Keep the raw token out of this table; store a digest.
Draw a trust boundary map for email fixtures first so log-safe metadata is clear.
Implement bounded retries in a Node.js worker
The worker needs two limits: a maximum number of attempts for one delivery and a maximum time for the circuit to remain open. Exponential backoff with jitter prevents every worker from retrying on the same second.
function nextDelay(attempt, random = Math.random()) {
const base = Math.min(30_000, 1_000 * 2 ** attempt);
return Math.floor(base * (0.75 + random * 0.5));
}
function isRetryable(error) {
return error.code === "ETIMEDOUT" ||
error.code === "PROVIDER_5XX" ||
error.code === "RATE_LIMITED";
}
On a retryable error, increment attempts, set next_attempt_at, and release the job. On a permanent error, mark the delivery as failed and stop. On a timeout after the provider may have accepted the request, do not blindly create a new token; first use the request key or provider idempotency key to make the next attempt replay-safe.
The circuit can be process-local in a small service, but a multi-instance deployment needs shared state. Otherwise one instance can stop sending while the others continue. Use a short lease for the half-open probe so multiple workers cannot all declare recovery at once.
Persist attempts and cooldowns in PostgreSQL
PostgreSQL is useful here because the state transition can be made atomic. A worker should claim a due row and update its attempt metadata in one transaction, rather than reading a row and hoping another worker does not claim it first.
WITH candidate AS (
SELECT id
FROM verification_deliveries
WHERE status = 'pending'
AND (next_attempt_at IS NULL OR next_attempt_at <= now())
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE verification_deliveries AS d
SET status = 'sending', updated_at = now()
FROM candidate
WHERE d.id = candidate.id
RETURNING d.*;
When the breaker is open, the worker should avoid claiming unlimited rows and immediately putting them back. Either pause polling for the cooldown or claim only a small batch for visibility. This keeps the queue honest and avoids a busy loop that looks like useful work in metrics.
Record counters for open transitions, probes, permanent failures, retries, and delivery latency. Do not log tokens, complete message bodies, or recipient addresses by default. A label like tem email or temp mailid does not make data safe; contents and retention rules matter more than the fixture name.
Testing the failure path
Unit tests can cover the state machine, but integration tests should exercise the boundary between the API, queue, database, and provider adapter. Test at least these cases:
- a timeout after the provider accepted the request
- repeated
429responses followed by recovery - two workers claiming the same delivery
- a client retry with the same idempotency key
- a permanent rejection that must not be retried
- a half-open probe racing with another worker
Run these scenarios with a fake provider that controls response timing. Keep the test inbox isolated by build and make the provider response part of the evidence. Teams working in cloud pipelines can review guidance on isolated email tests in Docker CI.
Assert on state transitions and request counts, not only on the final email; one inbox message can hide multiple provider calls.
Q&A: common circuit-breaker decisions
Should an open circuit reject every verification request?
Usually it should accept a bounded request if the queue has capacity, then report that delivery is delayed. Reject when more work would breach a queue or retention limit.
A practical implementation checklist
- Give each logical verification request an idempotency key.
- Store delivery state separately from account activation.
- Bound attempts, queue age, and provider timeouts.
- Add jittered backoff and a shared circuit state for multiple instances.
- Use a lease for half-open probes.
- Claim PostgreSQL jobs with row locking and
SKIP LOCKED. - Test lost responses, duplicate workers, rate limits, and recovery.
- Redact tokens and personal data before logs or CI artifacts are created.
A circuit breaker is a small state machine, but it changes the reliability contract of the whole verification flow. Once delivery has explicit states, bounded work, and replay-safe requests, provider failures become a manageable system condition instead of a mystery scattered across API logs and user reports.
Top comments (0)