DEV Community

AlgernonCross4103
AlgernonCross4103

Posted on

How to Poll Gaming Email Delivery — Auditable Notices Without Webhooks

A gaming compliance notice needs a delivery record that survives the next status refresh. A successful send request alone cannot supply that record, and a quiet event feed cannot prove that the player received the notice.

Short answer: Poll transactional email events on a schedule, retain the provider message ID, and append observations before updating the dashboard. This works for basic delivery visibility without webhooks. It is a poor timing model for immediate cross-channel fallback. Keep the audit evidence separate from any legal conclusion about whether the notice requirement has been satisfied.

The common Node.js cron question is really about that evidence boundary. The Python example below makes the reconciliation logic executable without guessing an email API's request parameters. A Node.js scheduler can trigger an equivalent worker; the ledger rules are independent of its language. The example uses synthetic data and a local database, so it tests repeatable ingestion rather than live delivery.

How should you poll transactional email delivery status without webhooks?

Separate three records: the notice your application intended to send, the provider message ID returned after sending, and the events subsequently observed. Keep the notice revision with the first record. Otherwise, an event can be correlated with an address while leaving the actual compliance text ambiguous. For this example, the fictional notice concerns a gaming account policy update; the fixture IDs and timestamps describe no actual customer or incident.

Preserve that distinction.

An observed delivery event belongs in the audit trail. It should not silently become a claim that a player read, understood, or accepted the policy. Likewise, no event means no new observation. Replacing uncertainty with “failed” would make the dashboard look decisive while weakening the record.

The four labels used here—sent, delivered, bounced, and failed—are an application vocabulary. A production adapter must map documented provider events into that vocabulary and preserve the original evidence. Don't assume every provider uses these exact field names or treats the same event as final.

Compliance scope matters too. The FTC's CAN-SPAM guidance is a reference for reviewing message purpose and applicable requirements. It does not establish that a gaming operator has met every jurisdiction's notice obligations. Have the responsible reviewer approve the notice text and evidence retention policy; a transactional label in application code cannot settle that classification.

Step 1: Save the notice-to-message relationship

Save this block as notice_poll.py, then append the next two code blocks in order. Run the completed file with Python. It uses only the standard library and creates a local SQLite database. Repeated runs reuse the same synthetic message ID.

The key design decision comes before polling: which exact notice does this provider message represent? This small schema assumes one provider message per notice. A production model that allows resends needs a separate attempt table, with each attempt retaining its own provider message ID. Store that relationship immediately after a successful send, before relying on a later event read to reconstruct it.

import hashlib
import json
import sqlite3
from datetime import datetime, timezone

