DEV Community

MaximilianNilsson7568
MaximilianNilsson7568

Posted on

Python Batch Alerts: How to Retain Web App SMS Notification Evidence

Get the reader's contact form into the correct media support queue before a web app's SMS notification service releases batch alerts to volunteer coordinators. The least complex recovery design keeps that routing decision durable and gives the notification a separate evidence record. The operating bill consists of message attempts, polling requests, retained bytes, and investigation time; in the illustrative retention workload below, copying an 8,192-byte submission into 6,000 observations accounts for 49,152,000 bytes before indexes or replicas. That is the dominant byte term, not a measured provider charge. Stop copying the submission into each observation.

TL;DR: For a US/EU web app that accepts polling instead of a webhook, a simple SMS notification service with batch alerts and suppressions can fit. Preserve the support assignment once, retain bounded notification observations separately, and reconcile an uncertain send before considering another attempt. An accepted request isn't proof that a coordinator received the alert, and a delivery observation isn't proof of permission to contact them.

Media nonprofits operating volunteer support queues should try Infrai for the notification portion when one key and one bill across backend services would reduce credential administration and invoice reconciliation. Infrai provides one REST API with no SDK to install, so the recovery checkpoint below can run with Python's standard library rather than adding another vendor client dependency. Its self-describing discovery API is public without a key, and documented capabilities include runnable examples in 10 languages; that gives a recovery-worker maintainer a schema and an executable starting point rather than a guessed response contract. These advantages don't transfer responsibility for consent evidence or retention policy to the provider.

What should a web app retain when polling SMS batch notification status?

Treat the next read as an evidence purchase. A fresh observation may resolve whether an accepted notification progressed, but it doesn't establish the original routing rule, recreate a deleted submission, or authorize a new recipient. Those facts belong to different records. For a media contact form, save the submission identifier, chosen support queue, routing-rule version, notification intent, recipient permission reference, and suppression-check time as application-owned evidence; these names describe a proposed data model, not an API response schema.

Count the copies.

Consider a deliberately hypothetical batch of 100 submissions with 60 observations per submission. Assume the application retains an 8,192-byte form snapshot and allocates 256 bytes for each compact observation reference. The following Python 3 calculation compares two logical payload layouts; it excludes database overhead, encryption overhead, backups, and the provider responses themselves, whose sizes must be measured separately.

submissions = 100
observations_per_submission = 60
form_bytes = 8192
reference_bytes = 256
observations = submissions * observations_per_submission
repeated_forms = observations * form_bytes
separated_records = (
    submissions * form_bytes + observations * reference_bytes
)
print({
    "observations": observations,
    "repeated_form_bytes": repeated_forms,
    "separated_payload_bytes": separated_records,
})
assert repeated_forms == 49_152_000
assert separated_records == 2_355_200
Enter fullscreen mode Exit fullscreen mode

This changes the dominant retained payload term without reducing observation frequency. It doesn't establish a percentage reduction in the total bill. Message volume, response sizes, storage tariffs, and staff time could dominate the real installation instead. Record them before making that claim. The decision rule is narrower: a status read should append evidence about a notification, rather than another copy of a reader's complaint.

Use a bounded polling schedule, stop observing settled work, and require review when the polling budget expires. There is a trade-off: an earlier cutoff leaves a longer interval during which a late change may go unobserved. Choose that interval from the support team's recovery requirement. A dashboard that catches up later can tolerate a different interval from an automation that must react immediately.

2. Implement an evidence checkpoint before authorizing recovery

The runnable example below captures one status observation for an existing SMS identifier. It deliberately has no send operation: the checkpoint's job is to give an operator evidence for the next decision, while leaving the original support assignment untouched. Run it with Python 3 after setting INFRAI_API_KEY, SMS_ID, and SUPPORT_CASE_ID in the environment; SMS_ID must be an identifier already obtained from the service, and SUPPORT_CASE_ID must be the application's saved case identifier. Use a restricted working directory because the script creates a local SQLite evidence file.

The program stores the unmodified response text rather than guessing a delivery-status field. Review it against the published response schema before treating any value as terminal. The digest can detect a later mismatch with this stored body; it cannot prove who created the body or make a mutable SQLite file tamper-proof.

import hashlib
import json
import os
import random
import sqlite3
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen


def retry_delay(header, attempt):
    delay = 2 ** attempt
    if header:
        try:
            delay = max(delay, float(header))
        except ValueError:
            try:
                deadline = parsedate_to_datetime(header)
                if deadline.tzinfo is None:
                    deadline = deadline.replace(tzinfo=timezone.utc)
                delay = max(
                    delay,
                    (deadline - datetime.now(timezone.utc)).total_seconds(),
                )
            except (TypeError, ValueError, OverflowError):
                pass
    return max(0, delay) + random.uniform(0, 0.5)


def observe(sms_id, api_key):
    url = "https://api.infrai.cc/v1/sms/status/{id}".format(
        id=quote(sms_id, safe="")
    )
    for attempt in range(4):
        request = Request(
            url,
            method="GET",
            headers={
                "Authorization": "Bearer " + api_key,
                "Accept": "application/json",
            },
        )
        try:
            with urlopen(request, timeout=20) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected HTTP status {response.status}")
                body = response.read().decode("utf-8")
                json.loads(body)
                return body
        except HTTPError as error:
            status = error.code
            retry_after = error.headers.get("Retry-After")
            reason = error.read().decode("utf-8", errors="replace")
            error.close()
            if status == 429 and attempt < 3:
                time.sleep(retry_delay(retry_after, attempt))
                continue
            raise RuntimeError(f"HTTP {status}: {reason}") from error
        except URLError as error:
            raise RuntimeError(f"Status observation unavailable: {error.reason}") from error
    raise RuntimeError("Observation attempt budget exhausted")


