Sub topic 2
Templates and Localization in a Notification System
Assume you understand HTTP APIs, databases, key-value stores, message queues, asynchronous workers, and short Python programs. This chapter focuses on the delivery path after an application creates a notification event.
Templates and localization
A template separates message content from application code. Store templates by notification type, channel, and locale. For example, order_shipped might have different templates for email and push notifications.
Select the locale from the user profile, then fall back to a default locale. Render only trusted variables from the event payload. Do not allow arbitrary template code to execute.
templates = {
("order_shipped", "email", "en"): "Order {order_id} has shipped.",
("order_shipped", "email", "es"): "El pedido {order_id} ha sido enviado.",
}
def render(event_type, channel, locale, values):
template = templates.get(
(event_type, channel, locale),
templates[(event_type, channel, "en")],
)
return template.format(**values)Queues and channel workers
The event-ingestion API should acknowledge a valid event quickly. It publishes the event to a durable queue instead of calling every provider during the request.
Workers consume queued jobs and perform channel-specific work. An email worker understands email providers, while a push worker understands device tokens. This separation limits failures and lets each channel scale independently.
Provider integration and device tokens
Use a provider adapter with a common interface, such as send(message). The adapter translates your internal message into the provider’s API format and normalizes responses. Store provider message IDs and classify failures as transient or permanent.
Push providers require device tokens. Store tokens per user and device, record their platform, and update their last-seen time. Remove or disable tokens when a provider reports that they are expired or invalid. Never treat a token as permanent identity.
Retries and backoff
Retry timeouts and temporary server errors. Do not retry invalid addresses, revoked tokens, or rejected content. Exponential backoff increases the delay after each attempt. Jitter adds randomness so many workers do not retry together.
import random
import time
def send_with_retry(send, attempts=4):
for attempt in range(attempts):
try:
return send()
except TimeoutError:
if attempt == attempts - 1:
raise
delay = random.uniform(0, min(30, 0.5 * 2**attempt))
time.sleep(delay)Exercise
Why should channel workers be separate from the event-ingestion API?
Show answer
They keep provider latency and failures out of the request path, and each channel can scale and retry independently.