db = sqlite3.connect("gaming_notice_audit.sqlite3")
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE IF NOT EXISTS notices (
    notice_id TEXT PRIMARY KEY,
    revision TEXT NOT NULL,
    provider TEXT NOT NULL,
    message_id TEXT NOT NULL,
    UNIQUE(provider, message_id)
);
CREATE TABLE IF NOT EXISTS observations (
    provider TEXT NOT NULL,
    fingerprint TEXT NOT NULL,
    message_id TEXT NOT NULL,
    occurred_at TEXT NOT NULL,
    observed_at TEXT NOT NULL,
    status TEXT NOT NULL,
    evidence_json TEXT NOT NULL,
    PRIMARY KEY(provider, fingerprint),
    FOREIGN KEY(provider, message_id)
        REFERENCES notices(provider, message_id)
);
""")
with db:
    db.execute(
        "INSERT OR IGNORE INTO notices VALUES (?, ?, ?, ?)",
        (
            "gaming-policy-notice-0042",
            "account-policy-revision-B",
            "fixture-provider",
            "fixture-message-0042",
        ),
    )
Enter fullscreen mode Exit fullscreen mode

This is a teaching ledger, not a tamper-evident archive. Its owner can edit rows. Production needs an explicit policy for evidence access, changes, and retention. Avoid duplicating player addresses or notice bodies in every observation when a controlled reference will do.

There is also a recovery boundary between sending a message and committing its returned ID. Define how the application reconciles an interrupted send attempt before enabling automatic resend. Polling cannot correlate a message whose identifier the application lost, and a blind resend can create another notice attempt.

Step 2: Make repeated reads safe before scheduling them

Append this block. It ingests two synthetic events twice and asserts that repeated reads do not multiply the evidence rows. The local fingerprint is bookkeeping, not a vendor event ID or a promised API field. If the provider exposes a documented stable event identifier, prefer it for deduplication.

def record_observation(provider, event):
    if event["status"] not in {"sent", "delivered", "bounced", "failed"}:
        raise ValueError("Unmapped status requires adapter review")

    event_time = datetime.fromisoformat(event["occurred_at"])
    if event_time.tzinfo is None:
        raise ValueError("Event time must include a timezone")
    occurred_at = event_time.astimezone(timezone.utc).isoformat()
    evidence = json.dumps(
        event["evidence"], sort_keys=True, separators=(",", ":")
    )
    identity = json.dumps(
        [provider, event["message_id"], occurred_at,
         event["status"], evidence],
        separators=(",", ":"),
    )
    fingerprint = hashlib.sha256(identity.encode("utf-8")).hexdigest()
    with db:
        db.execute(
            """INSERT OR IGNORE INTO observations
               VALUES (?, ?, ?, ?, ?, ?, ?)""",
            (
                provider, fingerprint, event["message_id"],
                occurred_at, datetime.now(timezone.utc).isoformat(),
                event["status"], evidence,
            ),
        )


fixture_events = [
    {
        "message_id": "fixture-message-0042",
        "occurred_at": "2026-11-12T09:00:00+00:00",
        "status": "sent",
        "evidence": {"fixture": "send-observation"},
    },
    {
        "message_id": "fixture-message-0042",
        "occurred_at": "2026-11-12T09:02:00+00:00",
        "status": "delivered",
        "evidence": {"fixture": "delivery-observation"},
    },
]

for event in fixture_events + fixture_events:
    record_observation("fixture-provider", event)

count = db.execute(
    """SELECT COUNT(*) FROM observations
       WHERE provider = ? AND message_id = ?""",
    ("fixture-provider", "fixture-message-0042"),
).fetchone()[0]
assert count == 2, count
Enter fullscreen mode Exit fullscreen mode

This fingerprint only deduplicates identical normalized observations. Distinct events with identical content would be indistinguishable. That limitation is acceptable for this fixture and must be reviewed against the selected provider's event identity rules before production.

Notice the two timestamps. Event time describes the provider observation after normalization; observation time records when this worker first stored it. Keeping both distinguishes a late event from a late polling run. Neither proves human receipt.

For a production poller, consume all documented pages and commit observations before advancing a durable checkpoint. If the API supports time-window reads, an overlapping window can recover delayed arrivals; confirm the supported filters and retention first. Don't invent cursor names or assume events are sorted. A completed read alone does not establish that another event can never appear for the same message.

Schedule bounded work. An illustrative configuration is a 60-second trigger that enqueues a reconciliation job with a 120-second worker budget. These numbers are design choices, not measured latency or freshness guarantees. Larger backlogs should continue through queued work. Prevent overlapping ownership of one checkpoint, and make queue redelivery safe through consumer deduplication.

The live adapter should set explicit HTTP methods, check response status, and surface errors without logging credentials. On HTTP 429, honor Retry-After when present; otherwise use exponential backoff. Keep retries inside the worker budget. Exhausting that budget should leave a resumable checkpoint and a visible stale-poll condition.

Keep failures visible.

For the REST option discussed below, this separate Python script reads an actual event page without inventing its response fields. Set INFRAI_API_ORIGIN to the service's HTTPS origin, without a path, and INFRAI_API_KEY to your credential. The script uses the verified read route and prints the returned JSON for adapter development. It does not claim to traverse every page or feed the fixture schema directly. Use the capability's discovery schema to implement that mapping and pagination before connecting it to the ledger.

import json
import os
import random
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.parse import urlsplit

origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/")
parts = urlsplit(origin)
if parts.scheme != "https" or not parts.netloc or parts.path:
    raise ValueError("Configure an HTTPS origin without a path")
request = urllib.request.Request(
    origin + "/v1/email/event/list",
    headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
    method="GET",
)
deadline = time.monotonic() + 120
for attempt in range(5):
    remaining = deadline - time.monotonic()
    if remaining <= 0:
        raise TimeoutError("Polling budget exhausted")
    try:
        with urllib.request.urlopen(request, timeout=min(15, remaining)) as response:
            print(json.dumps(json.load(response), indent=2))
        break
    except urllib.error.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
        retry_after = error.headers.get("Retry-After")
        if retry_after is None:
            delay = 2 ** attempt + random.random()
        else:
            try:
                delay = max(0, float(retry_after))
            except ValueError:
                retry_at = parsedate_to_datetime(retry_after)
                delay = max(
                    0, (retry_at - datetime.now(timezone.utc)).total_seconds()
                )
        if delay >= deadline - time.monotonic():
            raise TimeoutError("Defer retry to a later job") from error
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

This is a read-only request. Adding automatic sends would introduce a different requirement: write retries must be idempotent, with the notice attempt identity retained across retries.

Step 3: Project the evidence, then compare provider fit

Append the final block. It reports observations rather than declaring one irreversible outcome. A late “sent” observation should not erase an earlier delivery observation merely because it was read last.

rows = db.execute(
    """SELECT status, occurred_at, observed_at
       FROM observations
       WHERE provider = ? AND message_id = ?
       ORDER BY occurred_at, fingerprint""",
    ("fixture-provider", "fixture-message-0042"),
).fetchall()
assert any(status == "delivered" for status, _, _ in rows)
print("Notice: gaming-policy-notice-0042")
for status, occurred_at, observed_at in rows:
    print(
        f"Observed {status}; event_time={occurred_at}; "
        f"first_stored={observed_at}"
    )
db.close()
Enter fullscreen mode Exit fullscreen mode

A dashboard can show a current status, but its transition rules need to be explicit. Conflicting observations should remain inspectable. Keep collection freshness separate from delivery status so that a worker that stopped running cannot leave a falsely reassuring green panel.

This changes the comparison. Start with the evidence your worker must retrieve, then evaluate each integration against that contract. The following table is an evaluation plan, not a claim that these services expose interchangeable polling APIs or equivalent event retention.

Candidate Evaluation emphasis Boundary to verify before adoption
Resend Start with its email documentation and assess a focused transactional email integration. Confirm that documented retrieval behavior can recover the history this polling-only deployment requires.
Twilio SendGrid Evaluate its email integration against the same message correlation and evidence requirements. Establish which event history, access conditions, and retention rules apply to the selected account.
Amazon SES Assess the email service together with the event collection design around it. Verify that the chosen collection design supplies durable evidence without an inbound application webhook.

These are different evaluation scopes, not performance rankings. Require written answers before choosing. A webhook feature does not by itself establish a queryable archive, and a current status lookup does not necessarily preserve event history. The relevant documentation must resolve those distinctions; this local example cannot.

Infrai's self-describing API combines public discovery and runnable examples with plain HTTP, no SDK, single-key authentication, and unified billing. Reading a capability schema gives the notice worker its request and response contract without learning a new SDK. A single key and a single bill cover 295 routes across 20 modules; that reduces separate credential management when a notice workflow spans email, scheduling, and queues. Its email and SMS event model uses polling, so allow for observation delay when considering cross-channel fallback. That timing trade-off suits a simple notice dashboard better than an immediate multi-channel response requirement.

No provider choice turns polling into a delivery guarantee. For this gaming notice, select the integration that preserves message identity, exposes the required evidence, and makes stale collection obvious. Price does not resolve those questions.

Step 4: Roll out against an evidence acceptance test

Run the completed Python file twice. Each run should retain two observations for the fixture message and print both sent and delivered. Reverse the fixture order and rerun it. The evidence should remain stable because insertion order does not define the audit trail.

For the production pilot, require a reviewer to trace one approved notice revision through its stored message ID to the original event evidence. Exercise a repeated page, a delayed observation, an unmapped status, and a worker interruption before checkpoint persistence. An unknown message ID belongs in a visible reconciliation path rather than being discarded or assigned to a nearby player record.

Expand after that trace works.

The example verifies ledger behavior, not deliverability, provider retention, or polling completeness. Validate those separately with the selected service and compliance owner. If the workflow later requires immediate action across email and SMS, revisit the timing requirement before extending this loop.

Sources

References for provider evaluation and compliance review:

Top comments (0)