Sub topic 18
Privacy, consent and compliance
A notification system sends messages to real people through their phones, inboxes and handsets. It also stores personal data: email addresses, phone numbers, device tokens and a history of what each person was sent. Mistakes here can cost money and trust. This chapter covers how consent, data handling and legal rules shape the design.
This chapter assumes you have read the chapters on user preferences, queues and workers, and delivery tracking. It also assumes you can read short Python snippets. It is a design guide, not legal advice. Rules differ by country and change over time, so check them with your legal team.
Why privacy is a design concern
Privacy rules apply to a notification system in three ways:
- Whether you may send. Some channels need explicit consent before the first message.
- What you may store. Contact details, message content and logs are personal data.
- What you must do on request. Users can ask you to stop, to export their data or to delete it.
These rules are easier to meet when they are built into the pipeline early. Adding them later usually means changing every worker.
Preferences versus consent
A preference is a choice a user makes about what they want to receive, such as "no marketing push". Consent is a recorded, provable agreement that you may contact them at all on a given channel for a given purpose. Preferences can be stored as simple flags. Consent needs more detail, because you may have to prove it later.
A consent record should hold:
- the user and the channel (for example SMS)
- the purpose (for example marketing or transactional)
- the status: granted or withdrawn
- the time of the change
- the source, such as a checkbox on the signup form, a reply of "STOP", or an unsubscribe link
- the wording or version of the text the user agreed to
Store consent as an append-only history instead of overwriting one flag. The current state is the latest entry. The history is your evidence.
from dataclasses import dataclass
from datetime import datetime, timezone
@dataclass(frozen=True)
class ConsentRecord:
user_id: str
channel: str
purpose: str # "marketing" or "transactional"
granted: bool
source: str # "signup_form", "sms_stop", "unsubscribe_link"
recorded_at: datetime
class ConsentLog:
def __init__(self):
self._records = []
def record(self, user_id, channel, purpose, granted, source):
self._records.append(ConsentRecord(
user_id, channel, purpose, granted, source,
datetime.now(timezone.utc),
))
def has_consent(self, user_id, channel, purpose):
"""The most recent record for this user, channel and purpose wins."""
for rec in reversed(self._records):
if (rec.user_id, rec.channel, rec.purpose) == (user_id, channel, purpose):
return rec.granted
return False # no record means no consent
log = ConsentLog()
log.record("user-42", "sms", "marketing", True, "signup_form")
log.record("user-42", "sms", "marketing", False, "sms_stop")
print(log.has_consent("user-42", "sms", "marketing")) # FalseThe default matters. When no record exists, the function returns False. A system that defaults to "allowed" will eventually message someone who never agreed.
Transactional versus marketing messages
Most rules treat the two kinds differently.
| Kind | Example | Typical consent need | Can the user opt out? |
|---|---|---|---|
| Transactional | Password reset, order shipped | Usually none beyond the service relationship | Often only for non-essential ones |
| Marketing | Sale announcement, newsletter | Explicit opt-in in many regions | Always, and it must be easy |
Put a purpose field on every event, the same way the event already carries a type. The router can then apply different checks without guessing. Do not label a promotional message "transactional" to get around opt-outs. Regulators and mail providers treat this as abuse.
Where the consent check belongs
Check consent in the shared routing step, before a message is placed on a channel queue. Do not rely on each channel worker to remember it. Check it again just before the actual send, because a user may withdraw consent while the message waits in a queue or in a retry loop.
def may_send(event, consent_log, channel):
purpose = getattr(event, "purpose", "transactional")
if purpose == "transactional":
return True
return consent_log.has_consent(event.user_id, channel, purpose)This function is deliberately small so that every worker can call it. The check is cheap compared with the cost of a wrongful send.
The flow below shows both checks.
Honoring opt-outs quickly
Each channel has its own opt-out mechanism, and you must connect all of them to the same consent log:
- Email: an unsubscribe link in every marketing message. Many mailbox providers also expect a one-click unsubscribe header.
- SMS: reply keywords such as STOP. Your SMS provider often tracks these, and you must sync them into your own records through a webhook.
- Push: the user can turn off notifications in the operating system. You learn this through failed deliveries or invalid tokens, as covered in the device token chapter.
- In-app: a settings screen backed by the preference store.
Process opt-outs promptly. Some laws set a deadline for honoring them. A good target is to apply them within minutes, not days, by writing to the consent log as soon as the event arrives.
Minimizing the personal data you hold
Store only what you need. Several design choices help:
- Keep contact details in one place. Notification events should carry a
user_id, and the worker should look up the email or phone number at send time. This avoids copying addresses into queues, logs and analytics tables. - Keep payloads small. Put the order number in the payload, not the full address. A template can fetch the rest if it really needs it.
- Mask values in logs. Log
user-42and the channel, not the phone number or message body. - Protect sensitive content. Lock-screen previews and SMS are visible to anyone holding the phone, and SMS is not encrypted end to end. Do not send one-time codes or health details in a form that reveals more than necessary.
def mask_phone(number):
"""Show only the last two digits so logs stay useful but not identifying."""
return "*" * max(len(number) - 2, 0) + number[-2:]
print(mask_phone("+14155550123")) # **********23Retention and deletion
Delivery logs help with debugging and tracking, but you should not keep them forever. Set a retention period for each data type, and enforce it with an automatic job.
| Data | Why you keep it | Example retention |
|---|---|---|
| Delivery status records | Debugging, support | 30 to 90 days |
| Message bodies | Rarely needed after sending | Short, or not stored |
| Consent history | Proof of consent | Long, while the relationship lasts plus a legal period |
| Device tokens | Sending push | Until invalid or user logs out |
The example periods are illustrations, not recommendations for your case.
When a user asks for deletion, you must find their data everywhere: the preference store, device tokens, delivery logs, queues and any analytics copies. Consent history is a special case. You may need to keep a minimal record that the person opted out, so that you do not message them again. Store this as a hashed identifier or a suppression entry, and document the reason.
Regional rules and data location
Several well-known regimes affect notification design. This is an overview only.
- GDPR (European Union): requires a lawful basis for processing, such as consent. It gives users rights to access, correct and delete their data.
- ePrivacy rules (European Union): govern electronic marketing and generally require opt-in for marketing messages.
- CAN-SPAM (United States): covers commercial email. It requires a clear unsubscribe method and a physical sender address.
- TCPA (United States): limits automated calls and texts, and generally requires prior consent for marketing texts.
- CASL (Canada): requires consent for commercial electronic messages.
Two practical consequences follow. First, the user's region may decide which rules apply, so store a country or region on the user profile. Second, some rules limit where data may be stored or processed. If you use third-party providers, remember that each one receives personal data from you. Review their agreements, and choose regional endpoints where required.
Time and place of sending
Quiet hours are a courtesy, and in some regions they are a legal requirement for calls and texts. Evaluate quiet hours in the user's own time zone, not the server's. Store the zone as an IANA name such as Europe/Paris, not a fixed offset, so that daylight saving changes are handled for you.
Audit trail
Keep a record of each decision the router makes. When a message is sent or blocked, log the event id, the user id, the channel, the decision and the reason, such as blocked: no_consent or blocked: quiet_hours. This helps you answer a complaint that says "why did I get this?" or "why did I not get this?" It also feeds the observability work from the previous chapter. Keep audit logs free of message bodies and raw contact details.
Common mistakes
- Treating a missing consent record as "yes".
- Checking consent only at ingestion, so withdrawn consent is ignored for queued messages.
- Syncing SMS opt-outs from the provider but never reading them back.
- Putting phone numbers and email addresses into logs and queue payloads.
- Deleting a user's data without keeping a suppression entry.
- Using the server's time zone to decide quiet hours.
Exercise
A user replies STOP to a marketing SMS at 10:00. A marketing SMS for that user was placed on the SMS queue at 09:59 and a worker picks it up at 10:02. Which design lets the system avoid sending it, and what should be logged?
Show answer
The worker must check consent again immediately before calling the provider, reading from the consent log that the STOP webhook updated at 10:00. The check finds the latest record is "withdrawn", so the worker drops the message. It should log the event id, user id, channel, the decision "blocked" and the reason "no_consent", without the phone number or message body.
Exercise
Why should a notification event carry a user_id instead of the user's phone number, and what is the trade-off?
Show answer
A user_id keeps phone numbers out of queues, logs and analytics copies, so there are fewer places to protect, delete and audit. The trade-off is that the worker needs an extra lookup at send time, and that lookup service becomes a dependency that must be fast and available.