Sub topic 16
Measuring the funnel and testing the flow
This chapter assumes you have the schema from earlier chapters (subscribers and consent_events), the signed token functions, and the GET/POST confirmation handlers. You should be comfortable with SQL aggregates and with writing tests in Python. Here you will measure how the flow performs and check that each safety property still holds after every change.
What you are measuring
A double opt-in flow is a funnel. Each stage loses some people, and each loss has a different cause and a different fix. Measure the stages separately.
The table lists the metrics worth tracking and what each one tells you.
| Metric | Definition | What a problem suggests |
|---|---|---|
| Confirmation rate | Confirmed subscribers divided by sign-ups, per sign-up cohort | Weak email subject, delivery to spam, unclear landing page |
| Time to confirm | Median time from `signup` to `confirm` | A long tail suggests the email arrives late or is ignored |
| Expiry rate | Pending subscribers whose token has expired | The expiry window is too short, or no reminder is sent |
| Resend recovery | Share of resent confirmations that lead to a confirm | Whether the resend step is worth keeping |
| Bounce rate at confirmation | Hard bounces on the confirmation email | Typos, fake addresses, a missing address check on the form |
| First-send unsubscribe rate | Unsubscribes after the first campaign, divided by recipients | Expectations set at sign-up do not match what you send |
| Complaint rate | Spam complaints divided by delivered messages | Reputation risk. Google asks bulk senders to stay under 0.3% and recommends staying below 0.1% |
| One-click share | Unsubscribes that arrive through the header POST | Whether the header works and mail clients use it |
| Preference save rate | Preference changes divided by all attempts to leave | Whether the preference centre keeps people who would otherwise leave |
Compute rates by sign-up cohort, not by calendar day. Someone who signs up on Friday may confirm on Monday. A daily ratio of confirms to sign-ups will look wrong at both ends of the weekend, and a cohort view will not.
Do not use open rate as a funnel stage. Mail Privacy Protection and some security scanners load images automatically, so opens overstate real attention. Confirmation clicks are more reliable, but only if your GET/POST split is in place. Without it, a scanner that follows the link can create a confirm event no human caused. If your confirmation rate looks excellent and the median time to confirm is a few seconds, suspect scanners.
Computing the funnel from the audit trail
Because consent_events is append-only, the funnel can be rebuilt from it at any time. The query below groups people by the week they signed up and counts how many of them ever confirmed.
WITH signups AS (
SELECT subscriber_id, min(occurred_at) AS signed_up_at
FROM consent_events
WHERE event_type = 'signup'
GROUP BY subscriber_id
),
confirms AS (
SELECT subscriber_id, min(occurred_at) AS confirmed_at
FROM consent_events
WHERE event_type = 'confirm'
GROUP BY subscriber_id
)
SELECT
date_trunc('week', s.signed_up_at) AS cohort_week,
count(*) AS signups,
count(c.confirmed_at) AS confirmed,
round(100.0 * count(c.confirmed_at) / count(*), 1) AS confirm_rate_pct,
percentile_cont(0.5) WITHIN GROUP (
ORDER BY c.confirmed_at - s.signed_up_at
) AS median_time_to_confirm
FROM signups s
LEFT JOIN confirms c USING (subscriber_id)
GROUP BY 1
ORDER BY 1;Using min(occurred_at) per subscriber means a repeated confirmation, which the handler allows, is counted once. percentile_cont ignores rows where confirmed_at is NULL, so the median describes only people who confirmed. Read it together with the confirmation rate.
Recent cohorts will always look worse than old ones, because their tokens have not yet had time to be used. Do not compare a cohort younger than your token lifetime (48 hours in the earlier chapter) with older ones.
Testing the flow
Metrics tell you that something changed. Tests tell you that the safety properties still hold. Test at three levels.
Unit tests for tokens and handlers
The token code has four properties that must never regress: it accepts valid tokens, rejects the wrong purpose, rejects expired tokens, and rejects tampered ones. The handler code has one: a GET request changes nothing. This pytest file covers them. It assumes the token functions are in tokens.py and the two handlers are in flow.py.
import os
os.environ.setdefault("TOKEN_SECRET", "test-secret")
import pytest
import flow
import tokens
class FakeDB:
def __init__(self):
self.calls = []
def execute(self, sql, params):
self.calls.append((sql, params))
@pytest.fixture(autouse=True)
def stub_render(monkeypatch):
monkeypatch.setattr(flow, "render", lambda name, **kw: name, raising=False)
def test_round_trip():
token = tokens.make_token("[email protected]", "confirm")
assert tokens.verify_token(token, "confirm") == "[email protected]"
def test_wrong_purpose_is_rejected():
token = tokens.make_token("[email protected]", "confirm")
assert tokens.verify_token(token, "unsubscribe") is None
def test_expired_token_is_rejected():
token = tokens.make_token("[email protected]", "confirm", ttl_seconds=-1)
assert tokens.verify_token(token, "confirm") is None
def test_forged_payload_is_rejected():
real = tokens.make_token("[email protected]", "confirm")
other = tokens.make_token("[email protected]", "confirm")
forged = other.split(".")[0] + "." + real.split(".")[1]
assert tokens.verify_token(forged, "confirm") is None
@pytest.mark.parametrize("junk", ["", "abc", "a.b.c", "!!!.???"])
def test_garbage_is_rejected(junk):
assert tokens.verify_token(junk, "confirm") is None
def test_get_does_not_change_state():
db = FakeDB()
token = tokens.make_token("[email protected]", "confirm")
assert flow.show_confirmation_page(token) == "confirm_button.html"
assert db.calls == []
def test_post_only_updates_pending_rows():
db = FakeDB()
token = tokens.make_token("[email protected]", "confirm")
flow.confirm_subscription(db, token)
flow.confirm_subscription(db, token)
assert len(db.calls) == 2
assert all("status = 'pending'" in sql for sql, _ in db.calls)The last test checks the idempotence guard in the SQL text. It does not prove the database behaves correctly, so back it with an integration test.
Integration tests against a real database
Run the schema in a throwaway PostgreSQL database and check outcomes, not SQL strings:
- Sign up, confirm twice, and assert that
statusisconfirmedandconfirmed_atdid not change on the second call. - Unsubscribe a confirmed subscriber, then replay the old confirmation token. The subscriber must stay
unsubscribed, because theWHERE status = 'pending'guard blocks the update. - Assert that every state change wrote exactly one row to
consent_events, with a non-emptysource. - Add the address to the suppression list and assert the send query returns no row for it.
End-to-end tests with a mail catcher
Point a staging environment at a local SMTP catcher such as Mailpit. Submit the sign-up form, read the captured message, and check:
- The message contains both
List-UnsubscribeandList-Unsubscribe-Post: List-Unsubscribe=One-Clickheaders on marketing mail. - The HTTPS unsubscribe address accepts a POST with the body
List-Unsubscribe=One-Clickand does not require a login or cookie. - Opening the confirmation link with a plain GET leaves the subscriber pending. You can simulate a scanner like this:
curl -s -o /dev/null -w "%{http_code}\n" "https://staging.example.com/confirm/$TOKEN"
psql "$DATABASE_URL" -c "SELECT status FROM subscribers WHERE email = '[email protected]';"The status must still read pending. Then POST to the same address and check that it becomes confirmed.
To test expiry without waiting 48 hours, pass a short ttl_seconds in a test build, or patch time.time. Do not add a production setting that disables expiry checks.
Setting up alerts
Some failures are quiet. Add alerts for these conditions:
- The confirmation rate for a cohort older than 72 hours falls well below the trailing average.
- More than a small share of confirmations happen within five seconds of the email being sent. This is a sign scanners are confirming people.
- The count of sends that skipped the suppression check is above zero. Log it at send time.
- Complaint rate approaches the mailbox provider limit.
- The one-click POST endpoint returns anything other than a success status.
Pick the thresholds from your own history after a few weeks of data. Generic benchmarks for confirmation rates vary too much by audience and source to be useful targets.
Common mistakes
- Counting per event instead of per subscriber. Repeated confirmations and resends inflate counts unless you use
DISTINCTormin()per person. - Judging young cohorts. A cohort that is still inside its token lifetime is incomplete.
- Treating a high confirmation rate as success. If scanners confirm people, the rate is high and the list quality is poor. Check time to confirm.
- Testing only the happy path. The valuable tests are the rejections: wrong purpose, expired, forged, replayed after unsubscribe.
- Changing the form copy without recording it. If you A/B test the sign-up wording, store the variant in
consent_textso that the audit trail matches what each person saw.
Exercise
Your dashboard shows a 92% confirmation rate, and the median time to confirm is 2 seconds. Your own test sign-ups usually take about a minute. What is the most likely cause, which test would confirm it, and what should you check in the code?
Show answer
Security scanners or link prefetchers are following the confirmation link and causing confirmations, so the rate is inflated. Confirm it by sending a plain GET request with curl to a confirmation link for a pending test address and checking whether the subscriber becomes confirmed. In the code, check that the GET handler only shows a page with a button and that only the POST handler updates subscribers and writes the confirm event.
Exercise
Why does the funnel query use LEFT JOIN from signups to confirms rather than an inner join?
Show answer
A LEFT JOIN keeps subscribers who never confirmed, so count(*) is the true number of sign-ups and the confirmation rate has the right denominator. An inner join would count only people who confirmed and show a rate of 100%.