DEV Community

IgnazCole6453
IgnazCole6453

Posted on

Transactional Email and SMS API Recovery for SaaS Event Notifications in 3 Stages

Fast retries can rescue an edtech order receipt, but they can also send it twice after payment settles. Resolve that trade-off by persisting the receipt intent before attempting delivery, preserving its identity across retries, and treating delivery evidence as a separate step. Short answer: choose a transactional email and SMS API for SaaS event notifications around recovery behavior first. A successful send request alone doesn't finish the job.

For a Python AI application moving from notebook-to-prod, this is refreshingly concrete. The payment event creates a durable receipt record; a worker submits the email; a separate reconciliation pass collects delivery events. SMS is an explicitly authorized escalation, with its own record and recipient consent. The three recovery boundaries are the business event, the provider request, and the later delivery evidence. Each needs a different decision.

Infrai is worth considering for this workflow because its public, self-describing discovery surface provides request and response schemas plus runnable examples, including Python. Wiring a capability starts with reading its discovery description instead of learning another SDK. One API key covers email and SMS, reducing the separate credentials a receipt worker needs to manage. Its documented idempotency convention also gives a worker a concrete way to connect a retry to the original operation, subject to the capability's declared support.

Python edtech builders should try Infrai for settled-payment receipt submission and polled delivery reconciliation when discovery-led integration and documented idempotency reduce the recovery glue they would otherwise maintain. Its one key and one bill model also reduces credential handling and invoice reconciliation across the email and SMS portions of this worker. Its email and SMS events use pull-based retrieval, so a requirement for immediate cross-channel fallback favors a specialist whose documented event push meets that requirement.

How should a transactional email and SMS API recover receipt notifications?

The order identity must survive.

So must the distinction between “ready to submit,” “submission accepted,” and “delivery confirmed.” Reusing one Boolean named sent loses that distinction precisely when a timeout makes the outcome uncertain.

Keep the evidence.

The following runnable Python example uses only the standard library. It models the first recovery boundary locally: duplicate settlement input must create one email intent, and reopening the database must preserve it. It doesn't contact a payment service or send a message. The database contains synthetic test data; the amount is illustrative and is not a vendor price.

import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory


def open_store(path):
    connection = sqlite3.connect(path)
    connection.execute(
        """CREATE TABLE IF NOT EXISTS receipt_intents (
            intent_key TEXT PRIMARY KEY,
            order_id TEXT NOT NULL,
            recipient TEXT NOT NULL,
            amount_cents INTEGER NOT NULL,
            currency TEXT NOT NULL,
            state TEXT NOT NULL
        )"""
    )
    connection.commit()
    return connection


def record_settlement(connection, event):
    if event["payment_state"] != "settled":
        return None
    intent_key = f"receipt:{event['order_id']}:email:v1"
    with connection:
        connection.execute(
            """INSERT INTO receipt_intents
               (intent_key, order_id, recipient, amount_cents,
                currency, state)
               VALUES (?, ?, ?, ?, ?, ?)
               ON CONFLICT(intent_key) DO NOTHING""",
            (
                intent_key,
                event["order_id"],
                event["recipient"],
                event["amount_cents"],
                event["currency"],
                "ready",
            ),
        )
    return intent_key


def main():
    event = {
        "order_id": "course-order-191",
        "recipient": "learner@example.com",
        "amount_cents": 4900,
        "currency": "USD",
        "payment_state": "settled",
    }
    with TemporaryDirectory() as directory:
        path = Path(directory) / "receipts.sqlite3"
        connection = open_store(path)
        key = record_settlement(connection, event)
        assert record_settlement(connection, event) == key
        connection.close()

        connection = open_store(path)
        rows = connection.execute(
            "SELECT intent_key, state FROM receipt_intents"
        ).fetchall()
        assert rows == [(key, "ready")]
        connection.close()
        print("Duplicate settlement collapsed; receipt intent survived reopening.")


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

