Sub topic 8
Integrating with delivery providers
This chapter assumes you know the pipeline from the architecture chapter: events enter a queue, and channel workers take them off it. You should also be comfortable with HTTP status codes and short Python snippets.
Why providers sit behind an adapter
Your system rarely delivers messages itself. Push goes through APNs and FCM, SMS and email go through vendors, and each has its own API, authentication, payload format and error codes. A provider is a third party that can be slow, rate limited, or down.
Workers should not know any of this. Put an adapter in front of each provider. The adapter exposes one send method and translates the vendor's responses into your own result and error types.
Classifying errors
The adapter's most important job is to sort failures into two groups, because the retry logic depends on it.
| Provider response | Meaning | Adapter raises |
|---|---|---|
| 2xx | Accepted | Returns a result |
| 429, 5xx, timeout | Overloaded or unavailable | `TransientError` |
| 400, 401, 403 | Bad request or credentials | `PermanentError` |
| Invalid or unregistered recipient | Address or token is dead | `PermanentError` |
Retrying a permanent error wastes quota and delays other messages. Treating a transient error as permanent loses a notification.
from dataclasses import dataclass
class TransientError(Exception):
"""Worth retrying: timeout, 429 or 5xx."""
class PermanentError(Exception):
"""Not worth retrying: bad request or dead recipient."""
@dataclass(frozen=True)
class SendResult:
provider: str
provider_message_id: str
class EmailAdapter:
def __init__(self, http_post):
self._post = http_post # returns (status_code, body_dict)
def send(self, to, subject, body, idempotency_key):
try:
status, data = self._post(
{"to": to, "subject": subject, "body": body,
"idempotency_key": idempotency_key}
)
except TimeoutError as exc:
raise TransientError("provider timeout") from exc
if status == 429 or status >= 500:
raise TransientError(f"provider returned {status}")
if status >= 400:
raise PermanentError(f"provider rejected request: {status}")
return SendResult("example-email", data["id"])
def fake_post(request):
return 202, {"id": "msg-123"}
adapter = EmailAdapter(fake_post)
print(adapter.send("[email protected]", "Shipped", "Order A-77 shipped", "evt-1001:user-42:email"))The adapter passes an idempotency key to the provider when the provider supports one. Later chapters cover how that key prevents duplicates.
Other integration concerns
- Credentials. Keep API keys in a secrets manager, not in code, and rotate them without redeploying.
- Timeouts. Set a short connect and read timeout on every call. A hung call holds a worker slot.
- Failover. For critical channels, configure a secondary provider. Fail over only on transient errors, and expect the secondary to have its own sender identity and reputation.
- Provider message id. Store the id the provider returns. Delivery receipts and bounce callbacks refer to it, so you need it to track status later.
- Provider limits. Providers enforce their own quotas, so your workers must stay under them.
Exercise
A provider returns HTTP 400 with the message "recipient address is invalid". Should the adapter raise a transient or a permanent error, and why?
Show answer
Permanent. The request itself is wrong, so retrying will fail the same way. The worker should record the failure and, if appropriate, mark the address as invalid.