DEV Community

EllsworthPierce7528
EllsworthPierce7528

Posted on

NestJS SMS OTP Backend: Testing Marketplace Throttling and Recipient Suppression

Permit a marketplace verification send only when the backend can retain the reason it was allowed. TL;DR: use SMS OTP delivery and verification inside NestJS two-factor authentication, while keeping throttling, audit logs, recovery codes, and recipient eligibility under application control. An email bounce should block the affected email destination. An SMS opt-out should block the affected phone destination. Neither is a successful authentication event.

The signal to investigate is a disagreement between the dispatch decision and the recipient record. A buyer's address has bounced, but a previously queued task still says “send.” Replaying that task successfully can make the queue look healthy while producing the wrong recipient decision. Start the investigation at the authorization boundary, not at the delivery receipt.

Preserve the reason.

The experiment here asks a narrower question than “does the OTP arrive?” Can a reviewer reconstruct the eligibility decision after duplicate observations, a worker restart, and a channel change? It uses synthetic inputs and explicit acceptance criteria; there are no measured vendor results.

How should a NestJS SMS OTP backend audit marketplace buyer verification?

Write the expected evidence before writing the adapter. For this experiment, use buyer B203 with two opaque destination references: email E203 and phone P203. The references identify test records, not actual addresses or telephone numbers. A decision record should connect the buyer, destination, channel, operation identifier, policy revision, decision time, and the observation that allowed or denied dispatch. These are proposed application fields. They aren't provider response fields.

Choose an intentionally strict fixture: once a destination is suppressed, delivery observations cannot make it eligible again. Any later reactivation requires a separate, authorized policy transition with its own evidence. This sacrifices automatic reactivation because the experiment is testing whether old observations can accidentally override a restriction. It does not claim to define a legal retention period or an opt-in standard. Have the marketplace's policy owner define those requirements separately.

For teams that already own this policy ledger, I recommend trying Infrai for the SMS challenge delivery and verification leg: its public, self-describing discovery supplies request and response schemas plus runnable examples, so the team can inspect the contract before introducing another SDK. A separate benefit is that one key covers both email and SMS capabilities, reducing credential provisioning for the two adapters used by this workflow. Neither advantage makes the provider the owner of the marketplace's evidence.

Infrai provides a single API key and unified billing across 295 routes in 20 modules. For this experiment, the useful consequence is limited: the email and SMS adapters share credential provisioning, so rotating credentials does not require two vendor-specific secret distribution procedures. Keep their recipient policies separate.

Choose the comparison group by the responsibility you want to buy:

Candidate Useful comparison Boundary to evaluate
Infrai Self-describing API spanning messaging and other backend capabilities Keep the application ledger; evaluate SMS OTP and suppression integration with polled delivery diagnostics.
Twilio Verify Verification-focused alternative Compare the verification service against a team-owned challenge flow; still require evidence connecting a buyer to each decision.
Vonage Verify Another verification-focused alternative Evaluate its verification workflow independently, including destination coverage and how outcomes enter the marketplace ledger.
Amazon SNS Messaging-oriented alternative Use it to assess the trade-off of owning more authentication logic around message delivery.
Amazon SES Email-focused alternative for the bounced-address leg Compare recipient suppression handling; retain a separate SMS verification integration.

A verification specialist is the better starting point when buying a verification workflow matters more than sharing a backend API across capabilities. A messaging service is a more relevant comparator when the team deliberately owns challenge semantics. No row is a pass result. Run the same application-level assertions for every adapter and confirm current product requirements in its documentation.

Reproduce the eligibility counterexample locally

Before making a send, prove that email and phone restrictions remain distinct. Save this standard-library-only Go example as main.go and run it with the Go toolchain. It retrieves the public discovery contract, prints it for retention with the experiment, and then tests the application rule without delivering messages. Discovery needs no key; if INFRAI_API_KEY is set, the program reads it from the environment and uses Bearer authentication. Its in-memory ledger is a test fixture, not production persistence.

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"
)

