DEV Community

kevindev
kevindev

Posted on

Transactional Outbox for Email Verification APIs

Email verification looks like a two-step feature: create a user, then send a message. In a real backend, it is a distributed workflow. The database transaction can commit while the mail provider is unavailable, or a worker can send the same message twice after a timeout.

A transactional outbox gives the workflow a durable handoff. The API records the verification state and the email command in one PostgreSQL transaction. A separate relay delivers the command and records the result. This keeps the REST API responsive while making failures visible and recoverable.

The delivery problem starts inside the database transaction

Consider an endpoint such as POST /v1/email-verifications. It may need to create a token, associate it with a user, and request an email. If the handler sends email before committing the transaction, the message can point at data that never commits. If it commits first and sends afterward, a process crash leaves a user waiting forever.

Use a clear ownership boundary:

  1. The API owns verification state.
  2. PostgreSQL owns the atomic change to that state.
  3. The outbox owns the request to deliver a message.
  4. A relay owns communication with the provider.

That boundary is easier to reason about than a request handler doing all four jobs. It gives operations a record of what should happen, even when delivery status are temporarily unknown.

Separate verification state from email delivery

The verification record should answer whether a token is valid. It should not depend on whether the last provider request returned a response. A simple model might contain:

CREATE TABLE email_verifications (
  id uuid PRIMARY KEY,
  user_id uuid NOT NULL,
  token_hash bytea NOT NULL,
  expires_at timestamptz NOT NULL,
  consumed_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE email_outbox (
  id uuid PRIMARY KEY,
  verification_id uuid NOT NULL,
  event_key text NOT NULL UNIQUE,
  payload jsonb NOT NULL,
  available_at timestamptz NOT NULL DEFAULT now(),
  sent_at timestamptz,
  attempts integer NOT NULL DEFAULT 0,
  last_error text
);
Enter fullscreen mode Exit fullscreen mode

The API insert both rows in one transaction. The event_key can be derived from the verification ID and message purpose, so a retry of the request does not create a second logical email. The outbox rows is a command, not proof that a message was delivered.

For links that grant access to a flow, the token should be stored as a hash and consumed with a conditional update. A tenant-bound magic link for SaaS invites shows why the token's scope matters: the recipient, tenant, and action should not be left implicit.

Use an outbox row as the handoff contract

The relay claim available rows in small batches. PostgreSQL can support this with FOR UPDATE SKIP LOCKED, or the application can use a lease column with an expiry time. The important detail is that claiming a row is not the same as marking it sent.

The relay then calls the provider with a provider-side idempotency key when that feature exists. After a successful response, it sets sent_at. If the request times out, it increments attempts, stores a safe error summary, and schedules a later attempt. This makes retries boring, which is a good thing.

There is still a small uncertainty window: the provider may accept a message and the relay may crash before recording sent_at. Provider idempotency, a stable event key, or a downstream deduplication rule is needed to handle that case. An outbox does not create exactly-once delivery by itself; it creates a durable and inspectable at-least-once process.

Make the REST API retry-safe

Clients and load balancers retry requests for ordinary reasons. The endpoint should accept an idempotency key, or derive a safe request identity from the user and verification purpose. A repeated request can then return the existing verification record without issuing a new token each time.

The verification endpoint should make the state transition conditional:

UPDATE email_verifications
SET consumed_at = now()
WHERE id = $1
  AND token_hash = $2
  AND consumed_at IS NULL
  AND expires_at > now();
Enter fullscreen mode Exit fullscreen mode

Only one transaction should be able to change an unused token to consumed. Email delivery can be duplicated in a rare provider failure, but successful verification must not be duplicated. A trust boundary for OAuth test tokens is a useful related reminder: test inboxes and message links are inputs to authentication, not authorities that define it.

Relay, observe, and recover without double verification

Track the outbox lifecycle with fields that support action: available, leased, sent, failed, and dead-lettered. Keep raw tokens, full message bodies, and provider credentials out of logs. Record a verification ID, event key, attempt count, and a redacted provider response instead.

When a worker crash happens after send but before acknowledgement, the next worker should retry using the same event key. Alert on age and repeated failures, not only on process health. A queue that is technically running can still be quietly stuck.

For manual staging checks, a disposable temporary email inbox can be useful for inspecting a non-production message, but never send real credentials or customer data there. Seeded test data sometimes contains strings like tamp mail com; treat them as ordinary input and do not infer trust from the address.

A practical implementation checklist

  • Insert verification state and the outbox command in one PostgreSQL transaction.
  • Give each logical message a stable, unique event key.
  • Make token consumption conditional and single-use.
  • Lease work with an expiry so a dead worker does not hold it forever.
  • Use provider idempotency when available, while still designing for duplicates.
  • Keep retries bounded and move persistent failures to a reviewable dead-letter state.
  • Expose delivery age, attempts, and last failure without exposing secrets.
  • Test the crash windows: before commit, after commit, after provider acceptance, and before acknowledgement.

Questions worth asking before shipping

Does the outbox guarantee one email? No. It guarantees that the request is durable. Exactly-once delivery requires cooperation from the provider or a deduplicating boundary.

Can the API wait for the email provider? It can, but that couples user-facing latency and availability to a downstream service. The outbox lets the API acknowledge durable work instead.

What should a user see when delivery is delayed? Return a stable verification state and allow a controlled resend. A resend should create a new event only when policy allows it, not on every network retry.

The design is small, but the tradeoff is clear: PostgreSQL commits the user-visible state, the outbox records the delivery intent, and the relay handles an unreliable boundary. That separation makes email verification easier to retry, audit, and maintain as the service grows.

Top comments (0)