Build idempotent double opt-in signup

By

Tagged: Database

Use a conditional SQL upsert to prevent duplicate subscribers, limit confirmation resends, and recover immediately after failed email delivery.

When someone submits your waitlist form twice, you shouldn’t end up with two subscribers in the database or send two confirmation emails. At the same time, if that first email failed, submitting the form again should let them retry.

Handling both comes down to making signups idempotent while pairing that with a resend policy for cooldowns and delivery failures.

Enforce uniqueness in the database

Start by giving the table a case-insensitive email column and a unique index so each email can only appear once per list:

CREATE TABLE subscribers (
  id TEXT PRIMARY KEY,
  list_id TEXT NOT NULL,
  email TEXT NOT NULL COLLATE NOCASE,
  status TEXT NOT NULL DEFAULT 'pending'
    CHECK (status IN ('pending', 'confirmed')),
  consent_at INTEGER NOT NULL,
  consent_version TEXT NOT NULL,
  confirmation_token_hash TEXT,
  confirmation_expires_at INTEGER,
  confirmed_at INTEGER
);

CREATE UNIQUE INDEX subscribers_list_email_idx
ON subscribers (list_id, email);

Checking for an existing row in your application code isn’t enough on its own. Two requests that arrive together can both check for a missing row, see nothing there, and both try to insert. Let the database own uniqueness so that race can’t create duplicates.

You should still normalize email addresses to lowercase before inserting them. Adding COLLATE NOCASE gives you a backup layer at the schema level so Person@example.com and person@example.com can’t end up as two separate rows.

Use an upsert

To handle new signups and eligible resends in one query, insert a pending subscriber with an upsert:

INSERT INTO subscribers (
  id,
  list_id,
  email,
  status,
  consent_at,
  consent_version,
  confirmation_token_hash,
  confirmation_expires_at
) VALUES (?, ?, ?, 'pending', unixepoch(), ?, ?, ?)
ON CONFLICT (list_id, email) DO UPDATE SET
  consent_at = excluded.consent_at,
  consent_version = excluded.consent_version,
  confirmation_token_hash = excluded.confirmation_token_hash,
  confirmation_expires_at = excluded.confirmation_expires_at
WHERE subscribers.status = 'pending'
  AND (
    subscribers.confirmation_expires_at IS NULL
    OR subscribers.confirmation_expires_at
       <= excluded.confirmation_expires_at - 600
  )
RETURNING id, status, confirmation_token_hash;

Store confirmation_expires_at as Unix seconds so the subtraction stays plain integer math. When this runs, it either inserts a new subscriber or rotates the token for a pending one whose cooldown has passed. If the subscriber is already confirmed, or still inside the cooldown window, the query doesn’t return a row.

Rotate only after the cooldown

Suppose every new confirmation token expires in 24 hours. You calculate the incoming expiry like this:

now + 24 hours

For the ten-minute cooldown, calculate the timestamp for ten minutes ago:

incoming expiry - 10 minutes

Because that condition sits inside the ON CONFLICT clause, consent, token hash, and expiry all follow the same rule and update together. A confirmed subscriber is never updated.

Decide whether to send

Don’t call your email provider right after the upsert. If the process crashes between the two steps, you can rotate the token without ever sending the email, or send the email without recording what happened.

Instead, create one row per delivery attempt along with an outbox row for work that still needs to reach the provider:

CREATE TABLE email_deliveries (
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
  id TEXT NOT NULL UNIQUE,
  subscriber_id TEXT NOT NULL,
  operation_key TEXT NOT NULL UNIQUE,
  retry_of_delivery_id TEXT,
  status TEXT NOT NULL,
  created_at INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE INDEX email_deliveries_subscriber_sequence_idx
ON email_deliveries (subscriber_id, sequence DESC);

CREATE UNIQUE INDEX email_deliveries_retry_idx
ON email_deliveries (retry_of_delivery_id)
WHERE retry_of_delivery_id IS NOT NULL;

CREATE TABLE email_outbox (
  id TEXT PRIMARY KEY,
  delivery_id TEXT NOT NULL UNIQUE,
  recipient TEXT NOT NULL,
  confirmation_url TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'queued',
  created_at INTEGER NOT NULL DEFAULT (unixepoch())
);

Run the upsert and the delivery and outbox inserts inside a single write transaction:

BEGIN IMMEDIATE
run the subscriber upsert
if the upsert returned a row:
  insert one queued email_deliveries row
  insert its email_outbox row
COMMIT

BEGIN IMMEDIATE serializes competing SQLite writers, and if the transaction rolls back, you don’t leave behind a rotated token or leftover email work.

When the upsert returns no row, look up the existing subscriber to check their state:

SELECT id, status
FROM subscribers
WHERE list_id = ?
  AND email = ?;

Whether the subscriber is already confirmed or still pending inside the cooldown window, return the same neutral HTTP response.

Recover after delivery failure

The cooldown gets in the way when the previous email bounced or the provider rejected it. In that case, the user shouldn’t have to wait before trying again.

Look up the latest delivery using its database sequence rather than a timestamp, since several attempts can share the same timestamp:

SELECT id, status
FROM email_deliveries
WHERE subscriber_id = ?
ORDER BY sequence DESC
LIMIT 1;

Allow an immediate retry when the latest delivery ended in one of these states:

const retryable = [
  'bounced',
  'failed',
  'rejected'
]

Inside the same BEGIN IMMEDIATE transaction, claim that failed attempt so concurrent requests can’t retry it twice:

INSERT INTO email_deliveries (
  id,
  subscriber_id,
  operation_key,
  retry_of_delivery_id,
  status
) VALUES (?, ?, ?, ?, 'queued')
ON CONFLICT (retry_of_delivery_id)
WHERE retry_of_delivery_id IS NOT NULL
DO NOTHING
RETURNING id;

If that insert doesn’t return a row, another request has already claimed the failure. Otherwise, rotate the token while making sure the subscriber is still pending:

UPDATE subscribers
SET
  consent_at = unixepoch(),
  consent_version = ?,
  confirmation_token_hash = ?,
  confirmation_expires_at = ?
WHERE id = ?
  AND status = 'pending'
RETURNING id;

If the update returns no row, roll back the transaction. If it succeeds, insert the complete confirmation email into email_outbox and commit.

A worker sends each outbox row using delivery_id as the provider’s idempotency key. If the worker crashes after the provider accepts the message, retrying the outbox row sends the same key. You need that provider-side idempotency key to avoid duplicate sends across crashes, because your database alone can’t tell whether the provider already accepted the first request.

Test the important sequences

Before shipping this, make sure your tests cover these cases:

  1. A first submission creates a pending subscriber and sends a confirmation email.
  2. An immediate duplicate doesn’t send anything.
  3. A submission after the cooldown rotates the token and sends a new email.
  4. A confirmed subscriber stays confirmed and doesn’t receive another email.
  5. A failed delivery allows an immediate retry.
  6. Concurrent first submissions still produce one subscriber.
  7. Concurrent retries after a failure send only one new email.

The original implementation that inspired this post used an unconditional recovery update, which left a race open when retries arrived together. Pairing a unique retry claim with an outbox closes that race and keeps every database change tied to its email work.

Next, you’ll want to look at making the confirmation link safe from email scanners and tracking what happens after the email provider accepts a message. You can also see this same signup flow wired up in Build a waiting list with double opt-in on your own Cloudflare account.

Want me to talk about your product? You can sponsor this site.

Related posts about database: