Sub topic 4
Modelling the subscriber lifecycle
This chapter turns the consent rules from earlier chapters into a data model. It assumes you can read basic SQL and Python, you know what a database transaction is, and you have seen the difference between single and double opt-in. By the end you will have a small state machine that every later feature (confirmation links, unsubscribe, preference centre) can rely on.
Why model states explicitly
A subscriber list is often a single column of addresses plus a boolean such as is_active. That breaks as soon as you add double opt-in. Three different situations all look like "not active":
- The person signed up but has not confirmed yet.
- The person confirmed and later unsubscribed.
- The address was added by mistake and should never be mailed.
Each needs different handling. You may remind the first group once. You must never mail the second group. You need to know the history of the third. A named status column lets the database and the application agree on which of these a row is in.
The three core states
The schema from the topic plan uses a status column with three values:
| State | Meaning | May receive marketing email? |
|---|---|---|
| `pending` | An address was submitted but ownership of the mailbox is not yet proven | No. Only the confirmation message (and a limited reminder) |
| `confirmed` | The mailbox owner clicked the confirmation link and pressed the button | Yes, subject to preferences and the suppression list |
| `unsubscribed` | The person withdrew consent | No |
CREATE TABLE subscribers (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'confirmed', 'unsubscribed')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
confirmed_at TIMESTAMPTZ
);The CHECK constraint means a typo such as 'confirmd' fails at write time instead of silently excluding someone from every send. The UNIQUE constraint on email gives you one row per person, which the transitions below depend on.
Normalise the address before it reaches the constraint
UNIQUE compares exact strings. [email protected] and [email protected] would become two rows, and an unsubscribe for one would leave the other mailable. Trim whitespace and lowercase the whole address before every lookup and insert. Lowercasing the local part is not strictly guaranteed by the email standards, but in practice mailbox providers treat it as case-insensitive, and the cost of a duplicate is higher than the cost of the rare exception. Do not strip +tag suffixes or dots, because those can identify different mailboxes.
Transitions
A state machine is defined by which moves are allowed and what triggers them. Here is the full set for this tutorial.
Three rules in this diagram deserve explanation, because each prevents a real failure.
- A repeat sign-up never demotes a confirmed subscriber. If submitting the form reset a confirmed row to
pending, anyone could stop a stranger's newsletters by typing their address into your form. The sign-up for a confirmed address is a no-op. You can show the same "check your inbox" message either way so the form does not reveal who is subscribed. - Unsubscribed people return only through a fresh sign-up. They go to
pending, not straight toconfirmed, so the person must prove mailbox ownership again. An admin import, a purchase, or an old confirmation link must not move a row out ofunsubscribed. - Unsubscribing is idempotent. A person may click the link twice, or a mail client may send a one-click POST and the person may then also click the footer link. The second request should succeed and change nothing.
Confirmation has one more edge case. If someone signs up, unsubscribes from the pending state, and then clicks the old confirmation link, the link must not revive the subscription. The WHERE status = 'pending' condition in the confirm query from the landing-page chapter handles this, and the table below makes the logic explicit.
| Current state | Event | New state | Side effects |
|---|---|---|---|
| none | signup | `pending` | Insert row, send confirmation email |
| `pending` | signup | `pending` | Resend, subject to a rate limit |
| `pending` | confirm | `confirmed` | Set `confirmed_at` |
| `pending` | unsubscribe | `unsubscribed` | Stop all mail |
| `confirmed` | signup | `confirmed` | None |
| `confirmed` | confirm | `confirmed` | None (repeat is harmless) |
| `confirmed` | unsubscribe | `unsubscribed` | Stop all mail |
| `unsubscribed` | signup | `pending` | Clear `confirmed_at`, send confirmation email |
| `unsubscribed` | confirm | `unsubscribed` | Reject, the link is stale |
| `unsubscribed` | unsubscribe | `unsubscribed` | None |
Encoding the rules in code
Keeping the table in one place, as data, makes it testable. This standalone Python module has no dependencies and can be run as it is.
TRANSITIONS = {
(None, "signup"): "pending",
("pending", "signup"): "pending",
("pending", "confirm"): "confirmed",
("pending", "unsubscribe"): "unsubscribed",
("confirmed", "signup"): "confirmed",
("confirmed", "confirm"): "confirmed",
("confirmed", "unsubscribe"): "unsubscribed",
("unsubscribed", "signup"): "pending",
("unsubscribed", "confirm"): "unsubscribed",
("unsubscribed", "unsubscribe"): "unsubscribed",
}
def next_status(current, event):
"""Return the new status, or raise if the move is not defined."""
try:
return TRANSITIONS[(current, event)]
except KeyError:
raise ValueError(f"No transition for {event!r} from {current!r}")
if __name__ == "__main__":
status = None
for event in ["signup", "confirm", "signup", "unsubscribe", "confirm", "signup"]:
status = next_status(status, event)
print(f"{event:12} -> {status}")Running it prints pending, confirmed, confirmed, unsubscribed, unsubscribed, pending. The second signup leaves the person confirmed, and the stale confirm after unsubscribing changes nothing.
An undefined pair raises an error instead of guessing. That is deliberate: a missing case is a bug you want to see in a test, not a silent state change on a real person.
Changing state and writing the event together
The consent_events table from the plan is an append-only history. The status column answers "what is true now" and the events answer "how did we get here". They must change together. If the status update succeeds and the event insert fails, you have a confirmed subscriber with no evidence of confirming.
In PostgreSQL, a single statement with a common table expression does both atomically, and the WHERE status = 'pending' makes the transition conditional:
WITH changed AS (
UPDATE subscribers
SET status = 'confirmed', confirmed_at = now()
WHERE email = '[email protected]'
AND status = 'pending'
RETURNING id
)
INSERT INTO consent_events (subscriber_id, event_type, source, consent_text)
SELECT id, 'confirm', 'email_link', 'Confirmed via link in confirmation email'
FROM changed;If the row is not pending, changed is empty and nothing is inserted. A double click therefore produces one confirm event, not two. The conditional update also protects against race conditions: two concurrent requests cannot both succeed, because the database applies the WHERE clause under a row lock.
What does not belong in `status`
It is tempting to add bounced, complained, paused, or suppressed as extra values. Resist that for two reasons.
- They are independent of consent. A person can be confirmed and have a hard-bouncing mailbox. The status describes consent. The suppression list, covered in a later chapter, describes whether you may send right now. Mixing the two means that fixing a mailbox would appear to change a consent decision.
- They have different lifetimes. A pause in the preference centre ends on a date. A consent withdrawal does not end unless the person acts again.
Keeping consent status small and the other facts in their own tables makes the sending query simple: a subscriber is mailable when status = 'confirmed', the address is not in the suppression list, and the preferences allow the message.
Single opt-in under the same model
Single opt-in does not need a different schema. On sign-up you apply signup and confirm back to back, so the row skips pending in practice and still records two events with a different source. Using one model for both means you can change a list's policy later without migrating data. The cost is that single opt-in rows carry weaker evidence, since no mailbox proof exists, and your records should show that honestly.
Common mistakes
- Deleting unsubscribed rows. You then forget who opted out and may re-import and mail them. Keep the row with status
unsubscribed. - Setting
confirmed_aton import. Importing a purchased or legacy list asconfirmedfabricates consent. Import it aspendingand run a confirmation campaign, or do not import it. - Leaving
confirmed_atset after re-signup. The column then claims a confirmation that no longer applies. Clear it when moving fromunsubscribedtopending. - Letting GET requests change state. The link-scanner chapter covers this: a prefetching scanner would otherwise confirm or unsubscribe people.
Exercise
A person confirmed last month. Today a stranger types that person's address into your sign-up form. What status should the row have afterwards, what should the form show, and why?
Show answer
The row stays confirmed because the table defines (confirmed, signup) -> confirmed. The form shows the same "check your inbox" message as for any other sign-up, so it does not reveal whether the address is already subscribed. Resetting the row to pending would let anyone suspend a stranger's subscription, and sending a new confirmation email would let your form be used to pester a third party.
Exercise
Write the single SQL statement that unsubscribes [email protected] and records an unsubscribe event only if the person was not already unsubscribed. Why does this make a double click safe?
Show answer
WITH changed AS (UPDATE subscribers SET status = 'unsubscribed' WHERE email = '[email protected]' AND status <> 'unsubscribed' RETURNING id) INSERT INTO consentevents (subscriberid, eventtype, source) SELECT id, 'unsubscribe', 'footerlink' FROM changed; On the second click the row is already unsubscribed, so the UPDATE matches nothing, changed is empty, and no duplicate event is written. The person still sees a success page, so the repeat is harmless.