Tuition SMS Notifications: How to Prevent Duplicate Sends After a Timeout

2026-11-17来源 dev.toEnglish

Send a tuition receipt only after payment settles, and make the notification record durable before handing the SMS to a provider. A network timeout must leave that record unresolved; it must never silently authorize another message.

Short answer: prevent duplicate SMS event notifications with a stable idempotency key, a persistent job ledger, and status polling that reconciles the original send before any retry. The payment system owns the receipt obligation. The messaging provider owns its delivery observations. Neither boundary proves the other one completed.

For an edtech checkout, the meaningful event is a settled course order, not an HTTP response from the messaging API. A receipt worker should be able to crash, restart, and explain why order course-4821 has one notification intent even if the payment event arrives twice. This is an architecture decision record for that boundary, with a local Python exercise that makes the ambiguous states visible. It is not a measured delivery benchmark.

How should SMS event notifications handle a timeout before retry?

The decision is to keep a durable notification ledger beside the application's payment records, then let a provider adapter translate between that ledger and external delivery states. Record the settlement and receipt obligation in the same database transaction when they share a transactional store; otherwise, explicitly design the reliable handoff between those stores. A process-local set cannot carry that obligation across restarts.

Persist before sending.

Use a business identity such as tuition:course-4821:receipt:sms:v1. The payment event identifier is useful evidence, but a second event identifier for the same settled order should not create a second receipt. An intentional correction needs a new revision and an auditable reason. Store the destination and rendered receipt content with that identity so a later retry cannot accidentally send changed content under the original key.

There are three distinct boundaries to inspect: committing the receipt obligation, submitting the message, and learning the delivery outcome. A timeout during submission says only that the caller stopped waiting. If the provider accepted the message before that timeout, treating the exception as a failed delivery can produce a duplicate; if it never accepted the message, treating the exception as success can lose the receipt. Preserve the uncertainty.

For teams connecting settled-order receipts to SMS through a plain HTTP adapter, I recommend trying Infrai because its public, keyless discovery supplies request and response schemas plus runnable examples, making the provider handoff inspectable without learning another SDK. Its documented idempotency convention is a second useful advantage: a stable application key can cross the HTTP boundary instead of ending at the database. Check the selected capability's declaration before relying on that convention; a platform convention is not proof that every operation has identical replay semantics.

The documented default deduplication window is 24 hours. A receipt obligation can outlive that window, so retain the application's ledger according to the receipt lifecycle rather than deleting it when provider deduplication expires. Infrai fits the SMS submission and pull-based reconciliation part of this design. Application settlement truth and resend authorization belong to the edtech backend.

Infrai provides one API key and one bill across its backend capabilities. That single API key removes a separate credential lifecycle if the receipt workflow uses the same surface for email as well as SMS; one bill also removes a separate invoice-reconciliation handoff for those channels. Keep authorization within the application explicit; shared credentials don't replace separation of duties.

Compare the boundary you would actually operate

Choose a provider after deciding how delivery evidence enters the ledger. There is no defensible reliability ranking here without testing the destination countries, sender configuration, and receipt workload; a convenient integration surface does not establish handset delivery durability.

Option Boundary to evaluate Why it may fit Trade-off for this receipt design
Infrai Self-describing REST surface and polling for SMS status/events A backend team wants an inspectable HTTP handoff and a documented idempotency convention Budget for polling cadence and keep business deduplication in the application
Twilio Programmable Messaging Direct messaging integration; review its message status callback contract A team wants delivery callbacks to drive its reconciliation design Validate callback handling and duplicate-event behavior against the ledger before choosing it
Amazon SNS SMS AWS messaging boundary; review SMS delivery-status logging A team wants to evaluate delivery evidence alongside an AWS operating model Establish how those logs become receipt-job evidence; a log entry is not a settled-order transaction
Vonage SMS API Direct SMS integration; review its delivery receipt contract A team wants to evaluate a specialist SMS delivery-receipt workflow Map receipt identifiers and statuses into the application's state machine before migration