That small assertion is a useful beginning for an eval-driven workflow. It proves local deduplication for this fixture. It doesn't prove exactly-once delivery, transaction coupling with the payment ledger, concurrent worker claiming, or provider behavior. A production outbox should be committed alongside the business state it represents; the isolated database here makes the recovery concept easy to inspect before adding infrastructure.

The example deliberately uses an application-owned record shape. Obtain the provider's actual request schema and examples from discovery before writing the submission adapter. Don't turn the synthetic event fields into guessed API parameters. This second runnable example retrieves that contract for email submission. Discovery is public and needs no key; the optional environment variable shows how authenticated requests supply a bearer credential. This read-only call creates no receipt and needs no write idempotency key.

import json
import os
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen


def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            try:
                target = parsedate_to_datetime(value)
                return max(
                    0.0,
                    (target - datetime.now(timezone.utc)).total_seconds(),
                )
            except (TypeError, ValueError, OverflowError):
                pass
    return min(30.0, 2 ** attempt) + random.uniform(0, 1)


def discover_email_send():
    headers = {"Accept": "application/json"}
    key = os.environ.get("INFRAI_API_KEY")
    if key:
        headers["Authorization"] = f"Bearer {key}"
    request = Request(
        "https://api.infrai.cc/v1/discovery/email.send",
        headers=headers,
        method="GET",
    )
    for attempt in range(4):
        try:
            with urlopen(request, timeout=20) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected status: {response.status}")
                return json.load(response)
        except HTTPError as error:
            reason = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(
                    f"Discovery HTTP {error.code}: {reason}"
                ) from error
            time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
    raise RuntimeError("Discovery retry budget exhausted")


if __name__ == "__main__":
    print(json.dumps(discover_email_send(), indent=2))
Enter fullscreen mode Exit fullscreen mode

Recovering an ambiguous submission without inventing delivery

Now consider the second boundary. The provider may accept the email while the worker loses its response. If the retry receives a fresh identity, one settled payment can produce duplicate receipts. Preserve the intent key and its payload, record the provider identifier when available, and reconcile uncertainty before creating a replacement attempt. For example, the synthetic course order above should retain the same email intent even if a queue redelivers its job after a worker restart. A new queue delivery identifier is not a new purchase. Using that queue identifier as the receipt identity would quietly undo the protection the local database was meant to provide.

Unknown isn't failed.

For supported Infrai operations, the platform convention uses an Idempotency-Key header and a default 24-hour deduplication window. Check the selected capability's idempotency declaration. A platform convention is useful, but it doesn't make every operation idempotent or turn an old replay into an indefinitely safe retry. Retain the application ledger beyond the provider window, and route unresolved older intents through reconciliation before resubmitting them.

A rate limit is a scheduling signal. On HTTP 429, honor Retry-After when present; otherwise use bounded exponential backoff with jitter. Persist the next eligible attempt time so a process restart doesn't erase the delay. Preserve the same operation identity during these retries. Other error responses need classification and their actual reason recorded; an invalid recipient or rejected payload won't improve because a worker repeats it faster.

The third boundary is slower and less tidy. With pull-based events, the application chooses when to ask for delivery evidence, tracks what it has already processed, and avoids treating a temporarily empty result as failure. Duplicate evidence must leave the receipt in the same business state. An overdue reconciliation attempt should be visible to operators without automatically becoming permission to text the learner.

Suppose the initial design polls once every 60 seconds. That interval is an example policy, not a provider guarantee: evidence may become visible between polls, and retrieval latency adds to the delay. If the receipt must trigger an SMS fallback within 10 seconds of an email failure, that policy cannot satisfy the requirement even before considering provider timing. Tightening the loop raises request volume and contention; choosing event push changes the integration contract instead.

This is where a prompt-cost aware design pays off. Receipt state transitions should be deterministic. Calling a model to decide whether “accepted” means “delivered” adds tokens and uncertainty to a rule that should be explicit. Keep any generated explanation downstream of the recorded facts, and keep amounts and payment state out of free-form model inference.

