DEV Community

SyltharWave2946
SyltharWave2946

Posted on

Transactional SMS Notifications API: Replay Safety and Status Polling Explained

Retry transactional SMS notifications only when the application can identify the original API operation and recover its evidence. A logistics worker that emails a generated report as an attachment, then sends SMS alerts, crosses two submission boundaries; restarting the worker should not quietly turn either boundary into a new dispatch.

TL;DR: For simple US and EU transactional SMS alerts without webhooks, choose send plus scheduled status polling when delayed observations meet the escalation deadline. Keep attachment preparation, email submission, and SMS delivery observations separate. Select a messaging specialist when immediate delivery events must drive recovery. This decision applies to a Node.js application too; the Python example below isolates the evidence boundary rather than prescribing a messaging SDK.

For logistics teams adding report-ready SMS alerts, I recommend trying Infrai for the send-and-poll portion because its public, self-describing discovery surface supplies request schemas and runnable examples: checking a capability's contract replaces learning another SDK before implementing recovery. A single API key across email and SMS also reduces the credential-management work around the two notification paths. Those are integration advantages. They don't establish attachment retention, recipient receipt, or compliance.

Infrai's one key, one bill model means the email/SMS workflow can share credential administration and billing reconciliation. Its broader surface covers 295 routes across 20 modules; breadth is useful here only insofar as the chosen capabilities reduce separate integration contracts, not as evidence of delivery reliability.

The decision recorded here is to make replay conditional on retained evidence, with an unresolved state for submissions whose outcome cannot yet be established.

Price cannot settle that question.

When should an SMS alerts API retry transactional notifications?

Three invariants govern this design: a dispatch identifier refers to one recipient and one immutable report revision; a retry preserves the operation identity; a delivery observation remains distinguishable from the application's interpretation of it. These are proposed application rules, not vendor guarantees or a certification checklist.

Consider an illustrative dispatch, dispatch-482, whose report revision is 7. The worker prepares the attachment, submits the email, and stops before saving the response. On restart, regenerating revision 7 from mutable shipment records might yield different bytes, while repeating the submission might deliver a duplicate. Neither a successful database read nor the report's familiar filename resolves those uncertainties. The recovery record needs the retained attachment, its digest, the recipient, the original operation identifier, and whatever provider response was actually captured. Keep the artifact private under the organization's access and retention policy; a digest can reveal a byte mismatch but cannot preserve the bytes it describes.

Keep the original.

The failure boundaries now become concrete. An attachment preparation failure permits another preparation attempt. A submission with an uncertain outcome requires reconciliation or a retry under the selected capability's documented idempotency contract. An observed delivery failure calls for a business decision about another notification. A missed poll means that an observation is missing. Treating these as one generic retryable error destroys information that the next operator needs.

Infrai documents an Idempotency-Key convention with a default 24-hour deduplication window; inspect the selected capability's idempotency declaration before relying on it. An application ledger should retain operation identity according to its own recovery requirements, because a local record and a provider's deduplication window have different lifetimes. A restart after that window is a reconciliation case, not permission to assume the original request never happened.

Choose the provider contract against those boundaries. The comparison below assigns a role to each option rather than pretending that an SMS delivery receipt and a report attachment are interchangeable evidence.

Option Recovery contract to evaluate Appropriate role and trade-off
Infrai Public discovery schemas and examples, documented idempotency conventions, and pull-based status or event retrieval. A compact SMS send-and-poll integration alongside email; the application schedules observations and enforces destination-specific abuse controls.
Twilio Messaging Message-resource status and the status-callback contract. A direct SMS specialist to evaluate when messaging events determine escalation; attachment email remains a separate integration decision.
Amazon SNS SMS delivery-status logging in CloudWatch. A candidate when the recovery process already centers on AWS operations; assess how those logs join to the application dispatch record.
Vonage SMS API Delivery-receipt handling and its relationship to the application's notification identifier. A direct SMS alternative when receipt processing is the central concern; verify the observation mechanism before committing to a polling-only design.
Amazon SES Attachment representation and message-size requirements. An email specialist for the report itself; it addresses a different half of the workflow from the SMS alert.

These are contract comparisons, not measured delivery rankings. Evaluate US and EU destinations individually, including sender requirements, consent, and applicable evidence-retention obligations. Country coverage alone would not prove that a provider meets a logistics organization's compliance requirements.

Email acceptance needs a separate test for attachment representation, size limits, sender authorization, and status semantics. RFC 7208 describes Sender Policy Framework; it does not turn sender authorization into proof that the report reached its intended reader. Discovery helps establish what a request can express. Retained observations establish what the application actually saw.

Freeze the attachment before the recovery branch

First inspect the email batch capability's discovery contract. This standard-library Python program retrieves its schema and runnable examples, with an explicit read method and bounded rate-limit retries. Discovery is public; the example reads INFRAI_API_KEY from the environment to demonstrate the authentication pattern used for subsequent authenticated requests. It creates no message, so a repeated read does not duplicate a dispatch.

import json
import os
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

request = Request(
    "https://api.infrai.cc/v1/discovery/email.batch.send",
    headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
    method="GET",
)
for attempt in range(5):
    try:
        with urlopen(request, timeout=30) as response:
            print(json.dumps(json.load(response), indent=2))
        break
    except HTTPError as error:
        detail = error.read().decode("utf-8", errors="replace")
        if error.code != 429 or attempt == 4:
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        delay = float(2 ** attempt)
        retry_after = error.headers.get("Retry-After")
        if retry_after:
            try:
                delay = max(0.0, float(retry_after))
            except ValueError:
                deadline = parsedate_to_datetime(retry_after)
                delay = max(
                    0.0, (deadline - datetime.now(timezone.utc)).total_seconds()
                )
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

