DEV Community

SolomonFletcher5872
SolomonFletcher5872

Posted on

Fintech Email and SMS Notification Events: Evidence for Recipient Suppression

Recipient suppression has a difficult trade-off: stop sending to an invalid address quickly, while retaining enough evidence to explain why that address was blocked. For fintech email and SMS notification events, put that decision in a durable application ledger and keep provider delivery collection asynchronous. TL;DR: record the event, normalize the delivery result, apply a channel-specific suppression rule, and check that rule before a retry or a new notification.

Keep the evidence.

A SaaS application running Node.js can enqueue notification work without waiting for a delivery outcome. The implementation below uses Python to make the suppression policy executable in a notebook before it becomes a production worker contract. The question worth testing is concrete: after a confirmed invalid email recipient, can a later billing notification reach the sending step?

How should email and SMS notification events trigger suppression?

A rejected email address should affect subsequent email attempts to that address under an explicit policy. It should not silently disable SMS for the same customer. Nor should an ambiguous transport failure establish that a recipient is invalid. Those are separate decisions, and collapsing them into one “failed” flag makes the compliance evidence harder to defend.

The data flow is short.

The application records a notification intent with an identifier, customer reference, channel, and recipient reference; a worker checks suppression before dispatch; a collector retrieves delivery events; a normalizer maps confirmed evidence to an internal outcome; and a transaction records that evidence alongside any suppression decision. Retries return through the same check. This is a proposed application contract, so its field names are yours to define. For a synthetic billing example, use customer reference account-258, an email recipient reference email-17, and a separate SMS reference phone-17. Keep raw addresses and phone numbers out of the notebook fixture. In production, resolve those references through the application's recipient store with appropriate access controls. The identifier alone is not a privacy guarantee; it is a way to avoid copying contact details into every diagnostic artifact.

Make the suppression decision executable

The following read-only collector retrieves email event evidence. Configure INFRAI_BASE_URL with the service's HTTPS origin, without a version suffix, and INFRAI_API_KEY with your credential. It makes no sending or suppression writes. The returned JSON remains provider evidence until a schema-validated normalizer classifies it.

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["INFRAI_BASE_URL"].rstrip("/")
if not origin.startswith("https://"):
    raise ValueError("The service origin must use HTTPS")
url = origin + "/v1/email/event/list"


def retry_delay(value, attempt):
    if value:
        try:
            return max(0.0, float(value))
        except ValueError:
            try:
                instant = parsedate_to_datetime(value)
                return max(
                    0.0,
                    (instant - datetime.now(timezone.utc)).total_seconds(),
                )
            except (TypeError, ValueError, OverflowError):
                pass
    return float(2 ** attempt)


def collect_events():
    for attempt in range(4):
        request = Request(
            url,
            method="GET",
            headers={
                "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
                "Accept": "application/json",
            },
        )
        try:
            with urlopen(request, timeout=30) as response:
                if response.status != 200:
                    raise RuntimeError(
                        f"Unexpected response status: {response.status}"
                    )
                return json.load(response)
        except HTTPError as error:
            details = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(
                    f"Collection failed: HTTP {error.code}: {details}"
                ) from error
            time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
    raise RuntimeError("Collection attempts exhausted")


evidence_response = collect_events()
print("Evidence response collected; normalization is a separate step.")
Enter fullscreen mode Exit fullscreen mode

There are 4 attempts in this example, with a 30-second timeout per request. Those are sample policy values, not measured service limits. Retry-After can lengthen the total wait, so run collection in a background worker. Don't expose error details containing recipient data in a public response.

Here is a runnable Python policy example using only the standard library. Save it as a Python file and run it. It creates an in-memory SQLite ledger, applies an invented normalized email event twice, and checks that email is suppressed while SMS remains eligible. Every event and field in this fixture belongs to the application example; none represents a provider response schema.