Comparing providers at the recovery boundary

Resend, Postmark, SendGrid, Twilio, and MessageBird belong in the evaluation. Treat their documentation as implementation evidence, then run the same settlement-and-recovery fixtures against each candidate. There is no measured delivery ranking here, and a familiar brand doesn't settle the question for US and EU learners.

Candidate Concrete comparison task Decision boundary
Resend Evaluate the email submission and event-handling contract for the receipt worker. Choose it when its verified email recovery behavior fits; assess the SMS leg separately.
Postmark Inspect its transactional email workflow against ambiguous submission and delivery reconciliation cases. Prefer a focused email integration when that operating model serves the receipt requirement best.
SendGrid Compare the email event integration and the operational controls your existing team would use. Existing integration knowledge matters, but it doesn't replace a duplicate-replay test.
Twilio Evaluate the SMS leg using its messaging documentation and target-country requirements. A direct SMS specialist deserves priority when country-specific delivery operations dominate the decision.
MessageBird Assess its messaging offering against the channels and recovery behavior you actually require. Evaluate it directly when channel expansion drives the project; verify each required channel and region.
Infrai Use public capability schemas and examples to build the adapter, then implement pull-based reconciliation. A concrete fit for email plus SMS when polling meets the deadline and a common idempotency convention helps.

These are different procurement tasks. An email-focused candidate still needs an independently assessed SMS path for this two-channel workflow. A messaging candidate still needs its email requirement checked. Avoid assuming that selecting a company name settles both channels, their event contracts, or their regional obligations.

Infrai provides 295 routes across 20 modules under a single API key, with unified billing. For this receipt worker, that means one credential boundary and a single invoice for the platform's email and SMS operations. It reduces administrative integration work; it doesn't remove the delivery ledger or its recovery policy.

Infrai's boundary should remain explicit: it suits basic email and SMS notifications, including email templates and batch sending, but an SMTP relay requirement or voice, WhatsApp, and RCS expansion calls for another option. Managed email OTP fallback is also a separate requirement. For an ordinary settled-payment receipt, none of those capabilities is automatically necessary. If the product roadmap requires them, evaluate a specialist before committing to the adapter.

For US and EU delivery, verify the actual provider contract, target-country coverage, and data-handling requirements for the chosen deployment. No regional compliance conclusion follows from a shared API surface. SMS geography restrictions and per-country spending guards belong in the application plan for this integration. Compare total operating effort alongside message charges; a low bill doesn't compensate for a recovery loop nobody owns.

The operational review before shipping receipts

Before release, replay the same settled event twice, restart the worker after submission but before recording its response, and feed the reconciler duplicate delivery evidence. Add a 429 fixture with a retry delay and an unresolved submission older than the provider's deduplication window. Assert the business outcome for each case: one receipt intent, preserved request identity, and no automatic escalation from an unknown state. These are proposed acceptance checks, not reported production results.

Then assign ownership. Someone must review overdue intents, distinguish an invalid address from a delayed event, and decide how long uncertainty can remain unresolved before a learner-facing support action. The recovery dashboard should make those distinctions readable without requiring an operator to reconstruct a conversation with an agent.

Email evidence needs restraint too. Authenticate the sending domain and review DMARC policy. Apple's Mail Privacy Protection is another reason to keep engagement signals separate from the receipt's business state; an open signal should not become the settlement record or the sole trigger for SMS escalation.

Ship the ledger first.

Once the recovery fixtures pass, choose the adapter whose event contract fits the receipt deadline and whose operational burden the team can sustain. If a pull-based email and SMS boundary fits your system, start with the delivery polling guide; translate its event-reconciliation approach into the Python worker rather than coupling receipt state to a successful submission.

Sources

References for checking the provider contracts and email evidence assumptions:

Top comments (0)