Sub topic 14
Designing and building a preference centre
A preference centre is a web page where a subscriber chooses what they receive instead of choosing between everything and nothing. This chapter assumes you have the subscriber lifecycle (pending, confirmed, unsubscribed), the signed token helpers make_token and verify_token, and the consent_events table from earlier chapters. It also assumes basic SQL and Python, and that you know the difference between a GET and a POST request.
What a preference centre is for
A subscriber who is unhappy with your emails has three options: ignore them, mark them as spam, or unsubscribe. The first two hurt you. Ignored mail lowers engagement. Spam complaints damage sender reputation. A preference centre gives that subscriber a fourth option: reduce what they get.
A preference centre does not replace the unsubscribe link. It sits beside it. The rules are:
- Unsubscribing stays one step. A one-click unsubscribe must still work without visiting the preference centre.
- The centre offers alternatives. Fewer topics, lower frequency, or a temporary pause.
- Every change is recorded. Preference changes are consent changes, so they go into the audit trail.
Choosing what to offer
Each control you add must change what you actually send. A control that does nothing is worse than no control, because the subscriber discovers it later and complains.
| Control | What it changes | Cost to you |
|---|---|---|
| Topic toggles | Which campaigns the subscriber is included in | You must tag every campaign with a topic |
| Maximum frequency | How many messages per period | You need a send-time frequency check |
| Pause until a date | Excludes the subscriber until the date passes | You need a date filter, and a cap on the pause length |
| Unsubscribe from all | Moves the subscriber to `unsubscribed` | Must write to the suppression list |
Start with two or three topics. Many topics produce a long form that few people finish, and each one needs content to back it up.
The data model
The preference record from the spine looks like this:
{
"email": "[email protected]",
"topics": {
"product_updates": true,
"weekly_digest": true,
"events": false
},
"frequency": "weekly",
"paused_until": "2027-01-15"
}In SQL, keep preferences in their own table, one row per subscriber. This keeps the subscribers table small and lets the preference shape change without touching lifecycle logic.
CREATE TABLE subscriber_preferences (
subscriber_id BIGINT PRIMARY KEY REFERENCES subscribers(id),
topics JSONB NOT NULL DEFAULT '{}',
frequency TEXT NOT NULL DEFAULT 'weekly'
CHECK (frequency IN ('daily', 'weekly', 'monthly')),
paused_until DATE,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);A JSONB column for topics is a trade-off. Adding a topic needs no migration, but the database cannot enforce which topic names are valid. Enforce that in application code, as the validator below does. If you have many topics and need to query them heavily, a separate subscriber_topics table with one row per topic is easier to index.
Reaching the page safely
The preference centre exposes personal data and can change it, so a visitor must prove they own the address. The simplest method is a link in every email that carries a signed token, the same mechanism as confirmation links.
Use a different purpose string, "preferences", so that a confirmation token cannot open the centre. verify_token already rejects a token whose purpose does not match. Give these tokens a longer lifetime than confirmation tokens, such as 30 days, because the link sits in emails people read late. Each new email carries a fresh link.
token = make_token(email, "preferences", ttl_seconds=30 * 24 * 3600)
link = f"https://example.com/preferences/{token}"If the token has expired, show a page that asks for the email address and sends a new link. Do not reveal on that page whether the address is on your list. Always show "If that address is subscribed, we have sent a link."
Apply the scanner rule from the earlier chapter here too. A GET request shows the form and changes nothing. Only a POST request saves.
Validating what the visitor submits
Treat every form field as untrusted input. The validator below accepts only known topics, known frequencies, and a pause date that is in the future and no more than 180 days away. The pause cap stops a "pause" from becoming a silent way to hold someone for years without a clear record of intent.
from datetime import date, timedelta
TOPICS = {"product_updates", "weekly_digest", "events"}
FREQUENCIES = {"daily", "weekly", "monthly"}
MAX_PAUSE_DAYS = 180
def validate_preferences(data: dict, today: date | None = None) -> dict:
"""Return a clean preference dict or raise ValueError.
Topics missing from the input are treated as off, because an
unchecked HTML checkbox is not sent by the browser at all.
"""
today = today or date.today()
topics = data.get("topics", {})
unknown = set(topics) - TOPICS
if unknown:
raise ValueError(f"unknown topics: {sorted(unknown)}")
if not all(isinstance(v, bool) for v in topics.values()):
raise ValueError("topic values must be true or false")
clean_topics = {name: topics.get(name, False) for name in sorted(TOPICS)}
frequency = data.get("frequency", "weekly")
if frequency not in FREQUENCIES:
raise ValueError(f"unknown frequency: {frequency!r}")
paused_until = data.get("paused_until")
if paused_until:
paused_until = date.fromisoformat(paused_until)
if paused_until <= today:
raise ValueError("pause date must be in the future")
if paused_until > today + timedelta(days=MAX_PAUSE_DAYS):
raise ValueError("pause is too long")
else:
paused_until = None
return {
"topics": clean_topics,
"frequency": frequency,
"paused_until": paused_until,
}
if __name__ == "__main__":
print(validate_preferences({"topics": {"events": True}, "frequency": "monthly"}))date.fromisoformat raises ValueError on a malformed date, so one except ValueError in the handler covers every failure.
Saving the change and recording it
The POST handler verifies the token, validates the input, writes the preferences, and appends a consent event, all in one transaction. It only updates subscribers who are confirmed, so someone who has unsubscribed cannot be silently re-enrolled through an old preferences link.
import json
def save_preferences(db, token: str, form: dict, ip: str, user_agent: str):
"""Handle POST from the preference centre."""
email = verify_token(token, "preferences")
if email is None:
return render("link_invalid_or_expired.html")
try:
prefs = validate_preferences(form)
except ValueError as error:
return render("preferences_form.html", token=token, error=str(error))
with db.transaction():
db.execute(
"INSERT INTO subscriber_preferences "
"(subscriber_id, topics, frequency, paused_until) "
"SELECT id, %s, %s, %s FROM subscribers "
"WHERE email = %s AND status = 'confirmed' "
"ON CONFLICT (subscriber_id) DO UPDATE SET "
"topics = EXCLUDED.topics, frequency = EXCLUDED.frequency, "
"paused_until = EXCLUDED.paused_until, updated_at = now()",
(json.dumps(prefs["topics"]), prefs["frequency"],
prefs["paused_until"], email),
)
db.execute(
"INSERT INTO consent_events "
"(subscriber_id, event_type, source, consent_text, ip_address, user_agent) "
"SELECT id, 'preferences_updated', 'preference_centre', %s, %s, %s "
"FROM subscribers WHERE email = %s AND status = 'confirmed'",
(json.dumps(prefs, default=str), ip, user_agent, email),
)
return render("preferences_saved.html")Here render is your template function, as in the confirmation chapter, and db.transaction() stands for whatever transaction context your database library provides. Storing the submitted values in consent_text lets you later show exactly what the subscriber chose and when.
Applying preferences at send time
Preferences only matter if the sending query respects them. The query below selects recipients for a campaign tagged with one topic. It assumes a suppression_list table with an email column, and it checks suppression first.
SELECT s.id, s.email
FROM subscribers s
JOIN subscriber_preferences p ON p.subscriber_id = s.id
WHERE s.status = 'confirmed'
AND NOT EXISTS (SELECT 1 FROM suppression_list x WHERE x.email = s.email)
AND (p.paused_until IS NULL OR p.paused_until <= CURRENT_DATE)
AND (p.topics ->> 'weekly_digest')::boolean IS TRUE;A subscriber with no preferences row is excluded by the inner join. Decide deliberately whether that is what you want. If you want new subscribers to receive default topics, create their preferences row when they confirm.
Frequency needs a second check: count the messages sent to each subscriber in the period and skip those at their limit. Record sends in a table so the count is cheap.
Common mistakes
- Making unsubscribe harder. Burying "unsubscribe from all" below ten toggles, or requiring a login, invites spam complaints and may breach legal requirements. Keep it visible on the page.
- Changing state on GET. A scanner that opens the link would then alter preferences.
- Reusing the confirmation token. Always check the purpose.
- Silent re-subscription. Never let a preference save move someone from
unsubscribedback toconfirmed. Re-subscribing needs a new sign-up and a new confirmation. - Ignoring preferences in one sender. If a second system, such as a transactional or automation tool, sends marketing mail, it must read the same preference and suppression data.
Exercise
A subscriber opens the preference centre from an old email, sets a pause until a date 300 days away, and submits. What should happen, and which part of the code decides it?
Show answer
The submission should be rejected and the form shown again with an error message such as "pause is too long". validate_preferences decides this: it raises ValueError when paused_until is later than today plus MAX_PAUSE_DAYS (180 days), and save_preferences catches the error and re-renders the form instead of writing anything.
Exercise
Your send query joins subscriber_preferences with an inner join. A subscriber confirmed last week never opened the preference centre. Will they receive the weekly digest, and how would you change that?
Show answer
No. They have no preferences row, so the inner join drops them. To include them, create a row with default topics when the subscriber confirms, or use a LEFT JOIN and treat a missing row as the default preferences.