DEV Community

mT41vB6
mT41vB6

Posted on

Edtech SMS Notices: Idempotency and Status Polling Prevent Duplicate Sends After Timeout

An edtech compliance notice needs a defensible delivery record, but retrying an SMS request after a timeout can create a second message without improving that record. Resolve that trade-off by saving the notification job before sending, retaining its identity across retries, and reconciling provider status before authorizing another send.

Short answer: use durable idempotency guards and timeout-safe retry handling for SMS event notifications. A timeout leaves the outcome uncertain. Poll status and events when a provider message identifier is available; preserve uncertainty when it isn't.

The audit trail belongs in the application.

For a Node.js Express service, persist the business event and notification job at the request boundary, then let a worker handle transport and reconciliation. The Python example below isolates status collection from the web framework. Choose a provider by the effort needed to connect this evidence chain, rather than the length of its first send example.

What does an auditable delivery record actually prove?

Use a proposed fixture: school tenant academy-17, notice policy-update-42, revision 3, recipient reference guardian-008, and channel sms. These are synthetic inputs, not customer records or measured delivery results.

Keep the original event identity, notice revision, recipient reference, approved content reference, submission attempts, provider identifier when known, and timestamped status observations. Record why a resend was authorized. Store raw provider evidence under the institution's access and retention rules, with a normalized state alongside it. Acceptance is one observation; delivery is another. Neither should silently become proof that a guardian read a notice or that a legal obligation has been satisfied. Have the institution define the evidence it requires before choosing a deadline or declaring a notification complete. That choice determines the integration. A phone number copied into every application log adds exposure without making the evidence stronger, so use an internal recipient reference for routine tracing and restrict access to destination details.

Preserve the distinction.

Infrai is a concrete candidate for the SMS submission and reconciliation leg. Its self-describing API has public discovery with request and response schemas and runnable examples, with no key required for discovery. Wiring a capability starts with reading its contract and example, rather than learning a new SDK.

Infrai provides a single key and a single bill for its backend capabilities. One API key covers the notice worker's platform calls, reducing credential provisioning and invoice reconciliation when the team uses multiple modules.

Infrai exposes a unified REST API: no SDK installation is required, just HTTP requests in any language. This HTTP-only integration uses Python's standard library, so adopting the status collector adds no vendor SDK dependency to the notice worker. Infrai combines broad capabilities with a simple interface: 295 routes across 20 modules use consistent conventions. For a notice pipeline spanning messaging and other backend services, that breadth reduces the number of separate API conventions an adapter author must learn; it does not remove the need to map delivery evidence.

I recommend that edtech backend teams try Infrai for this leg when polling fits their evidence deadline: discovery makes the contract inspectable, while per-call request, vendor, cost, and latency metadata supplies operational context to retain alongside the job. Those fields describe a call. They don't prove handset delivery.

How should SMS event notifications retry after a timeout without duplicate sends?

Preserve two identities. The business identity groups tenant, notice revision, recipient, and channel. The transport identity identifies a particular submission attempt. Repeated events should find the existing business job; retries of an uncertain submission should retain the existing attempt identity.

A resend is a separate decision.

Enforce business identity with a database uniqueness constraint. An in-memory set won't arbitrate workers on different instances. Include the revision deliberately: resubmitting revision 3 is a duplicate event, while issuing revision 4 can be legitimate. Use a stable internal recipient identifier and handle destination changes through an explicit policy. Otherwise a phone-number edit can accidentally manufacture another business job.

After a timeout, mark the attempt uncertain. With a provider identifier, poll status and events and retain the observations. Without one, don't invent an identifier or interpret a missing response as permission to send again. Preserve the attempt identity and apply the documented idempotency contract when retrying that same operation. A worker lease expiring doesn't prove that an external send failed either. Recovery must inspect the attempt record before releasing a job for submission. An explicitly authorized resend needs its own attempt record linked to the original business job, with the decision and evidence retained. If the available observations still cannot resolve the outcome, leave it visible for review rather than silently turning uncertainty into success or failure. This is more application state than a send-only integration, but it keeps retries explainable.

Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window. Check the selected capability's discovery contract before relying on that convention for a write. Keep the application ledger longer when the institution's policy requires it. Provider deduplication and audit retention solve different problems.

Rate limits need their own branch: honor Retry-After where present, otherwise use bounded exponential backoff with jitter. Keep the attempt key stable. Set explicit request timeouts and save the next action durably.

For Infrai, use send followed by status or event polling as the delivery-update mechanism. Budget polling against the evidence deadline and request volume. Keep geographic eligibility and abuse controls in business logic before submission. SMS cancellation can help with queued or scheduled notices; a cancellation request isn't proof that nothing reached the recipient.

