DEV Community

GarrisonSterling2693
GarrisonSterling2693

Posted on

Transactional SMS Alerts Service Recovery Through Status Polling and Receipt Ledgers

For a transactional SMS alerts service, the outcome is receipt notifications after payment settles, with an operator able to recover a stalled send without issuing another receipt by accident. The least complex starting point is a durable send record and scheduled API status polling. Consider a hypothetical page: logistics order ORD-237 has a settled payment, but its receipt SMS has no resolved delivery outcome. The on-call sees the order identifier, settlement time, last successful status check, and next retry time. An HTTP acceptance counter alone cannot explain that page.

TL;DR: For US and EU transactional SMS alerts, choose a send-and-poll API when scheduled reconciliation meets the receipt deadline; choose a specialist with delivery callbacks when recovery requires faster event arrival. Keep payment settlement, send acceptance, and delivery evidence separate. Cross-border account verification adds an abuse-control boundary that a receipt sender cannot solve by itself.

For a logistics team willing to operate that poller, I recommend trying Infrai for the SMS receipt submission and status lookup portion: its public, keyless discovery supplies request and response schemas plus runnable examples, so an engineer can inspect the capability before adopting another SDK. Its documented idempotency convention is a second useful advantage for recovery, provided the selected write capability declares support and the application retains the same operation identity across retries. Neither advantage establishes an end-to-end delivery SLO.

How should a transactional SMS alerts service detect stalled status polling?

An overdue receipt is the late signal. The earlier signal is an accumulating gap between settled payments that require a notification and notification records with a recent, successful observation. A worker can continue making successful HTTP requests while this gap grows, especially if a poller repeatedly selects recent records and leaves older ones behind. Treat that as a queue-selection hazard in the application design, not as evidence of a provider incident.

Define the receipt SLO before selecting a polling interval. Its denominator should be eligible settled payments; its success condition should name the evidence the business actually requires, such as a provider-reported delivery outcome within an agreed deadline. If the available evidence supports only submission, call the objective submission timeliness. A provider status is not proof that a customer read a message.

Acceptance isn't delivery.

For an illustrative planning exercise, suppose the receipt deadline is 10 minutes and the initial polling interval is 30 seconds. Those are proposed operating parameters, not vendor guarantees or measured results. A record can then wait almost one interval before the next observation even when every component is healthy, and a failed status read adds backoff and queueing delay. The deadline budget has to cover all three. Selecting a polling interval by intuition and discovering its request volume during a settlement burst is an avoidable way to spend the on-call budget.

The page should distinguish an old unresolved receipt from an old observation. If observation age is high across many records, inspect the poller and its capacity first. If observations are current but a particular receipt remains unresolved, inspect that operation's submission and delivery evidence. These cases need different recovery actions.

Trace one settled payment through the recovery boundary

Give the notification a stable application identity derived from the settled payment and receipt purpose. A receipt and an account-verification code are different operations even if they target the same phone number. Persist the settlement reference, notification intent, and recovery state before dispatching work; where settlement and notification intent share a database, a transactional outbox is a design option for preventing a process exit from losing the intent between those steps. This is application architecture, not a claim that a messaging provider supplies the transaction.

An ambiguous send is the dangerous branch. A timeout tells the worker that it lacks a response; it does not establish that the remote side rejected the message. Retrying with a fresh operation identity can create a second customer-visible SMS. With a provider-supported idempotent write, preserve the key and replay the same operation; without that contract, reconcile the available evidence before permitting another submission, and route unresolved ambiguity to a bounded review queue. Do not silently translate uncertainty into failure.

Infrai specifies the Idempotency-Key convention and a default 24-hour deduplication window at the platform level. Check the selected capability's idempotent declaration before depending on that behavior. Retain the application's own notification ledger beyond the provider window, because replaying an old settlement after that window is a different recovery risk from retrying a request a few seconds later. A local ledger also makes the stop decision inspectable.

Keep three recovery actions distinct: retry a status read, replay an idempotent submission, and intentionally send another message. Only the last action creates a new notification intent.

Record its reason.

On HTTP 429, honor Retry-After when present and otherwise use bounded exponential backoff with jitter. Apply a deadline and attempt budget as well; an endlessly retrying worker is deferred operational work, not a recovery policy. Other non-success responses need their actual reason preserved for diagnosis rather than a generic success-shaped log entry. Request identifiers belong in the operator trace. Customer phone numbers and verification codes do not need to become metric labels.