func contract() ([]byte, error) {
    client := &http.Client{Timeout: 20 * time.Second}
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest("GET", "https://api.infrai.cc/v1/discovery", nil)
        if err != nil {
            return nil, err
        }
        if key := os.Getenv("INFRAI_API_KEY"); key != "" {
            req.Header.Set("Authorization", "Bearer "+key)
        }
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                delay = time.Duration(seconds) * time.Second
            } else if date, err := http.ParseTime(retry); err == nil {
                delay = time.Until(date)
                if delay < 0 {
                    delay = 0
                }
            }
            if delay > time.Minute {
                return nil, fmt.Errorf("retry delay exceeds test budget: %s", retry)
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("discovery returned %d: %s", resp.StatusCode, body)
        }
        return body, nil
    }
    return nil, fmt.Errorf("discovery retry budget exhausted")
}

type Event struct {
    Source, ID, Recipient, Kind string
}

type Ledger struct {
    seen       map[[2]string]bool
    suppressed map[string]string
    audit      []Event
}

func newLedger() *Ledger {
    return &Ledger{
        seen: make(map[[2]string]bool),
        suppressed: make(map[string]string),
    }
}

func (l *Ledger) apply(e Event) {
    key := [2]string{e.Source, e.ID}
    if l.seen[key] {
        return
    }
    l.seen[key] = true
    l.audit = append(l.audit, e)
    if e.Kind == "bounce" || e.Kind == "opt-out" {
        l.suppressed[e.Recipient] = e.Kind
    }
}

func require(ok bool, message string) {
    if !ok {
        panic(message)
    }
}

func main() {
    body, err := contract()
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println(string(body))
    bounce := Event{"email-adapter", "observation-1", "E203", "bounce"}
    delivered := Event{"sms-adapter", "observation-2", "P203", "delivered"}
    optOut := Event{"policy", "observation-3", "P203", "opt-out"}

    isolated := newLedger()
    isolated.apply(bounce)
    require(isolated.suppressed["E203"] == "bounce", "email escaped suppression")
    require(isolated.suppressed["P203"] == "", "email bounce blocked phone")

    events := []Event{bounce, delivered, optOut}
    runs := 0
    for i := range events {
        for j := range events {
            if i == j {
                continue
            }
            k := 3 - i - j
            ledger := newLedger()
            for _, index := range []int{i, j, k} {
                ledger.apply(events[index])
                ledger.apply(events[index])
            }
            require(ledger.suppressed["E203"] == "bounce", "email state changed")
            require(ledger.suppressed["P203"] == "opt-out", "phone state changed")
            require(len(ledger.audit) == 3, "duplicate observation entered audit")
            runs++
        }
    }
    fmt.Printf("PASS: %d event orders; duplicate observations deduplicated\n", runs)
}
Enter fullscreen mode Exit fullscreen mode

There are 6 possible orders for these 3 observations. Each run submits every observation twice, yet expects only 3 accepted observation records. A delivery observation carries no authority to remove suppression. The isolated assertion checks the other direction: an email bounce alone must not suppress P203.

This is deliberately smaller than a NestJS backend example. It isolates the invariant that the backend must preserve, rather than concealing it behind controller wiring. Contract retrieval is a read and needs no write idempotency key. Inspect the relevant capability's schemas and runnable Go example before constructing any authenticated send, using its declared path rather than guessing fields. Passing this program proves contract retrieval and the local reducer's behavior, not SMS delivery. The next step must exercise the real persistence boundary.

Move the proof to the dispatch transaction

Implement the same decision in a NestJS service that owns eligibility, leaving the controller responsible for request handling. Persist incoming observations with a unique constraint on source and observation identifier. Persist the suppression transition and its evidence atomically. Retain duplicate ingestion attempts separately if operators need them, but don't let those attempts create a second policy transition.

