DEV Community

RhettMurray8263
RhettMurray8263

Posted on

Bulk Email Notifications With Recipient Status Polling (After Partial Failure)

Bulk Email Notifications With Recipient Status Polling (After Partial Failure)

Keep a recipient ledger and check suppression before retrying a bulk notification. For a B2B SaaS application sending account event alerts, that is the least complex starting point for handling bounces without resending to everyone whose email already succeeded.

TL;DR: Batch email and SMS can support event notifications, but the application must reconcile partial failures per recipient. Poll status and event records, persist the result, suppress confirmed invalid destinations, and retry only eligible attempts. A batch submission acknowledgment cannot establish that every recipient received the alert.

The interesting failure is a batch that looks stuck because one address is invalid while another recipient's delivery is still unresolved. Replaying the whole job mixes two different decisions. One destination needs suppression; the other needs more evidence. For an AI application, a model-generated explanation can help an operator understand that distinction, but delivery state should come from deterministic evidence. Save the prompt budget.

How should batch email notifications handle partial failure per recipient?

The data flow is straightforward: persist each intended recipient before submission, associate the resulting provider identifiers with individual attempts, poll for status or events, normalize that evidence, and update the recipient ledger. Consult a separate suppression record before authorizing another send. When an attempt has no conclusive result, keep it unresolved and reconcile it again; silence alone cannot establish either delivery or permanent failure.

Suppression outlives a batch.

Don't resend blindly.

That distinction matters for account alerts generated by recurring SaaS events. An invalid address encountered during one notification should also be excluded when a later event produces a new batch. Meanwhile, a failed email destination does not prove that an SMS destination is invalid. Keep channel and destination in the suppression key, and keep the event identifier in the attempt key. Those keys answer different questions.

Replay the recovery rule before connecting a sender

This runnable Python example uses only the standard library. Its three recipients and four observations are synthetic fixtures, not delivery measurements. The status names are an application vocabulary; they are not provider response fields. A real adapter must translate documented provider evidence into that vocabulary and retain the original evidence for investigation.

The example deliberately leaves one recipient pending. That is a useful outcome: a reconciliation worker should be able to make progress without pretending that the entire batch has finished. Consider the next account event arriving while that recipient is unresolved: suppression can exclude the confirmed invalid address immediately, but eligibility alone cannot establish that the pending attempt is safe to repeat. Combining these checks into a single batch-level boolean loses the distinction. Keep the attempt history and the destination policy separate, even if that means two database lookups rather than one convenient flag.

First, this read-only collector retrieves email events. Set API_ORIGIN to the service's HTTPS origin, without a trailing slash or version suffix, and INFRAI_API_KEY to your credential. The base is supplied through configuration to keep this comparison unlinked. The response is printed without assuming undocumented fields; it still needs a schema-aware adapter before entering the ledger below. This is a bounded polling call, not the production polling scheduler.

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

origin = os.environ["API_ORIGIN"].rstrip("/")
if not origin.startswith("https://"):
    raise ValueError("API_ORIGIN must use HTTPS")
