Sub topic 5
Respecting user preferences and quiet hours
This chapter assumes you have read the architecture and event ingestion chapters. It also assumes you can read short Python snippets and know what a key-value store or relational table does. Here you decide, for each event, which channels a user wants and whether now is a good time to interrupt them.
Why preferences are a routing step
A notification system that ignores preferences gets muted, uninstalled, or reported as spam. Preferences are also often a legal requirement, which the privacy chapter covers. Treat them as a routing stage, not a UI feature. Every event passes through it after ingestion and before it reaches a channel queue.
The stage answers three questions:
- Which channels has this user enabled for this notification type?
- Is it currently a bad time to interrupt them?
- If it is a bad time, should we delay the message, downgrade it to a quieter channel, or drop it?
What to store
Keep preferences at two levels: per type and channel, and per user.
| Scope | Fields | Example |
|---|---|---|
| Type and channel | user_id, type, channel, enabled | user-42, order_shipped, push, true |
| User-wide | timezone, quiet_start, quiet_end, global opt-out flags | America/New_York, 22:00, 07:00 |
Store the timezone as an IANA name such as America/New_York, not a fixed offset. A fixed offset breaks twice a year at daylight saving changes.
The routing stage reads these values on every event, so cache them (for example in a key-value store with a short expiry) and invalidate the cache when the user saves a change. A stale cache is a real failure here. A user who just opted out of SMS should not get one a minute later.
Decide what a missing row means. The routing function below treats a missing type as "no channels". If you add a new notification type and forget to seed defaults, nobody receives it. Merge a default preference set with the user's overrides before routing.
Choosing channels
The routing function takes the event, the user's per-type preferences, and a flag saying whether quiet hours apply:
def choose_channels(event, prefs, quiet_hours_active):
"""Return the channels to use for this event.
prefs maps a notification type to the channels the user enabled,
for example {"order_shipped": ["push", "email"]}.
"""
allowed = list(prefs.get(event.type, []))
if quiet_hours_active and event.priority != "critical":
allowed = [c for c in allowed if c == "in_app"]
return allowedThe function starts from what the user enabled. It never adds a channel the user did not choose. During quiet hours it keeps only in_app, which shows up silently the next time the user opens the app. Critical events, such as a security alert, bypass the quiet-hours filter. They still respect the channel list.
Computing quiet hours correctly
Quiet hours are defined in the user's local time and often cross midnight, such as 22:00 to 07:00. The check has to handle both a normal window and a wrapped one:
from dataclasses import dataclass, field
from datetime import datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo
@dataclass(frozen=True)
class NotificationEvent:
event_id: str
user_id: str
type: str
priority: str = "normal"
payload: dict = field(default_factory=dict)
def in_quiet_hours(now_utc, tz_name, start, end):
local = now_utc.astimezone(ZoneInfo(tz_name)).time()
if start <= end:
return start <= local < end
return local >= start or local < end
def quiet_hours_end(now_utc, tz_name, end):
"""Next UTC moment when the quiet window ends."""
local = now_utc.astimezone(ZoneInfo(tz_name))
candidate = local.replace(hour=end.hour, minute=end.minute,
second=0, microsecond=0)
if candidate <= local:
candidate += timedelta(days=1)
return candidate.astimezone(timezone.utc)
start, end = time(22, 0), time(7, 0)
night = datetime(2026, 11, 26, 3, 30, tzinfo=timezone.utc)
day = datetime(2026, 11, 26, 14, 0, tzinfo=timezone.utc)
print(in_quiet_hours(night, "America/New_York", start, end)) # True
print(in_quiet_hours(day, "America/New_York", start, end)) # False
print(quiet_hours_end(night, "America/New_York", end)) # 2026-11-26 12:00:00+00:00On some systems, ZoneInfo needs the tzdata package installed (pip install tzdata). Always pass timezone-aware datetimes. A naive datetime.now() uses the server's zone and silently gives wrong answers.
The window is half-open: the start is included and the end is excluded. That way 07:00 sharp counts as awake and no minute is covered twice.
Delay, downgrade, or drop
Quiet hours do not mean the same thing for every message. Choose a policy per notification type:
| Policy | Behavior | Good for |
|---|---|---|
| Downgrade | Deliver to in-app only | Social activity, order updates |
| Delay | Hold until `quiet_hours_end`, then send | Reminders, digests |
| Drop | Discard | Time-limited offers that expire before morning |
| Bypass | Send normally | Security alerts, fraud warnings |
Delaying needs the scheduling machinery from a later chapter: a delayed queue or a scheduled-job table keyed by delivery time. Dropping needs care. Record the drop with a reason so that delivery tracking can explain why the user never received it.
Where the check runs
Run the check once when the event is routed. Run it again just before sending if the message waited in a queue or schedule. A user may change preferences while a message is delayed, and a retry may land hours later. The second check is cheap compared with sending an unwanted SMS.
Common errors
- Using server time. Quiet hours computed in UTC wake up users in other timezones. Convert to the user's zone every time.
- Forgetting midnight wrap. The check
start <= local < endalone fails for 22:00 to 07:00, which matches no time at all. - Letting "critical" grow. If every team marks its events critical, quiet hours stop working. Restrict the priority to a short, reviewed list of types, and reject it from untrusted producers at ingestion.
- Checking only at ingestion. Preferences change, and delayed messages need the second check.
- Treating opt-out as a UI state. A global opt-out must be enforced in the router, not only hidden in the settings screen.
- Changing preferences without a cache invalidation. The user sees the toggle flip, but the router keeps the old value.
Exercise
A user in Asia/Tokyo has quiet hours 23:00 to 06:00. An event of type "friendrequest" with normal priority arrives at 16:30 UTC. The user enabled push and inapp for this type. Which channels does choose_channels return, and why?
Show answer
16:30 UTC is 01:30 the next day in Tokyo (UTC+9), which falls inside the 23:00 to 06:00 window. The window wraps midnight, so the check is local >= 23:00 or local < 06:00, and 01:30 satisfies the second part. The priority is normal, so the quiet-hours filter applies and only inapp remains. The function returns ["inapp"].