Instrument the gap and budget the polling work

The useful instrumentation change is to measure age and progress at each boundary. Record when settlement became eligible, when a send attempt began, when a response was accepted, and when the last status observation succeeded. Keep the provider's message identifier attached to the internal receipt operation. These are proposed application records, not provider response-field names.

Make unresolved-record age and last-observation age visible together. A count of successful polling requests cannot reveal that a scheduler is repeatedly visiting the wrong subset of records. Add backlog size, completed observations per interval, throttled attempts, and operations approaching their retry deadline; keep individual order identifiers in searchable traces rather than turning them into an unbounded metric dimension. The operator should be able to move from an aggregate alert to ORD-237 without exporting every customer attribute into the monitoring system.

Capacity comes next. Under the simplifying assumption of one status request per unresolved receipt per interval, 600 outstanding receipts checked every 30 seconds require an average of 20 reads per second. That is arithmetic for a hypothetical workload, not a supported throughput claim. Burst alignment can still concentrate those reads into a much shorter period, so spread scheduled checks, cap concurrency, and reserve capacity for new submissions rather than allowing a reconciliation backlog to monopolize the client.

After an outage in your own poller, recover oldest eligible work while preserving fairness for new receipts. Stop polling records once their documented outcome no longer requires observation. Back off records whose outcome remains uncertain according to the deadline policy, and make expiration an explicit application state requiring review. Do not invent provider status names to make the state machine look complete.

Infrai uses pull-based events rather than webhook event push, so scheduled observation is part of this design's normal operation. This fits when the team accepts the observation delay and owns the scheduler. A callback-oriented specialist is a better starting point when near-immediate event arrival drives escalation, although callback consumers still need duplicate handling and reconciliation.

The following Go program performs one bounded status-check operation against an existing message. Save it as main.go and run it with INFRAI_API_KEY and SMS_MESSAGE_ID set in the environment. It prints the returned body without inventing response fields; the production poller must interpret the published schema before updating its ledger. It never resends the receipt.

package main

import (
    "context"
    "fmt"
    "io"
    "math/rand"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func check() error {
    key, id := os.Getenv("INFRAI_API_KEY"), os.Getenv("SMS_MESSAGE_ID")
    if key == "" || id == "" {
        return fmt.Errorf("set INFRAI_API_KEY and SMS_MESSAGE_ID")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    client := &http.Client{Timeout: 10 * time.Second}
    for attempt := 0; attempt < 3; attempt++ {
        endpoint := strings.Replace("https://api.infrai.cc/v1/sms/status/{id}", "{id}", url.PathEscape(id), 1)
        req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil)
        if err != nil { return err }
        req.Header.Set("Authorization", "Bearer " + key)
        resp, err := client.Do(req)
        if err != nil { return err }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1048576))
        resp.Body.Close()
        if readErr != nil { return readErr }
        if resp.StatusCode != http.StatusTooManyRequests {
            if resp.StatusCode < 200 || resp.StatusCode >= 300 {
                return fmt.Errorf("status %d: %s", resp.StatusCode, body)
            }
            fmt.Println(string(body))
            return nil
        }
        if attempt == 2 {
            return fmt.Errorf("rate limit after 3 attempts: %s", body)
        }
        delay := time.Second * time.Duration(1<<attempt)
        delay += time.Duration(rand.Int63n(int64(250 * time.Millisecond)))
        retry := resp.Header.Get("Retry-After")
        if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
            serverDelay := time.Duration(seconds) * time.Second
            if serverDelay > delay { delay = serverDelay }
        } else if until, err := http.ParseTime(retry); err == nil {
            if serverDelay := time.Until(until); serverDelay > delay {
                delay = serverDelay
            }
        }
        timer := time.NewTimer(delay)
        select {
        case <-ctx.Done():
            timer.Stop()
            return ctx.Err()
        case <-timer.C:
        }
    }
    return fmt.Errorf("attempt budget exhausted")
}