request = Request(
    origin + "/v1/email/event/list",
    headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
    method="GET",
)
for attempt in range(5):
    try:
        with urlopen(request, timeout=30) as response:
            if not 200 <= response.status < 300:
                raise RuntimeError(f"Unexpected HTTP status {response.status}")
            payload = json.load(response)
        print(json.dumps(payload, 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(delay, float(retry_after))
            except ValueError:
                retry_at = parsedate_to_datetime(retry_after)
                delay = max(
                    delay,
                    (retry_at - datetime.now(timezone.utc)).total_seconds(),
                )
        if delay > 60:
            raise RuntimeError("Defer polling until Retry-After expires") from error
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

Now replay the policy locally. No network access is needed for this second example. Its 3 recipients produce 4 observations but only 3 unique observation records; the repeated event must not create another effect.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE attempts (
    attempt_id TEXT PRIMARY KEY,
    event_id TEXT NOT NULL,
    channel TEXT NOT NULL,
    destination TEXT NOT NULL,
    state TEXT NOT NULL
);
CREATE TABLE suppressions (
    channel TEXT NOT NULL,
    destination TEXT NOT NULL,
    reason TEXT NOT NULL,
    PRIMARY KEY (channel, destination)
);
CREATE TABLE observations (
    observation_id TEXT PRIMARY KEY
);
""")

recipients = [
    ("a1", "account-event-42", "email", "ops@example.com", "pending"),
    ("a2", "account-event-42", "email", "old@example.com", "pending"),
    ("a3", "account-event-42", "email", "owner@example.com", "pending"),
]
with db:
    db.executemany("INSERT INTO attempts VALUES (?, ?, ?, ?, ?)", recipients)


def reconcile(observation_id, attempt_id, outcome):
    if outcome not in {"delivered", "invalid_destination", "pending"}:
        raise ValueError("Unmapped outcome requires investigation")
    with db:
        row = db.execute(
            "SELECT channel, destination, state FROM attempts "
            "WHERE attempt_id = ?",
            (attempt_id,),
        ).fetchone()
        if row is None:
            raise ValueError("Unknown attempt")
        inserted = db.execute(
            "INSERT OR IGNORE INTO observations VALUES (?)",
            (observation_id,),
        )
        if inserted.rowcount == 0:
            return
        channel, destination, current = row
        if current in {"delivered", "invalid_destination"}:
            if outcome not in {current, "pending"}:
                raise ValueError("Conflicting terminal evidence")
            return
        db.execute(
            "UPDATE attempts SET state = ? WHERE attempt_id = ?",
            (outcome, attempt_id),
        )
        if outcome == "invalid_destination":
            db.execute(
                "INSERT OR IGNORE INTO suppressions VALUES (?, ?, ?)",
                (channel, destination, "confirmed invalid destination"),
            )


fixtures = [
    ("observation-1", "a1", "delivered"),
    ("observation-2", "a2", "invalid_destination"),
    ("observation-2", "a2", "invalid_destination"),
    ("observation-3", "a3", "pending"),
]
for observation in fixtures:
    reconcile(*observation)


def may_send(channel, destination):
    return db.execute(
        "SELECT 1 FROM suppressions WHERE channel = ? AND destination = ?",
        (channel, destination),
    ).fetchone() is None


assert not may_send("email", "old@example.com")
assert may_send("email", "owner@example.com")
assert db.execute("SELECT COUNT(*) FROM observations").fetchone()[0] == 3
assert db.execute(
    "SELECT state FROM attempts WHERE attempt_id = 'a3'"
).fetchone()[0] == "pending"

for row in db.execute(
    "SELECT attempt_id, state FROM attempts ORDER BY attempt_id"
):
    print(*row)
db.close()
Enter fullscreen mode Exit fullscreen mode

The suppression lookup means only that the destination is eligible at that gate. It does not authorize resending an unresolved attempt. Production dispatch must also inspect attempt state and the existing submission identity, so a timeout cannot silently become a second notification.

There is another intentional boundary here: an invalid destination is stronger evidence than a generic bounce label. Normalize only when the provider's documented reason supports the classification. A temporary delivery problem should not automatically become permanent suppression. Preserve ambiguous evidence for another reconciliation pass or operator review.

Choose the delivery interface around the recovery loop

Infrai combines a single key and a single bill with a plain REST API covering 295 routes across 20 modules, so an HTTP-capable reconciliation worker can manage email and SMS without a dedicated SDK or separate credentials for each channel. Unified billing also reduces invoice reconciliation across those channels. Its public, self-describing discovery supplies request and response schemas for the polling adapter, with runnable examples in 10 languages. Email list, individual message lookup, and event polling capabilities support reconciliation, while recipient state and suppression policy still belong in the application.

That is a fit for a worker that already owns periodic reconciliation. Evaluate alternatives against the same requirements, including suppression semantics, evidence retention, and the operational work of consuming delivery events. The following comparison identifies useful evaluation targets, rather than claiming a measured reliability ranking.

Option Relevant documentation to examine Decision it helps resolve
Twilio SendGrid Event Webhook documentation Assess how pushed email events would feed the same recipient ledger, and what processing the receiver must own.
Amazon SES Suppression list documentation Examine account suppression behavior and its relationship to application suppression policy.
Postmark Bounce API documentation Examine bounce records and the evidence available for classifying a destination before allowing another send.

These are different entry points into the same recovery problem. An event receiver adds another service to operate; a polling worker adds reconciliation delay. Neither interface removes the need to correlate evidence with the exact recipient attempt. The cited documentation is the place to verify each product's current integration details before choosing one.

The trade-off is polling delay. A pull-based integration is not suitable for a requirement that depends on immediate webhook-driven fallback; evaluate SendGrid's Event Webhook for the email event leg instead. A successful batch submission is too early to trigger fallback, and an unresolved email is insufficient evidence to send an SMS duplicate.

Delivery reliability comes first.

Keep the scope narrow as well. An email-and-SMS notification workflow does not establish support for SMTP relay, voice, WhatsApp, or RCS. A login fallback introduces separate requirements: the application must own an email verification flow where there is no managed email OTP operation. SMS abuse controls, including geographic restrictions and country-based spending cutoffs, need explicit application policy. An SMS template inventory and any scheduled-email cancellation requirement also need independent verification; neither should be assumed from the existence of a send operation. Regional compliance needs its own evidence.

Carry the notebook checks into the worker

The notebook-to-prod transition is where this design earns its keep. Keep the tiny replay fixtures, then add delayed observations, conflicting terminal evidence, and an already suppressed destination appearing in a new account event. Use an eval-driven review of the adapter's classifications: the expected outcome is a reproducible state transition, not a persuasive explanation generated by a model. The example refuses conflicting terminal evidence because quietly overwriting it would hide the very case an operator needs to inspect.

Make persistence durable before dispatch. Correlate every provider message identifier with its attempt, and make replay handling transactional. For submission retries, preserve a stable idempotency identity wherever the provider documents support. On rate limiting, honor Retry-After when present and use bounded exponential backoff. These transport rules complement recipient suppression; they solve different duplicate-send paths.

Next, define what “stuck” means operationally. Use your notification deadline and reconciliation age, rather than inventing a universal delivery timeout. A pending row should remain visible with its last observation time and next reconciliation time. If an event source is paginated, persist progress only after the associated updates are durable. Record enough evidence to distinguish a worker that stopped polling from a recipient whose delivery is still unresolved.

Keep campaign and event-type accounting in the application ledger when a tag-aggregated reporting API is unavailable. This also helps a prompt-cost-aware AI team separate notification work from model work, without asking an LLM to reconstruct either from logs.

Before enabling recovery, confirm that the worker excludes suppressed destinations across new batches, leaves unresolved attempts unsent, and handles repeated observations without repeating effects. Then confirm that the product accepts the polling delay before SMS fallback, that SMS consent and destination eligibility are checked independently, and that an operator can investigate contradictory evidence. A batch can be partially complete. The dashboard and the retry policy should say so.

References

The sources below provide sender guidance and the competitor documentation used for the evaluation criteria. The Python example is a local policy demonstration, not a request or response schema for any provider. No measured latency, inbox-placement advantage, or reliability ranking is implied.

Further reading

Top comments (0)