The normalizer is an important boundary. Only map an event to invalid_recipient when the actual provider evidence supports that classification. The example starts after that decision and performs no network requests.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE evidence (
    event_id TEXT PRIMARY KEY,
    channel TEXT NOT NULL,
    recipient_ref TEXT NOT NULL,
    outcome TEXT NOT NULL,
    source_ref TEXT NOT NULL
);
CREATE TABLE suppression (
    channel TEXT NOT NULL,
    recipient_ref TEXT NOT NULL,
    reason TEXT NOT NULL,
    evidence_id TEXT NOT NULL REFERENCES evidence(event_id),
    PRIMARY KEY (channel, recipient_ref)
);
""")
db.execute("PRAGMA foreign_keys = ON")


def apply_event(event):
    with db:
        inserted = db.execute(
            "INSERT OR IGNORE INTO evidence VALUES (?, ?, ?, ?, ?)",
            (
                event["event_id"],
                event["channel"],
                event["recipient_ref"],
                event["outcome"],
                event["source_ref"],
            ),
        ).rowcount
        if inserted and event["outcome"] == "invalid_recipient":
            db.execute(
                "INSERT OR IGNORE INTO suppression VALUES (?, ?, ?, ?)",
                (
                    event["channel"],
                    event["recipient_ref"],
                    "confirmed_invalid",
                    event["event_id"],
                ),
            )


def eligible(channel, recipient_ref):
    row = db.execute(
        "SELECT 1 FROM suppression "
        "WHERE channel = ? AND recipient_ref = ?",
        (channel, recipient_ref),
    ).fetchone()
    return row is None


event = {
    "event_id": "fixture-event-258",
    "channel": "email",
    "recipient_ref": "email-17",
    "outcome": "invalid_recipient",
    "source_ref": "fixture-source-258",
}
apply_event(event)
apply_event(event)

assert not eligible("email", "email-17")
assert eligible("sms", "phone-17")
assert db.execute("SELECT COUNT(*) FROM evidence").fetchone()[0] == 1
assert db.execute("SELECT COUNT(*) FROM suppression").fetchone()[0] == 1
print("Duplicate event handled; email blocked; SMS eligibility unchanged.")
Enter fullscreen mode Exit fullscreen mode

The transaction couples evidence insertion to the suppression decision. The primary key makes an exact event replay harmless, and the channel-plus-recipient key prevents one channel's result from suppressing another. This is the useful notebook-to-prod step: promote the policy and its assertions, then replace the in-memory database and fixture with durable storage and a verified adapter.

There is a trap here.

Deduplicating collection does not make sending idempotent. A send worker needs its own stable notification identifier and a supported provider idempotency mechanism; retrying an uncertain send with a new identifier can create another notification. Preserve the original intent across attempts.

The sample stops at eligibility. A production design must define how suppression updates and dispatch compete, since checking eligibility and sending later creates an interval in which new evidence can arrive. Document which sends were already in flight when the suppression became effective, and retain the timestamps needed to reconstruct that ordering.

Evaluate evidence before selecting a delivery service

The useful comparison axis is the evidence chain: can the application connect a delivery result to a notification intent, a recipient, and the decision that stopped later sends? An API response accepting work is not sufficient evidence of the final delivery outcome. Build an eval-driven acceptance test around that distinction before connecting a provider.

These are real products to evaluate, with different channel scopes. The final column describes a selection test, rather than promising an unverified audit feature.

Option Relevant scope Selection test for this workflow
Amazon SES Email delivery Choose for an email integration only after demonstrating how its delivery evidence becomes a recipient suppression decision in your ledger.
Twilio SendGrid Email delivery Compare against SES on the same invalid-recipient fixture, including evidence export and reconciliation requirements.
Twilio Programmable Messaging SMS messaging Evaluate the phone-recipient evidence path separately; this does not replace the email-side comparison.

The two email products are alternatives for the email leg. The SMS product covers a different leg, so counting all three as interchangeable vendors would distort the choice. A combined shortlist should state who supplies each channel and who owns the cross-channel policy. Product documentation belongs in that review, followed by a test against the actual account configuration.

Infrai combines one key and one bill with a simple API across 20 modules: a single credential and consolidated billing cover email, SMS, and other backend capabilities. This breadth of capabilities under a unified API reduces the credentials and invoices the notification team must reconcile. Its REST API uses plain HTTP with no SDK required, and switching vendors behind a capability keeps the application-facing contract stable. The public, self-describing discovery surface exposes request and response schemas without a key, and documented capabilities include runnable examples in 10 languages. That gives the Python notebook and Node.js worker a shared schema to validate before promotion, reducing the friction of translating an evidence collector between runtimes. Apply the same evidence fixtures and deployment requirements to this pattern.

For an implementation that collects delivery events by polling, budget the collection interval into suppression freshness. The trade-off is delayed suppression versus a collector the application can replay and reconcile. This is suitable when the business can accept that interval and can reconcile missed collections. If the requirement demands an immediate push-driven response, use a delivery integration whose documented event mechanism and measured behavior satisfy that requirement. Treat event timing as an acceptance criterion.

Fintech compliance evidence requires more than a working sender. Require deployment-specific evidence for provider readiness, jurisdiction, data handling, and retention; neither an API's geographic breadth nor a successful test message establishes domestic compliance. Keep OTP issuance, scheduled-message cancellation, SMTP relay, and additional channels as separate procurement checks whenever the application needs them. SMS geographic restrictions and spend circuit breakers should have explicit application owners.

Retries need a reason, and audits need a trail

Don't retry blindly.

A retry policy should distinguish confirmed invalid recipients from temporary delivery trouble and uncertain submission outcomes. Suppress the first under the approved policy; schedule bounded retries for the second; reconcile the third against the original notification intent before authorizing another send. An uncertain result isn't permission to generate a new identifier. For audit review, retain the source evidence reference, normalization decision, policy version, and effective time alongside the affected recipient reference. These are proposed ledger fields, not a vendor response schema or a claim of regulatory sufficiency.

Keep classification deterministic. A prompt-cost aware design doesn't need an LLM to decide whether an explicitly classified invalid recipient should be suppressed. If an agent explains the outcome to an operator, give it the recorded decision and controlled evidence references; keep the actual eligibility check in code. That makes the eval useful across notebook runs and production deployments without making delivery policy depend on generated prose.

SPF has a narrower role. RFC 7208 concerns authorization to use a domain in email; passing that check doesn't establish that a recipient address is valid or that a suppression decision has adequate evidence. Keep sender authentication and recipient eligibility as separate controls.

Promote the policy with an operational check

Before deployment, replay a confirmed invalid recipient, an ambiguous failure, and a duplicate event through the same policy harness. Verify that a subsequent email intent is blocked for the invalid address while the independent SMS recipient remains eligible under its own policy. Then exercise the race between dispatch and newly collected evidence. The ledger should explain the ordering, including work already in flight.

Assign an owner to collection freshness and reconciliation, define the retention and access rules for recipient evidence, and make the retry budget explicit. Review suppression removal as a separate authorized transition with its own evidence. Finally, confirm that the chosen providers meet the deployment's channel and jurisdiction requirements. A green notebook is a useful beginning; the production acceptance criterion is an explainable decision every time a later notification is withheld.

Sources

References for the standards and product documentation used in the evaluation:

Top comments (0)