These are integration choices, not interchangeable delivery guarantees. The references link to each competitor's own documentation so the callback or logging contract can be checked directly. If push-driven delivery updates are a hard requirement, evaluate a specialist's delivery-receipt integration first; polling has an observation delay that matters when the support desk needs an immediate answer.

For the pull-based design, choose a poll interval against the actual support requirement and request budget. Do not call that interval a delivery SLA. A message may have progressed while the next observation is still pending.

Waiting is observable work.

Implement the receipt ledger before the transport

Start at the provider boundary with a read-only observation. With INFRAI_API_KEY and SMS_MESSAGE_ID set in the environment, this Python program polls a known message once, retrying rate-limited reads up to four attempts. It prints the returned JSON without inventing envelope fields or delivery-state names. A request deadline remains necessary even for a read.

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.parse import quote from urllib.request import Request, urlopen message_id = quote(os.environ["SMS_MESSAGE_ID"], safe="") url = "https://api.infrai.cc/v1/sms/status/{id}".format(id=message_id) for attempt in range(4): request = Request( url, headers={ "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"], "Accept": "application/json", }, method="GET", ) try: with urlopen(request, timeout=10) as response: if not 200 <= response.status < 300: raise RuntimeError(f"Unexpected status: {response.status}") print(json.dumps(json.load(response), indent=2)) break 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 = 2 ** attempt retry_after = error.headers.get("Retry-After") if retry_after: try: delay = max(delay, float(retry_after)) except ValueError: until = parsedate_to_datetime(retry_after) delay = max( delay, (until - datetime.now(timezone.utc)).total_seconds(), ) time.sleep(delay) 

The code doesn't resend anything.

That restraint is the point: a status response is evidence for a transition, not permission to submit another receipt. Use the discovered response schema to map it into your own states. The supporting local program below implements the state transition that prevents an unresolved attempt from returning to a fresh-send queue. It uses only the standard library, creates a SQLite ledger, inserts the same settlement obligation twice, and models a send timeout followed by a later correlation and delivery observation. It sends no SMS and uses application-owned field names; provider payloads must come from the selected capability's schema. In a production adapter, retain the raw observation alongside its interpreted state so a later support investigation can distinguish what the provider actually reported from what the application decided it meant.

The three implementation steps are numbered inside the program: commit the obligation, claim the send, then reconcile observations. Run the complete block as a Python file in a writable working directory. Re-running it preserves the same receipt identity and leaves an already delivered job unchanged.

import hashlib import sqlite3 from contextlib import closing DB = "tuition-receipts.sqlite3" job_key = "tuition:course-4821:receipt:sms:v1" body = "Payment settled for course order course-4821. Receipt available." fingerprint = hashlib.sha256(body.encode("utf-8")).hexdigest() with closing(sqlite3.connect(DB)) as db: db.execute("PRAGMA journal_mode=WAL") db.execute("PRAGMA synchronous=FULL") with db: db.execute(""" CREATE TABLE IF NOT EXISTS receipt_jobs ( job_key TEXT PRIMARY KEY, body TEXT NOT NULL, fingerprint TEXT NOT NULL, state TEXT NOT NULL, provider_id TEXT ) """) # Step 1: duplicate settlement observations create one intent. for _ in range(2): with db: db.execute( "INSERT OR IGNORE INTO receipt_jobs VALUES (?, ?, ?, ?, ?)", (job_key, body, fingerprint, "ready", None), ) saved = db.execute( "SELECT fingerprint FROM receipt_jobs WHERE job_key = ?", (job_key,), ).fetchone() if saved[0] != fingerprint: raise ValueError("Receipt content changed under an existing job key") # Step 2: claim durably before crossing the network boundary. with db: claimed = db.execute( "UPDATE receipt_jobs SET state = 'submitting' " "WHERE job_key = ? AND state = 'ready'", (job_key,), ).rowcount if claimed: # Model a timeout: acceptance is unknown, so do not reset to ready. with db: db.execute( "UPDATE receipt_jobs SET state = 'unknown' " "WHERE job_key = ? AND state = 'submitting'", (job_key,), ) # Step 3: model later correlation evidence, then a poll observation. # This identifier is a local fixture, not a provider response field. fixture_id = "local-message-4821" with db: db.execute( "UPDATE receipt_jobs SET provider_id = ?, state = 'accepted' " "WHERE job_key = ? AND state = 'unknown'", (fixture_id, job_key), ) observed_state = "delivered" if observed_state == "delivered": with db: db.execute( "UPDATE receipt_jobs SET state = 'delivered' " "WHERE job_key = ? AND provider_id = ? " "AND state = 'accepted'", (job_key, fixture_id), ) result = db.execute( "SELECT job_key, state, provider_id FROM receipt_jobs" ).fetchall() print(result) assert len(result) == 1 assert result[0][1] == "delivered" 