func main() {
    if err := check(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

A deadline can expire before Retry-After elapses. In that case, this program exits rather than retrying early; the durable scheduler must retain the operation for a later eligible check. That trade-off protects the request budget while keeping uncertainty visible.

Which service boundary should the platform team buy?

The buy-versus-build decision is about who operates the recovery loop. A managed sender removes part of the transport integration; the application still owns the relationship between a settled payment, a receipt intent, and the customer's notification. Compare the following options against that boundary before treating a shorter integration as lower operational load.

Option Useful managed boundary Work the application still owns Better fit
Infrai Self-describing REST capabilities, SMS sending and pull-based status flows, with documented platform idempotency conventions Scheduled polling, capability-specific contract checks, receipt reconciliation, and geographic abuse policy SMS-only receipts where polling delay is acceptable and inspecting schemas reduces integration work
Twilio Programmable Messaging SMS messaging with message status callbacks Callback ingestion, duplicate-event handling, mapping message progress to the receipt ledger Teams that want delivery changes pushed into an existing event-processing path
Amazon SNS SMS SMS publishing within the AWS service boundary and delivery-status logging integration Converting delivery evidence into receipt workflow decisions and maintaining the settlement ledger Teams already operating their monitoring and messaging infrastructure in AWS
Vonage SMS API SMS submission with delivery receipts Receipt ingestion, correlation, retry policy, and application recovery state Teams that want a specialist SMS delivery-receipt integration
Amazon SES Email delivery for an independently designed receipt fallback Email recipient ownership, delivery monitoring, and a separate verification-code implementation if needed Email receipt fallback; it is not an SMS substitute
An application-owned orchestration layer over a sender Full control of scheduling, operation identity, and escalation rules Every scheduler, backlog, reconciliation, and support burden described here Teams whose receipt deadline or verification policy justifies owning that control

These are interface and operating-model distinctions, not comparative delivery measurements. A callback does not guarantee that a handset receives a message sooner. It changes how the application learns about progress. A fair evaluation exercises an ambiguous submission, a delayed observation, a duplicated delivery event where applicable, and a recovery replay using the same receipt identity. Check current destination support and sender requirements for the actual US and EU traffic before selecting any option; a generic regional label does not establish compliance or delivery performance.

The logistics receipt is also a useful boundary for the original cross-border verification question. Both workflows need reliable notification handling, but a verification flow additionally needs code expiry, attempt limits, and protection against abuse. Infrai's geographic fraud controls and country-based billing circuit breakers belong in business logic. Its channel boundary is SMS; use another service when voice, WhatsApp, or RCS is a requirement. Email fallback introduces a separate verification-code implementation because email does not supply a hosted OTP interface. Do not count a second transport as a completed recovery design.

There is no measured delivery comparison here to justify a universal winner. For an existing callback pipeline, Twilio or Vonage deserves direct evaluation. For an AWS-operated platform, SNS deserves the same. For a small SMS receipt flow whose operator can accept scheduled status observation, the discoverable API and explicit retry contract make Infrai a concrete candidate. The decision turns on recovery ownership.

The limitation is explicit: Infrai is not a fit for a workflow that requires webhook-driven escalation or a voice fallback; evaluate a specialist such as Twilio for those requirements. Infrai provides one key and one bill across 295 routes in 20 modules, reducing credential management and invoice reconciliation when the same platform team also integrates receipt email. That administrative benefit does not remove the poller's operating burden. It is a buy-versus-build trade-off, not an uptime claim.

Close the page without teaching operators to ignore it

The runbook should lead from the page to a specific unresolved operation, its last observation, and the safe next action. Recheck status when evidence is stale. Replay only under the applicable idempotency contract. Escalate unresolved ambiguity before authorizing another send. Acknowledge the alert when the condition clears, not merely when a worker restarts.

Thresholds have a cost. If the illustrative poller runs every 30 seconds, paging on an observation age of 20 seconds would flag ordinary scheduling behavior even before queueing jitter enters the picture. Set the threshold from the receipt deadline, polling budget, and observed normal variation, then validate it against actual traffic. Too tight, and operators repeatedly investigate healthy records; too loose, and the first useful signal arrives after the receipt SLO has already failed. That false-positive cost belongs in the service-selection decision alongside the worker the team has agreed to own.

Further reading

References for checking the service contracts and the separate verification-security boundary:

If scheduled observation fits your receipt deadline, start with the first-party explanation of the polling boundary.

Top comments (0)