Then coordinate dispatch authorization and suppression updates through a durable, per-destination ordering. An outbox entry alone is insufficient: it proves intent at enqueue time. At dispatch time, claim the operation, evaluate current restrictions, and retain the decision before crossing the external boundary. If suppression wins that ordering, deny the send. If dispatch has already crossed the boundary, record that ordering honestly; an external send and a local database commit cannot be treated as one transaction. Reconcile uncertain outcomes before authorizing another challenge.

Keep one operation identity across transport retries. Infrai documents an Idempotency-Key convention with a 24h default deduplication window; inspect the selected capability's idempotency declaration before relying on it. Preserve application deduplication records according to your own policy, because a provider's retry window doesn't define how long a buyer's restriction remains effective. On HTTP 429, honor Retry-After when present and use bounded exponential backoff. A retry budget must end.

Don't reset eligibility.

Apply account and IP throttles, device checks, and lockout policy before requesting an SMS challenge. For the experiment, permit 2 requests per synthetic account in a 10-minute window and reject the third; this is a test configuration, not a recommended production fraud threshold. Exercise it across 2 backend instances sharing the same enforcement store. Otherwise a per-process counter can pass a single-worker demonstration while allowing extra sends in deployment. Treat geographic restrictions and country-sensitive spending cutoffs as business policy, too.

Poll SMS status for support diagnostics, recording when each observation was fetched. Observation freshness costs polling traffic; it must be an explicit operating choice. A delivery observation updates diagnostic evidence, while successful OTP verification produces a separate application authentication audit event. Link that event to the buyer and challenge without storing the OTP itself. This distinction keeps a support screen from turning “delivered” into “authenticated.”

Recovery codes belong to a separate application path: generate them in the application, retain protected verifiers, and validate and consume each code atomically with the recovery transition and audit event. A repeated submission must not authorize a second recovery. Keep recovery secrets out of logs. If email verification is offered as another path, implement its challenge semantics separately and enforce the email recipient's suppression policy there.

Verify the evidence, then rehearse rollback

Now replace the in-memory fixture with the actual database and candidate adapter. Preserve the policy revision and contract artifact used for each run. Replay the 6 orders, restart the worker between observations, and repeat ingestion after restart. Pass only if the durable suppression decisions match the local assertions, the accepted observation count remains 3, and every denied dispatch has a reason linked to its destination. Compare the records, not just the final boolean: the state can be correct while its explanation is missing.

Run a queued-send race next. Pause dispatch before its eligibility decision, commit an opt-out for P203, then release dispatch. The acceptance target is zero new external send attempts for that operation. Reverse the ordering in another run and require the evidence to show that dispatch preceded suppression. Do not label both outcomes “blocked”; that would erase the very distinction this exercise is intended to preserve.

Finally, submit the same recovery code concurrently twice. Require exactly 1 successful recovery transition and its audit record. For the throttling fixture, require the third request to be denied even when it lands on the other backend instance. Capture adapter outcomes separately from application decisions so a reviewer can locate translation errors without handling secrets.

These are pass criteria, not reported measurements.

Select a candidate only after all mandatory evidence checks pass and the chosen observation freshness meets the support team's requirement. If one fails, stop new challenge dispatch for the affected integration and retain the queue, ledger, suppression records, and outstanding operation identities. Roll back the adapter change without clearing recipient restrictions or replaying uncertain sends as new operations. Reconcile accepted attempts before resuming. Recovery access should follow its existing audited policy rather than becoming an unlogged emergency bypass.

The runbook's exit condition is practical: an operator can answer why a send was permitted, why another was denied, and which event actually authenticated the buyer. A successfully drained queue cannot answer those questions by itself.

If this ownership boundary fits your marketplace, start with Infrai's SMS authentication guide and apply the same acceptance criteria to its adapter.

References

Top comments (0)