Sub topic 8
Handling resends, expiry, and abandoned sign-ups
This chapter assumes you have the subscribers and consent_events tables from the lifecycle chapter. It also assumes you can issue and verify the signed confirmation tokens from the token chapter. It covers what happens when a confirmation email isn't acted on: the link expires, the person asks for another email, or they never come back.
Why a pending sign-up needs a policy
A double opt-in sign-up has three outcomes. The person confirms, the person asks for a new email, or the person does nothing. Without a policy, each outcome produces a failure:
- A link that never expires stays valid in an inbox for years and can be confirmed by someone who has since lost control of the mailbox.
- Unlimited resends let anyone use your signup form to send mail to a third party's address. Mailbox providers treat repeated unsolicited confirmation mail as spam.
- Pending rows that are never removed fill your database with addresses that never consented. Some of them are typos or spam traps.
Three rules cover these cases:
- A confirmation token lives for a fixed time. The token chapter set 48 hours.
- A pending subscriber gets a limited number of confirmation emails, with a cooldown between them.
- A pending subscriber who never confirms is deleted after a fixed time.
Expiry is enforced by the token, not the database
verify_token already rejects a token whose expires timestamp has passed. The subscriber row stays pending. Expiry only means this particular link no longer works.
The landing page for an expired link should say so plainly and offer a way forward. A page that only says "invalid link" gives people no next step. A page that sends a new email as soon as someone opens an old link is worse. A scanner that opens the link would then trigger a fresh email on every visit. Show a form with a "Send me a new link" button, and send the email only when the form is submitted.
Tokens in this design are stateless. If you send a second email, the first link keeps working until it expires. That is acceptable, because both links confirm the same address. If you need a resend to cancel older links, store a per-subscriber token version and include it in the signed payload. Most lists don't need this.
The resend decision
A resend can come from the expired-link form, or from the person typing the same address into the signup form again. Handle both with one function. It looks at the current state and decides what to do.
Add two columns to track sends:
ALTER TABLE subscribers
ADD COLUMN confirmation_sent_at TIMESTAMPTZ,
ADD COLUMN confirmation_send_count INTEGER NOT NULL DEFAULT 0;The decision logic has no side effects, so you can test it without a database or a mail server. It needs Python 3.10 or later.
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
MAX_SENDS = 3
COOLDOWN = timedelta(minutes=10)
@dataclass
class SubscriberState:
status: str
send_count: int
last_sent_at: datetime | None
def next_action(sub: SubscriberState | None, now: datetime) -> str:
"""Return one of: send_first, resend, wait, limit, ignore."""
if sub is None:
return "send_first"
if sub.status == "confirmed":
return "ignore"
if sub.status == "unsubscribed":
return "send_first" # a new sign-up needs fresh consent
if sub.send_count >= MAX_SENDS:
return "limit"
if sub.last_sent_at and now - sub.last_sent_at < COOLDOWN:
return "wait"
return "resend"
if __name__ == "__main__":
now = datetime(2026, 11, 26, 12, 0, tzinfo=timezone.utc)
assert next_action(None, now) == "send_first"
assert next_action(SubscriberState("confirmed", 1, now), now) == "ignore"
assert next_action(SubscriberState("pending", 1, now), now) == "wait"
old = now - timedelta(hours=1)
assert next_action(SubscriberState("pending", 1, old), now) == "resend"
assert next_action(SubscriberState("pending", 3, old), now) == "limit"
print("all checks passed")Each action has a database effect:
| Action | Database change | Email sent |
|---|---|---|
| `send_first` | Insert the row, or set an unsubscribed row back to `pending` and reset the count. Record a `signup` event. | Yes |
| `resend` | Increment `confirmation_send_count`, set `confirmation_sent_at`. | Yes |
| `wait` | None. | No |
| `limit` | None. | No |
| `ignore` | None. | No |
An unsubscribed person who signs up again is giving new consent, but only once they confirm it. A suppression entry created by a hard bounce or a spam complaint must block this path. The suppression chapter covers that check.
Do not reveal which case applied
The signup form should give the same response whatever next_action returned: "If this address can be subscribed, we have sent a confirmation email." If the response differs, the form tells an attacker which addresses are already on your list, which is user enumeration. It also tells them which are unsubscribed.
The same rule applies to the expired-link form. Treat the email address as input to a lookup, never as proof that the address exists.
Rate limit by IP address as well as by subscriber. The per-subscriber cap stops repeated mail to one address. It doesn't stop someone from submitting thousands of different addresses from one machine. A per-IP limit and a CAPTCHA on the public form handle that.
What the lifecycle looks like with resends
Recording what happened
Each email you send is a fact worth keeping. The consent_events table has no event type for a resend, and a resend isn't consent. Don't add a confirm event until the person actually confirms. A resend is operational data, which is why this chapter keeps it in the two columns above.
Record a signup event for each new sign-up, including a restart after an unsubscribe. The original signup event holds the consent wording and source that the person saw, and a later resend doesn't change that evidence.
Abandoned sign-ups
A pending row that is still unconfirmed after the abandonment window is deleted. Thirty days is a common choice. It is long enough for someone who returns from holiday, and short enough that the data doesn't become stale. Measure the window from the last confirmation email, not from created_at, so a recent resend extends it.
Pending subscribers never consented, so you have no consent evidence to preserve. Delete the events and the subscriber together. The foreign key from consent_events to subscribers stops you deleting the subscriber first, so remove both in one statement:
WITH stale AS (
SELECT id
FROM subscribers
WHERE status = 'pending'
AND COALESCE(confirmation_sent_at, created_at) < now() - interval '30 days'
),
removed_events AS (
DELETE FROM consent_events
WHERE subscriber_id IN (SELECT id FROM stale)
)
DELETE FROM subscribers
WHERE id IN (SELECT id FROM stale)
AND status = 'pending'
RETURNING id;The status = 'pending' check in the final DELETE keeps the subscriber row safe if someone confirms between the SELECT and the delete. Run the statement from a scheduled job once a day and log the number of rows it returns. A sudden spike means many sign-ups were abandoned, which the measuring chapter treats as a signal to investigate.
If you have a legal reason to keep a record that an address once requested a subscription, for example to detect repeated abuse, keep a salted hash of the address instead of the address.
Common errors
- Resending on GET. Opening the expired-link page must not send mail. Scanners open links, and each scan would send an email.
- Resetting the counter on every signup form submission. An attacker could then bypass the cap by resubmitting the form. Reset the count only on the restart from
unsubscribed. - Counting from
created_atfor purging. A person who requested a resend on day 29 would lose their pending row on day 30. - Forgetting that tokens are stateless. A user who receives two emails can confirm with either. This is correct behaviour. Don't treat the second click as an error, and the idempotent
UPDATE ... WHERE status = 'pending'already makes it harmless. - Different responses for different cases. This leaks list membership.
Exercise
A person signs up at 09:00, receives a confirmation email, and ignores it. At 09:05 they submit the same address again. Using the policy in this chapter, what does next_action return, what do they see on the page, and what does the database change?
Show answer
next_action returns wait, because the last email was sent 5 minutes ago and the cooldown is 10 minutes. The page shows the same neutral message as any other case ("If this address can be subscribed, we have sent a confirmation email"). The database doesn't change, because no email is sent and the counter is not incremented. The original link from 09:00 stays valid for its 48 hours.
Exercise
Why does the abandoned-sign-up job delete from consent_events and subscribers in a single statement, and why is the final delete restricted to status = 'pending'?
Show answer
The foreign key means the events must go before, or at the same time as, the subscriber. Doing both in one statement avoids a state where one table was cleaned and the other wasn't. The status = 'pending' check protects a subscriber who confirmed after the job selected the stale rows. Without it, the job could delete a confirmed subscriber.