Sub topic 8
Integrating with delivery providers
This chapter assumes you know the architecture from earlier chapters: events enter a queue, and channel workers take them off it. It also assumes you can read short Python snippets and know the basic HTTP status code classes. Here we look at the last hop, where a worker calls a third-party service to deliver a message.
Why providers need their own layer
Your system rarely delivers messages itself. Push goes through Apple Push Notification service (APNs) or Firebase Cloud Messaging (FCM). SMS and email go through vendors such as Twilio, Amazon SES, or SendGrid. Each one has its own authentication, payload format, error codes, rate limits, and webhooks.
If workers call these APIs directly, vendor details spread through your code. Switching vendors, or adding a second one for failover, then means editing every worker. The fix is a provider adapter: a small class that hides one vendor behind an interface your system defines.
A common interface
The adapter interface takes a recipient, a rendered message, and an idempotency key. It returns a normalized result or raises one of two error types. Everything above the adapter sees only these types.
from dataclasses import dataclass
from typing import Protocol
class TransientError(Exception):
"""A failure worth retrying, such as a timeout, a 429, or a 5xx."""
class PermanentError(Exception):
"""A failure that retrying cannot fix, such as an invalid address."""
@dataclass(frozen=True)
class SendResult:
provider: str
provider_message_id: str
class ChannelProvider(Protocol):
name: str
def send(self, recipient: str, message: dict, idempotency_key: str) -> SendResult:
...The provider_message_id matters later. Vendors report delivery outcomes through callbacks that refer to their own message id, so you store it to match those callbacks to your records.
Classifying errors
The adapter's most valuable job is deciding whether a failure is transient or permanent. The retry logic depends on this decision, so it must not leak vendor-specific codes.
| Provider response | Class | Typical action |
|---|---|---|
| Timeout, connection reset | Transient | Retry with backoff |
| HTTP 429 (rate limited) | Transient | Retry, honoring `Retry-After` if present |
| HTTP 5xx | Transient | Retry, consider failover |
| HTTP 400 (bad request) | Permanent | Drop and log, fix the code or template |
| HTTP 401 or 403 | Permanent for this message, but urgent | Alert, since credentials are probably wrong |
| Invalid or unregistered address or token | Permanent | Mark the address or token invalid |
Treat unknown responses as permanent only after you have looked at what the vendor returns. Retrying an unknown error forever is a common way to flood a provider.
Writing an adapter
This adapter wraps a hypothetical email API. The HTTP call is injected as post, so you can test the adapter without a network.
class EmailAdapter:
name = "email-a"
def __init__(self, post, api_key):
self._post = post
self._api_key = api_key
def send(self, recipient, message, idempotency_key):
try:
status, body = self._post(
"/v1/send",
headers={
"Authorization": f"Bearer {self._api_key}",
"Idempotency-Key": idempotency_key,
},
json={"to": recipient, "subject": message["subject"], "text": message["body"]},
timeout=5,
)
except (TimeoutError, ConnectionError) as exc:
raise TransientError(str(exc)) from exc
if 200 <= status < 300:
return SendResult(self.name, body["id"])
if status == 429 or status >= 500:
raise TransientError(f"status {status}")
raise PermanentError(body.get("error", f"status {status}"))Note three details. The adapter sets a short timeout, because a worker blocked on a slow provider cannot serve other messages. It translates network exceptions into TransientError. It also forwards the idempotency key, so vendors that support the header can discard a repeated request.
Failing over to a second provider
Providers have outages. For critical channels such as SMS verification codes, you can configure an ordered list of adapters and fall back when the first one fails transiently.
def send_with_failover(providers, recipient, message, key):
last = TransientError("no providers configured")
for provider in providers:
try:
return provider.send(recipient, message, key)
except TransientError as exc:
last = exc
raise last
def down(path, headers, json, timeout):
return 503, {}
def up(path, headers, json, timeout):
return 202, {"id": "msg-9"}
primary = EmailAdapter(down, "key-a")
backup = EmailAdapter(up, "key-b")
backup.name = "email-b"
result = send_with_failover(
[primary, backup],
"[email protected]",
{"subject": "Order shipped", "body": "Order A-77 is on its way."},
"evt-1001:user-42:email",
)
print(result)Running this prints SendResult(provider='email-b', provider_message_id='msg-9'). A PermanentError is not caught, so it propagates. A second vendor would reject an invalid address too.
Where retries fit
The adapter makes one attempt and classifies the outcome. The worker owns retries, using the backoff logic from the retries chapter. Keeping the two apart gives you one place to tune retry behavior across all vendors. For example, you can retry a provider a few times before failing over, or fail over at once when its error rate is high.
Credentials and configuration
- Store API keys and push certificates in a secrets manager, not in code or in the notification payload.
- Load them when the worker starts and support rotation without a redeploy, since APNs tokens and many API keys expire.
- Use separate credentials for staging and production. Most vendors offer a sandbox, and you should point non-production environments at it so a test never texts a real person.
- Record the provider name and version of each adapter in logs so you can tell which integration produced a failure.
Provider limits and callbacks
Vendors cap requests per second, and a 429 response is how they tell you. Respect the cap before you hit it by sharing a token bucket among all workers that use the same account, as covered in the rate limiting chapter. Also check each vendor's payload limits, such as the maximum push payload size or SMS segment length, and validate them in the adapter so a bad message fails fast.
A successful send only means the provider accepted the message. Actual delivery, bounces, and spam complaints arrive later as webhooks or, for APNs and FCM, as error responses on later sends. Webhook handlers must verify the vendor's signature, return a 2xx quickly, and handle repeated deliveries, because vendors retry callbacks too. The tracking chapter covers what to do with these events.
The flow end to end
Common mistakes
- Letting vendor exception types or status codes reach the worker, which makes every vendor switch a code change in many places.
- Retrying permanent errors, which wastes quota and can get your account flagged.
- Using no timeout, or a timeout longer than the queue's visibility timeout, so a message is redelivered while the first attempt is still running.
- Logging full recipient addresses and message bodies. Log ids and the provider's response code instead.
- Treating "accepted by provider" as "delivered to the user".
Exercise
A worker calls your SMS adapter, and the provider returns HTTP 400 with the error "invalid phone number". What should the adapter do, and why should the worker not fail over to the backup SMS provider?
Show answer
The adapter should raise PermanentError, because the request itself is wrong and retrying will not change the result. The worker should not fail over because a second provider would reject the same number, and sending it would only spend quota. The system should instead mark the phone number as invalid and log the failure.
Exercise
The primary email provider times out after accepting a message. The worker fails over to the backup, and the user receives two emails. Name two measures that reduce this risk.
Show answer
Send the same idempotency key to both providers, so a vendor that supports the header can discard a repeat, and record the provider for each attempt. You can also use failover only for channels where a late duplicate costs less than a missed message, and retry the primary a few times before failing over.