As web platforms grow, dispatching notifications (like emails, SMS alerts, and Slack webhooks) during client HTTP requests degrades response times. If a messaging API goes offline, client requests will fail or drop notifications. A resilient notification system delegates messaging to an asynchronous Notification Hub that processes jobs via worker queues.
By designing a central dispatcher in Python, we can route messages asynchronously across multiple API channels.
1. Implementing the Multi-Channel Message Router
The notification hub uses queue consumers to read message events and delegate them to channel adapters:
# message_router.py
import requests
class MessageRouter:
def __init__(self, email_key, sms_key):
self.email_key = email_key
self.sms_key = sms_key
def send_email(self, recipient, subject, body):
# Email API client delivery code
url = "https://api.emailprovider.com/v3/send"
headers = {"Authorization": f"Bearer {self.email_key}"}
payload = {"to": recipient, "subject": subject, "text": body}
return requests.post(url, json=payload, timeout=5)
def send_sms(self, phone_number, message):
# SMS API client delivery code
url = "https://api.smsprovider.com/sms"
payload = {"to": phone_number, "msg": message, "key": self.sms_key}
return requests.post(url, data=payload, timeout=5)
2. Handling Retry Loops and Fallbacks
Each delivery job runs inside a queue task. If an external service throws a timeout error, the worker catches the error and retries delivery using exponential backoffs, preventing data loss.