DEV Community

BrennanCross2167
BrennanCross2167

Posted on

Gaming Notifications Explained — SMS First, Email Fallback, and Delivery Polling Logic

A gaming operations team generates a report when a tournament travel itinerary changes. The urgent part is getting the change noticed; the durable deliverable is the report attached to an email. Those jobs need separate completion rules. An SMS receipt cannot establish that the attachment reached anyone.

TL;DR: Use SMS first for the urgent notification, poll its delivery status, and trigger email fallback after an explicit failure or a bounded waiting period. Send the report email independently when an attachment is required, even if SMS succeeds. Choose an integration by the orchestration it leaves your backend to own: receipt normalization, duplicate prevention, and report revision checks matter more than the length of the send call.

This applies to US/EU recipients, with country eligibility and communication preferences checked before sending. The same design fits an existing Node.js notification worker; the small Python example below isolates the decision rule without assuming a provider's request schema.

How should urgent event notifications use SMS first with email fallback?

Start with the artifact. For an illustrative event, tournament-42, revision 3 of a generated itinerary report supersedes revision 2. The SMS should tell an authorized recipient that the itinerary changed. The report email should identify the revision and carry the corresponding attachment. Treat these identifiers as application data, not provider fields. A late receipt for the revision 2 SMS must never mark the revision 3 report as delivered.

Keep them separate.

There are two email reasons here: an urgent fallback when SMS doesn't establish delivery, and fulfillment of the requested report attachment. If one email can satisfy both, record both reasons against the same logical send. Otherwise, a successful SMS could accidentally suppress the report, or the fallback worker could send a second copy of an email already queued by report generation. Neither outcome is necessary to implement SMS-first alerts.

Define success carefully. Provider acceptance, a delivery receipt, and a recipient reading a report are different observations. Record the evidence you actually receive. Don't turn an accepted send into proof that a player, coach, or travel coordinator has reviewed the change.

Derive the worker from the report revision

Persist an event identifier, report revision, intended recipient, SMS message identifier, next poll time, and fallback deadline. Also persist a logical email identity derived from the event, revision, and recipient. The report attachment and the urgent alert can then refer to the same revision without sharing a single delivery flag. This costs an extra state distinction, but it prevents receipt handling from deciding whether a promised document should exist.

For illustration, allow 90 seconds before an unresolved SMS makes email fallback eligible. That is a policy example, not a delivery guarantee or a recommended default for every itinerary change. A gate change close to departure may need a different deadline from tomorrow's pickup adjustment. Terminal non-delivery or a suppressed number can make fallback eligible sooner. A pending or unrecognized result should remain unresolved until the deadline; inventing a terminal status is worse than admitting uncertainty.

The clock matters.

Persist the deadline when the event is created, rather than restarting the timer on every worker retry. Schedule status polling with bounded backoff. On HTTP 429, honor Retry-After when supplied and back off instead of immediately repeating the request. A status lookup retry is different from a send retry: the first retrieves evidence, while the second can create another message. For writes, use the provider's documented idempotency mechanism and retain the same logical identity across retries.

Keep your own durable send ledger as well. Two workers may observe the deadline together. An atomic claim on the email identity prevents them from independently deciding to send the attachment, while provider idempotency addresses repeated submissions of that logical operation. An ambiguous send response deserves reconciliation before a new send identity is created.

Resends need a separate user action and an application limit. A noisy itinerary feed should not convert every revision poll into another text. Ordinary event notifications should use standard SMS sending and status retrieval; an OTP verification flow answers a different question.

Compare the integration surface after defining the state

The useful comparison is the work needed to connect a report generator to two delivery channels. It isn't a ranking of nominal send features. These options cover different boundaries, so an email product should be evaluated as part of a stack rather than treated as an SMS replacement.

Option Relevant fit Integration tradeoff for this report workflow
Twilio Programmable Messaging SMS sending and delivery status documentation make it a concrete choice for the urgent channel. Pair it with an email integration and keep the report revision and fallback decision in your worker.
Amazon SES Its documented attachment support makes it a candidate for the generated report email. It covers the email portion of this design; evaluate an SMS integration separately and connect both receipts to the same event.
Twilio SendGrid Mail Send Its attachment documentation gives the report worker an email API to evaluate. It still needs to be joined to the SMS decision and the application's duplicate prevention rules.

Infrai provides a unified API with a single key and a single bill for backend services: one API key replaces separate service credentials, and one invoice reduces month-end reconciliation. That makes it a candidate when integration administration is the priority. Its public, self-describing discovery surface also helps inspect request and response schemas before writing an adapter. For this workflow, plan to own delivery polling and fallback timing in the backend, together with country allowlists and budget guards; credential consolidation doesn't remove those responsibilities.

