Sub topic 3
Avoiding Duplicate Notifications
Assume you understand HTTP APIs, databases, key-value stores, message queues, and short Python programs. A notification worker may process the same queue message more than once, so reliable delivery requires idempotency, meaning repeated processing has the same effect as processing once.
Preventing duplicates
Create an idempotency key from the event ID, user ID, and channel. Store it in a shared database or key-value store with an atomic “set if absent” operation and an expiry.
class Deduplicator:
def __init__(self):
self._seen = set()
def claim(self, key):
if key in self._seen:
return False
self._seen.add(key)
return True
dedup = Deduplicator()
key = "evt-1001:user-42:push"
if dedup.claim(key):
print("send")
else:
print("skip duplicate")In production, claim the key before sending, but design recovery for a worker that crashes after claiming and before sending. A short expiry or an explicit delivery record can prevent permanent suppression.
Controlling load
Rate limiting restricts how many notifications a user, tenant, channel, or provider can receive in a time period. Throttling protects providers and prevents a noisy event source from overwhelming workers. Keep delayed work in a queue rather than dropping it unless the product policy says it is disposable.
Urgent events should use a priority queue. Critical security alerts can bypass ordinary limits, but this exception must be narrow and auditable. Lower-priority reminders can wait.
Scheduling and batching
Schedule notifications for the recipient’s local time and avoid quiet hours. Batch compatible updates, such as “12 new messages,” when individual notifications would create noise. Do not batch events whose meaning or urgency would be lost.
Tracking delivery and reliability
Record states such as queued, sent, delivered, failed, and unknown. Provider feedback may arrive later through a webhook, so correlate it with a provider message ID. Retry transient failures with exponential backoff and jitter. Do not retry permanent errors such as an invalid address.
Scale workers independently by channel and isolate failing providers. A dead-letter queue holds messages that exceed retry limits for investigation.
Monitoring and privacy
Monitor queue age, send latency, delivery rate, retry count, duplicate-suppression count, and provider error rate. Alert on symptoms that affect users, not only on process failures.
Store only the data needed to deliver and audit a notification. Encrypt sensitive payloads, protect device tokens, honor consent and opt-outs, and define retention limits. Access to notification history should follow least privilege.
Exercise
Why should an idempotency key include the channel?
Show answer
The same event may legitimately be sent once by push and once by email; each channel needs its own delivery claim.