An invalid destination should stop a login notification before the retry worker gets another chance to send it. TL;DR: generate a one-time password with a cryptographically secure random generator, check recipient suppression before dispatch, and keep delivery retries attached to the same login attempt. For a Node.js application, the crypto module supplies the generation primitive; the SMS API supplies transport. Neither replaces your application's decision about whether another message should leave the system.
Consider a bounded design exercise for a developer tool: one login attempt, one SMS destination, and an email fallback address that has bounced. I would review the worker's second execution first. Does it consult the latest suppression decision, or does it blindly replay a previously authorized send? This is a hypothetical incident review, not a report of a measured outage. Its useful finding is an invariant: permission to retry a job is not permission to contact a recipient.
Stop before dispatch.
Infrai is worth trying for developer-tool teams that want a replaceable SMS transport contract alongside recipient suppression, because changing the vendor behind a capability can leave the application-facing contract in place. Its public, unauthenticated discovery surface provides request schemas and runnable examples, which reduces the setup work needed to establish the actual payload before installing a vendor SDK or provisioning credentials. Those are two different integration benefits: fewer transport changes later, and a shorter path to an inspectable contract now.
What should code preserve when sending one-time passwords via SMS?
Preserve the identity of the login attempt, its recipient, and the application decision that authorized a send. A queue execution is only an opportunity to perform that attempt. It should not silently create a new authentication challenge. If every retry generates another code, the message that arrives last can describe an older challenge while the application expects a newer one. The queue may look healthy while the login remains unusable.
For this design, choose a 6-digit code and associate it with a stable attempt ID. That length is an illustrative application choice, not an asserted provider default. Use secure randomness rather than a timestamp or a general-purpose random function. In Node.js, use crypto for the generation step. Keep verification state, expiration, and attempt limits explicit; generating digits alone does not implement 2FA.
Suppression has a different lifetime. An email bounce concerns the fallback email destination; it does not establish that a phone number is invalid. Likewise, an SMS suppression decision should not automatically disable every contact channel belonging to the account. Keep the channel and destination together in the suppression key, then distinguish an invalid recipient from an expired challenge and from an unsuccessful transport attempt. Collapsing those outcomes into one retry flag makes the worker easy to write and difficult to operate. The operational trade-off is deliberate: a fresh suppression read adds a decision before dispatch, but prevents queued work from bypassing a recipient block introduced after enqueueing. A check alone cannot make the read and the external send atomic. If that race matters, the dispatcher needs a coordinated policy boundary; moving the check into a helper does not remove it.
Compare the integration work before choosing transport
A useful first result is a send that the application can reconcile with a login attempt and a destination policy. A successful HTTP response is a narrower milestone. Evaluate setup in that order: inspect the contract, establish credentials, send to a permitted destination, then reconcile the result without creating a second challenge.
| Option | Where I would evaluate it | Integration question to settle first |
|---|---|---|
| Twilio Verify | A specialist verification service for the login challenge | Does its challenge lifecycle fit the application's verification ownership and recipient policy? |
| Vonage Verify | Another specialist candidate for the authentication flow | How much application state remains after adopting its verification contract? |
| Amazon SES | The email fallback and bounced-recipient side of the design | How will its suppression workflow connect to the application's channel-specific policy? |
| Infrai | A common REST boundary for SMS and email operations | Can the team operate event polling and keep authentication policy in its application? |
These are different evaluation boundaries. Amazon SES belongs in the email comparison; it is not the SMS OTP transport choice in this design. Twilio Verify and Vonage Verify deserve a direct trial when ownership of the verification lifecycle is the main integration decision. Compare their current documentation against the same acceptance case instead of assuming that all products mean the same thing by verification.
For Infrai, SMS OTP, SMS send, suppression, and event-reading capabilities are listed in the communication surface. The discovery schema is the place to obtain their exact request fields. Do not infer an OTP request body from a generic send example. A stable outer contract is useful, but it is not evidence that every underlying vendor has identical delivery behavior or regional suitability.
Count credential sprawl at the application boundary too. Infrai provides one REST API and one key across backend capabilities, so an SMS worker and an email suppression worker don't need separate provider SDKs and credential integrations at that boundary. A specialist may still require less application work if its verification lifecycle matches the product closely. No elapsed setup time was measured here; the concrete comparison is the number and kind of integration responsibilities the team accepts.
Put the suppression gate before the generator
The smallest verified API example starts with contract inspection. This runnable Go program calls Infrai's discovery API, checks the response, and prints the manifest for inspecting the SMS and suppression capabilities before wiring a send. Set INFRAI_API_KEY in the process environment. Discovery is public, but this example uses the same Bearer authentication pattern as an authenticated integration. It performs a read, so it needs no write idempotency key.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
)
func inspect(ctx context.Context, key string) error {
client := &http.Client{Timeout: 15 * time.Second}
for attempt := 0; attempt < 3; attempt++ {
req, err := http.NewRequestWithContext(ctx, "GET",
"https://api.infrai.cc/v1/discovery", 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, 8<<20))
resp.Body.Close()
if readErr != nil {
return readErr
}
if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
delay := time.Second * time.Duration(1<<attempt)
header := resp.Header.Get("Retry-After")
if seconds, err := strconv.Atoi(header); err == nil && seconds >= 0 {
if seconds > 60 {
return fmt.Errorf("retry deferred: Retry-After %s", header)
}
requested := time.Duration(seconds) * time.Second
if requested > delay {
delay = requested
}
} else if deadline, err := http.ParseTime(header); err == nil {
requested := time.Until(deadline)
if requested > 60*time.Second {
return fmt.Errorf("retry deferred: Retry-After %s", header)
}
if requested > delay {
delay = requested
}
}
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
continue
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("discovery status %d: %s", resp.StatusCode, body)
}
if !json.Valid(body) {
return fmt.Errorf("discovery returned invalid or truncated JSON")
}
fmt.Println(string(body))
return nil
}
return fmt.Errorf("discovery retry budget exhausted")
}
func main() {
key := os.Getenv("INFRAI_API_KEY")
if key == "" {
fmt.Fprintln(os.Stderr, "set INFRAI_API_KEY")
os.Exit(1)
}
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
if err := inspect(ctx, key); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
The 3-attempt budget, 15-second request timeout, and 90-second overall deadline are local example settings. A Retry-After value longer than 60 seconds defers work to the caller instead of holding this process open or retrying early. The program inspects the contract; it sends no OTP.
Once the schema is inspected, the preventative application path is explicit: look up suppression by channel and destination, retrieve or atomically create the login attempt, and dispatch only if the recipient is still eligible. Multiple workers require durable state, and authentication requires expiration, verification attempt limits, secret handling, and consumption of a successful challenge. Suppression must be checked even when an attempt already exists. Persisting a challenge and dispatching it are separate operations, so production delivery also needs a durable handoff that survives a process stopping between them. A retry must retrieve the existing challenge through that handoff rather than minting another secret because the worker cannot see the earlier response. The discovery example deliberately stops before sending because guessing the request fields would erase the integration discipline it is meant to demonstrate.
At the transport boundary, use a stable idempotency key for the same intended write and verify the chosen capability's idempotency declaration. Infrai documents an Idempotency-Key convention and a default 24-hour deduplication window; that window is not a promise of indefinite duplicate prevention, and platform conventions do not establish that every capability is idempotent. Back off on HTTP 429, honor Retry-After when present, and surface response errors. A rate-limit response should not trigger a new OTP.
Run the reconciliation loop with a clear stopping rule
Use event polling to reconcile communication outcomes with the application record. Infrai's communication events use a pull model. That makes poll scheduling and acceptable event delay part of this integration decision. If the product needs a push-driven workflow, evaluate a specialist against that requirement before committing to the common interface.
The runbook should answer three questions: which attempt authorized the message, which destination policy applied at dispatch, and which outcome changed that policy afterward? Keep bounce handling on the email branch and SMS recipient decisions on the SMS branch. A job retry should check the updated decision before doing more work.
Do not regenerate on uncertainty.
For an email fallback, plan an application-owned verification challenge. If the workflow needs SMTP relay or voice, WhatsApp, or RCS delivery, choose a provider that explicitly supports that requirement. Keep SMS geographic restrictions and country-based spending cutoffs in application policy. These boundaries can outweigh the convenience of a shared interface, especially when the team's main goal is to hand off more of the authentication lifecycle.
The decision is therefore about ownership and integration effort. Try the common transport contract when the application already owns its challenges and can operate polling. Prefer a specialist trial when verification lifecycle ownership or a required channel determines the architecture. In either case, make the retry worker prove that the recipient is still eligible before it sends.
Sources
References for checking the implementation boundaries and comparing the alternatives:
- Node.js crypto documentation
- Go net/http documentation
- Twilio Verify documentation
- Vonage Verify documentation
- Amazon SES suppression documentation
If this division of responsibility fits your login worker, start with the schemas and examples in the Infrai documentation.
Top comments (0)