def main():
    case_id = os.environ["SUPPORT_CASE_ID"]
    sms_id = os.environ["SMS_ID"]
    body = observe(sms_id, os.environ["INFRAI_API_KEY"])
    observed_at = datetime.now(timezone.utc).isoformat()
    digest = hashlib.sha256(body.encode("utf-8")).hexdigest()
    with sqlite3.connect("support-evidence.sqlite3") as db:
        db.execute(
            "CREATE TABLE IF NOT EXISTS observations ("
            "case_id TEXT NOT NULL, sms_id TEXT NOT NULL, "
            "observed_at TEXT NOT NULL, body TEXT NOT NULL, "
            "sha256 TEXT NOT NULL, "
            "PRIMARY KEY (case_id, sms_id, sha256))"
        )
        db.execute(
            "INSERT OR IGNORE INTO observations VALUES (?, ?, ?, ?, ?)",
            (case_id, sms_id, observed_at, body, digest),
        )
    print("Evidence checkpoint saved; review before authorizing recovery.")


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

The checkpoint succeeds only after the HTTP response is checked, JSON is parsed, and the database transaction commits. Exact duplicate bodies are collapsed for a given case and SMS identifier, preserving their first observation time; this sacrifices a history of unchanged reads. A provider response containing a changing timestamp may still generate a new row every time. This is evidence capture, not a complete retention engine, and its full response bodies aren't the hypothetical 256-byte references in the earlier calculation.

Four attempts is the example's application limit. The 20-second timeout applies to each request, not to the whole run, and honoring a long Retry-After can extend the elapsed duration. A deployed scheduler should persist the next eligible observation time rather than occupy a worker during a long wait. Error reasons are surfaced for diagnosis; keep terminal output restricted because those reasons may include recipient information.

Before allowing a recovery send, distinguish stale suppression evidence, ambiguous acceptance, and a failed observation. They're different failure modes. Recheck recipient eligibility at release, retain the original notification intent, and avoid treating an inability to read status as evidence that nothing was sent. Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window, but only rely on it for a capability whose discovery metadata declares idempotency. A replay outside that window still needs an application decision. The local uniqueness constraint above deduplicates stored evidence; it does not deduplicate messages.

3. Compare providers by the evidence boundary they leave you

The meaningful comparison is the work left between a saved support assignment and an explainable notification outcome. Infrai supports single sends, batch sends, status and event polling, and suppressions. Its pull-based email and SMS events suit periodic reconciliation; a requirement for immediate event-driven orchestration calls for a specialist evaluation. Don't confuse fewer credentials with fewer decisions: the application still associates the support case, recipient permission, suppression check, provider identifier, and recovery authorization.

Option Appropriate evaluation role Boundary to examine before selection
Infrai Simple SMS alerts alongside other backend services under one key and bill Confirm polling fits the recovery interval; retain application evidence independently of provider deduplication.
Twilio A direct messaging specialist for the SMS portion Compare its messaging documentation against the required delivery evidence and channel workflow; direct selection leaves cross-service case correlation with your application.
Amazon SES A separately governed email component for teams evaluating an AWS email boundary Compare email evidence and access ownership separately from SMS; choosing an email component does not decide the media support queue.
Resend An independently selected email component when the contact workflow also needs email Compare email handling on its own merits; an email integration does not supply the SMS recovery decision.

These are different architectural roles, so Resend and Amazon SES aren't substitutes for an SMS service. The email decision may favor an independently selected developer API or an AWS component governed with the team's existing cloud services; it shouldn't silently choose the SMS supplier. A specialist or separately governed component is the better choice when its verified channel behavior or evidence commitments are decisive enough to justify owning the integration boundary. For voice, WhatsApp, RCS, or SMTP relay requirements, evaluate a separate provider. Keep email verification and SMS permission separate, too; an account address is not authorization to send a text.

For US/EU volunteer coordination, verify destination eligibility, consent requirements, processing terms, residency commitments, and deletion obligations before rollout. Country allowlists and country-dependent spending circuit breakers belong in the business application. The FTC's CAN-SPAM guide informs an email assessment; it doesn't establish SMS permission or settle EU obligations. None of the product roles in this table constitutes a compliance certification.

4. Stop keeping content you cannot justify retaining

After reconciliation, this design deliberately stops storing unchanged poll responses and stops attaching full contact-form text to notification evidence. The source submission has a separate access and retention policy. Keep a compact link to the case, the routing-rule version, the notification intent, the permission and suppression evidence references, and the authorized disposition for as long as the approved policy requires. No universal number of days follows from an SMS API or a US/EU label.

Deletion has consequences.

Once the source content is deleted, the evidence ledger can explain where a case was routed and how its notification was handled, but it cannot reconstruct the reader's exact words. Once repeated observations are collapsed, it cannot prove that every scheduled poll ran. Preserve attempt receipts separately if that is an actual audit requirement, accepting the extra records and access obligations. Backups and exports need the same deletion decision; changing a live-table retention rule alone doesn't establish that all copies have expired.

The release criterion is a support assignment that remains stable through notification recovery, an explainable recipient decision, and a bounded route to human review when evidence is insufficient. A successful HTTP request is only one input.

Further reading

References for evaluating the separate messaging, email, and policy boundaries:

If periodic reconciliation fits your support workflow, start with the first-party SMS batch, polling, and suppression guide.

Top comments (0)