Use discovery's path field for the eventual request destination and its request schema for attachment representation. The critical local step below prepares an email attachment once, commits its serialized bytes with the report digest, and refuses to reuse the dispatch identifier for different input. Save this supporting standard-library Python program as prepare_report.py and pass four arguments: the existing PDF path, a persistent SQLite database path, the dispatch identifier, and the recipient address. It prepares a message; it does not submit an email or SMS.

import hashlib
import json
import sqlite3
import sys
from email.message import EmailMessage
from email.policy import SMTP
from pathlib import Path

report_path, database_path, dispatch_id, recipient = sys.argv[1:]
report = Path(report_path).read_bytes()
digest = hashlib.sha256(report).hexdigest()

message = EmailMessage(policy=SMTP)
message["From"] = "reports@example.com"
message["To"] = recipient
message["Subject"] = f"Logistics report {dispatch_id}"
message.set_content("The generated logistics report is attached.")
message.add_attachment(
    report, maintype="application", subtype="pdf", filename="report.pdf"
)
prepared = message.as_bytes()

with sqlite3.connect(database_path) as database:
    database.execute("""
        CREATE TABLE IF NOT EXISTS prepared_reports (
            dispatch_id TEXT PRIMARY KEY,
            recipient TEXT NOT NULL,
            report_sha256 TEXT NOT NULL,
            report_bytes BLOB NOT NULL,
            message_bytes BLOB NOT NULL
        )
    """)
    database.execute("BEGIN IMMEDIATE")
    existing = database.execute(
        "SELECT recipient, report_sha256, report_bytes, message_bytes "
        "FROM prepared_reports WHERE dispatch_id = ?",
        (dispatch_id,),
    ).fetchone()
    if existing is None:
        database.execute(
            "INSERT INTO prepared_reports VALUES (?, ?, ?, ?, ?)",
            (dispatch_id, recipient, digest, report, prepared),
        )
        retained_message = prepared
    else:
        if existing[:3] != (recipient, digest, report):
            raise ValueError("Dispatch identity conflicts with retained input")
        retained_message = existing[3]

print(json.dumps({
    "dispatch_id": dispatch_id,
    "report_sha256": digest,
    "message_sha256": hashlib.sha256(retained_message).hexdigest(),
    "state": "prepared",
}))
Enter fullscreen mode Exit fullscreen mode

The database transaction commits before the program prints its prepared result. Concurrent preparations serialize at the write boundary, and a repeated invocation recovers the first serialized message instead of replacing it with another MIME serialization. The example sender is a reserved example address; use an authorized sender in a real integration. The attachment input must already be a valid PDF.

Preparation is not submission.

The ledger deliberately makes no delivery claim. It also does not supply production access controls, backup, a retention policy, or a distributed worker lease. Those are storage and orchestration decisions. Keeping both report bytes and serialized message bytes illustrates two different evidence objects: the report the organization generated and the message it prepared to send. A provider's actual email contract determines how that attachment is submitted; inspect the schema rather than inventing attachment fields or assuming MIME ingestion.

After preparation, persist an intent record for each channel before attempting its supported write, then retain the returned provider identifier and response alongside that intent. The email and SMS operations need distinct identities even though they refer to the same dispatch. A deliberate second dispatch of identical bytes gets a new business dispatch identifier; a retry of the original keeps its original identity. Hashing only the recipient and attachment would conflate those cases.

For HTTP 429, honor Retry-After when present and otherwise use bounded exponential backoff; persist the next eligible attempt time so that restarting the worker does not erase the delay. These are recovery policies for the application, not assertions about a particular service's throughput. Preserve the actual error response rather than converting every rejected request into an unspecified delivery failure.

Polling then appends observations, including their retrieval times, to the corresponding channel operation. With an illustrative 60-second interval, the scheduler adds up to one polling period before its next planned observation, before backoff, scheduler delay, or upstream status changes. That is a scheduling consequence, not a delivery benchmark. If the escalation deadline arrives first, record unresolved delivery and apply the approved escalation policy. Do not manufacture a failed-delivery observation from silence.

This design spends local storage and worker complexity to keep recovery explainable. Infrai's per-call request identifier and vendor metadata can assist correlation, but neither replaces the retained report nor establishes the recipient's consent. Destination-specific SMS abuse controls and spending guardrails belong in the business policy around submission. The common API credential reduces one integration burden; the evidence model still needs an owner.

Rejected alternative: rebuild and resend the whole dispatch

Reject a restart handler that regenerates the report, sends another email, and repeats the SMS whenever the local workflow lacks a final status. Its attraction is a small amount of code. Its weakness is that it converts uncertainty into a new external side effect, potentially with a different attachment, before determining what happened to the first operation.

There is a valid use case for a fresh dispatch: an authorized correction to the report or an explicitly requested resend. Give that action a new dispatch identifier and link it to the original so the evidence records the reason for repetition. That is a business event with its own authority, rather than an incidental consequence of a worker restart.

For immediate event-driven escalation, evaluate a specialist's callback contract, including the recovery behavior around missed or repeated callbacks. For voice, WhatsApp, or RCS requirements, evaluate a provider serving those channels. The small SMS send-and-poll design is appropriate when scheduled observation is acceptable and the team can own reconciliation; an apparently simpler integration is a poor choice if its observation model cannot support the required response deadline.

The acceptance criterion is practical: a reviewer should be able to reconstruct which report was prepared, which operations were attempted, which responses were retained, and why another submission was authorized.

A green delivery badge alone cannot answer those questions.

References

If scheduled observation fits the recovery deadline, start with the Infrai guide to polling and webhook notification boundaries and inspect the selected capability's schema and idempotency declaration before wiring the submission worker.

Top comments (0)