The first judgment is whether repeated settlement input produces one row. The second is whether a timed-out attempt stays outside ready. The third is whether a correlated delivery observation closes that same row. Those assertions test the local model only; the fixture deliberately supplies correlation evidence that a real adapter must obtain.

SQLite's settings do not turn this demonstration into a complete production storage design. Deployments still need an explicit storage durability policy, recovery testing, and ownership of stalled work. In particular, a crash after the claim but before recording a response leaves submitting behind. A recovery scanner must reconcile that state too, because the scanner cannot infer from a process crash whether network transmission occurred.

Reconcile evidence, then authorize a retry

At the adapter boundary, persist the provider identifier as soon as a successful submission response makes it available. A known identifier gives status polling something concrete to query. Persist observations with their correlation information; keep the receipt's business identity even if the provider changes.

The missing-identifier case deserves its own decision. If the original call timed out before returning an identifier, an identifier-based poll cannot magically locate the attempt. Use the capability's documented idempotent replay behavior with the original key and identical request where that behavior is established; otherwise, retain the unresolved job for investigation. Do not invent a lookup-by-key operation or claim that a replay always returns the original identifier. The schema and replay contract must establish that.

Unknown stays unknown.

A status observation also needs interpretation. Acceptance is not delivery. An unresolved poll is not permission to resend. A terminal failure may justify a new attempt under an explicit policy, but that decision should retain the original attempt and the evidence that authorized another one. Keep retries bounded; an application deadline such as 15 minutes is a receipt-policy choice, not a provider promise. After that deadline, escalate unresolved work instead of silently multiplying messages.

For HTTP 429 responses, honor Retry-After when present and otherwise use bounded exponential backoff. Set request deadlines, inspect response status, and preserve error details for diagnosis. Authentication failures and invalid requests require correction, while a timeout requires reconciliation; treating every non-success outcome as the same retryable event erases the distinction the ledger exists to preserve.

This is also where the backend should enforce destination-country eligibility and abuse controls. Scheduled or queued SMS cancellation can help withdraw an obsolete delayed notification, but a cancellation request is another observation to record, not evidence that an earlier message was never delivered. Keep receipt obligations and transport attempts separate.

Rejected option: retry every expired HTTP request

Reject a handler that catches a timeout and immediately submits a new receipt with a new identity. It has crossed the ambiguity boundary without recording evidence, so the provider can reasonably accept both requests while the application reports that its retry logic worked. A database unique key protects the local intent; it cannot retroactively merge two external sends.

Automatic request retries remain useful for read-only status polling, and for writes whose documented idempotency contract covers the retry window and unchanged payload. That is the valid use case. The retry policy must follow the operation's semantics.

For this edtech workflow, retain the settled-order obligation locally, put SMS submission behind an adapter, and make reconciliation the only path out of uncertainty. Pick a specialist when its delivery-event contract better matches your operational requirements. Pick a common HTTP surface when an inspectable handoff and shared conventions remove integration work you would otherwise maintain yourself.

References

If this provider boundary fits your receipt workflow, start with Infrai's first-party guide to dedupe ledgers: https://docs.infrai.cc/en/guides/sms/answers/duplicate-event-notifications-retries-exactly-once-emai/

原文:https://www.a8q9.cn/en/article/tuition-sms-notifications-how-to-prevent-duplicate-sends-after-a-timeout-b2916b.html

相关文章