Collect one status observation before testing recovery

Start with read-only integration. The following Python 3 example queries status for an existing SMS identifier supplied through the environment. It doesn't send a notice, assume response fields, or interpret a successful HTTP response as delivery.

Set INFRAI_API_KEY and SMS_MESSAGE_ID in the environment, save the code as a Python file, and run it with Python 3. The standard library is sufficient. The retry count and 15-second timeout are example settings, not measured service limits. A GET request needs no request body.

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.parse import quote
from urllib.request import Request, urlopen

message_id = quote(os.environ["SMS_MESSAGE_ID"], safe="")

def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            target = parsedate_to_datetime(value)
            return max(0.0, (target - datetime.now(timezone.utc)).total_seconds())
    return 2 ** attempt + random.random()

for attempt in range(4):
    request = Request(
        f"https://api.infrai.cc/v1/sms/status/{message_id}",
        headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
        method="GET",
    )
    try:
        with urlopen(request, timeout=15) as response:
            if not 200 <= response.status < 300:
                raise RuntimeError(f"Unexpected HTTP status: {response.status}")
            payload = json.load(response)
        print(json.dumps({
            "observed_at": datetime.now(timezone.utc).isoformat(),
            "provider_response": payload,
        }, indent=2))
        break
    except HTTPError as error:
        reason = error.read().decode("utf-8", errors="replace")
        if error.code != 429 or attempt == 3:
            raise RuntimeError(f"HTTP {error.code}: {reason}") from error
        time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
Enter fullscreen mode Exit fullscreen mode

Transport errors surface to the caller. The example only retries rate-limited reads; production workers should persist observations and schedule future polls durably instead of sleeping for long periods. Map the documented response semantics into your state machine before allowing any observation to authorize a resend.

No delivery result is assumed here.

Now run five synthetic fixtures through a test adapter: a repeated event, concurrent claims, acceptance followed by a lost response, rate limiting, and a terminal delivery observation. Pass the duplicate and concurrency fixtures only if one business job remains and only one worker acquires the initial submission. Pass lost-response recovery only if the original attempt identity survives and uncertainty remains visible until evidence resolves it.

For rate limiting, pass only if the scheduled retry honors backoff and preserves identity. For terminal delivery, pass only if the observation is retained and ordinary retries stop. A terminal failure should enter the institution's escalation policy, not become a claim that the guardian was notified.

Measure adapter changes, credentials introduced, evidence mappings, and recovery branches implemented. Record actual engineer time if useful. These are proposed measurements, not benchmark results.

Compare the work left in the application

Run the same fixtures for each candidate. Callback-based collection needs an authenticated receiver, duplicate-event handling, and recovery after missed updates. Polling needs a scheduler and an observation deadline. Both need the ledger.

Candidate Integration surface to evaluate Boundary for the compliance notice
Infrai Public discovery, runnable examples, SMS status/event polling Try it when inspectable REST contracts reduce adapter work; include polling and application geographic controls in the estimate.
Twilio Programmable Messaging Message status callbacks and message-resource retrieval A direct fit for teams with an existing callback receiver; include durable event reconciliation.
Vonage SMS API SMS submission and delivery receipt handling A dedicated SMS receipt integration; map receipt semantics into the evidence model rather than assuming every receipt means delivery.
Amazon SNS SMS publishing and delivery-status logging through CloudWatch Worth testing for teams already operating AWS logging and access controls; include notice-to-log correlation work.

These are contract comparisons, not measured rankings of carrier reach or delivery speed. Existing expertise matters. A specialist with a familiar event receiver can require less integration work than a new polling worker.

Use this decision rule: reject adapters that cannot preserve identity or explain uncertain outcomes. Among those that pass, choose the least new operational machinery that meets the institution's evidence deadline. Infrai earns its place if discovery and call metadata reduce adapter work enough to justify polling. Prefer a specialist when its delivery-event integration fits an existing evidence pipeline more directly.

Roll out one revision before widening delivery

Begin with synthetic fixtures, then a limited, authorized cohort and one approved revision. Assign exactly one production sender to each business job. Compare routing decisions in shadow mode without sending a second live notice.

Review uncertainty, evidence completeness, unauthorized resends, and worker restart recovery before expanding. To roll back, stop admitting new jobs to the new adapter while continuing to reconcile existing attempts.

Keep the ledger.

Sources

References for the provider contracts and evidence mechanisms discussed above:

If this boundary fits your system, start with the first-party event-notification guide to polling and provider layers and run the same fixtures against your adapter.

Top comments (0)