Choose the SMS-focused option when its messaging controls are the deciding requirement. Choose an email-focused component when the report delivery integration is already established and replacing it would add work. Consider the consolidated option when the surrounding backend also benefits from shared authentication and billing. Test attachment construction and receipt mapping before treating any combination as the easier integration. No comparative delivery benchmark is implied here.

A minimal decision rule with no network assumptions

This runnable example produces the next email action after a provider adapter has normalized SMS evidence. The strings are internal application states, not claims about any vendor's response fields. It deliberately keeps an attachment obligation distinct from SMS fallback. Save it as a Python file and run it with Python 3; it prints three decisions for the same illustrative report. Optionally, set SMS_MESSAGE_ID, INFRAI_API_KEY, and INFRAI_API_BASE_URL to retrieve a real SMS status first. Use the service's HTTPS API base ending in /v1, without a trailing slash. The response is printed without assuming an undocumented status field; map its documented schema in the adapter before using it as decision input.

from dataclasses import dataclass
from email.utils import parsedate_to_datetime
import os
import time
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen


def fetch_sms_status(message_id: str) -> str:
    base = os.environ["INFRAI_API_BASE_URL"].rstrip("/")
    if not base.startswith("https://"):
        raise ValueError("The API base must use HTTPS")
    url = f"{base}/sms/status/{quote(message_id, safe='')}"
    request = Request(
        url,
        headers={"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}"},
        method="GET",
    )
    for attempt in range(4):
        try:
            with urlopen(request, timeout=15) as response:
                return response.read().decode("utf-8")
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                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(delay, float(retry_after))
                except ValueError:
                    retry_at = parsedate_to_datetime(retry_after).timestamp()
                    delay = max(delay, retry_at - time.time())
            time.sleep(delay)
    raise RuntimeError("Status polling exhausted")


@dataclass(frozen=True)
class ReportNotice:
    event_id: str
    revision: int
    recipient_id: str
    sms_state: str
    elapsed_seconds: int
    attachment_required: bool
    email_claimed: bool = False
    fallback_after_seconds: int = 90


def next_email_action(notice: ReportNotice) -> dict:
    key = (
        f"{notice.event_id}:r{notice.revision}:"
        f"{notice.recipient_id}:report-email"
    )
    reasons = []
    if notice.attachment_required:
        reasons.append("report_attachment")
    if notice.sms_state in {"undelivered", "suppressed"}:
        reasons.append("sms_fallback")
    elif (
        notice.sms_state != "delivered"
        and notice.elapsed_seconds >= notice.fallback_after_seconds
    ):
        reasons.append("sms_deadline")
    if notice.email_claimed:
        action = "reconcile_existing_email"
    elif reasons:
        action = "claim_email"
    else:
        action = "wait"
    return {"action": action, "email_key": key, "reasons": reasons}


if __name__ == "__main__":
    if os.environ.get("SMS_MESSAGE_ID"):
        print(fetch_sms_status(os.environ["SMS_MESSAGE_ID"]))
    for state, elapsed, claimed in [
        ("delivered", 12, False),
        ("pending", 90, False),
        ("undelivered", 20, True),
    ]:
        notice = ReportNotice(
            event_id="tournament-42",
            revision=3,
            recipient_id="travel-coordinator-7",
            sms_state=state,
            elapsed_seconds=elapsed,
            attachment_required=True,
            email_claimed=claimed,
        )
        print(next_email_action(notice))
Enter fullscreen mode Exit fullscreen mode

Notice the first case: delivered SMS still produces an email claim because the report attachment is owed. The second case adds a fallback reason to that same email identity. The last requests reconciliation because another worker already owns the send. The function does not make an atomic database claim or submit an email; the production worker must implement those operations around the returned decision.

This boundary also keeps transport details out of the rule. A Node.js adapter can implement the same decisions without borrowing undocumented JSON fields from a different provider.

Roll out with recipient and revision checks

Begin with a small internal recipient cohort and one report type. Exercise a delivered SMS, a suppressed number, a deadline reached without a terminal receipt, and two workers racing for one email claim. Then replace a report revision while an older SMS is pending. Verify that the attachment, subject, and audit record all identify the intended revision before expanding delivery.

Keep SMS content minimal. Travel reports can contain personal details, so check recipient authorization before attaching the document and keep attachment contents out of routine logs. Apply country allowlists and communication preferences before dispatch; US/EU coverage is not itself a legal permission to contact someone. Keep operational itinerary notices separate from marketing. RFC 8058 explains one-click unsubscribe signaling, but it doesn't determine consent or lawful handling for this application.

Generate the attachment close to dispatch and recheck whether its revision is still current. This reduces dependence on withdrawing an already scheduled email when travel plans change again. Retain only the report and delivery evidence needed for the application's documented retention purpose. The rollout is ready to expand when a retry preserves one logical report email and every delivery claim can be traced to actual evidence.

Sources

References for the messaging, attachment, and unsubscribe interfaces discussed above:

Top comments (0)