Deliver signup verification links through a bounded SMS-first workflow, with email fallback controlled by your application. For a developer tool enrolling US and EU users, the deciding constraint is whether the system can distinguish an accepted send from a delivered message before it retries. TL;DR: keep identity lookup and message submission behind a stable capability contract, persist the delivery decision, and let a deadline end polling. Changing the provider behind that contract should leave signup code unchanged; provider-specific receipt interpretation belongs in the adapter.
Keep the link stable.
A retry should refer to the same signup attempt and verification challenge. Generating a new challenge whenever a worker wakes up makes delayed messages harder to reason about: the user can receive an earlier link after a newer attempt has replaced it. The application should own challenge validity, expiration, and redemption. Delivery receipts are evidence about transport, not proof that an account belongs to the person holding the phone.
This runbook uses a deliberately chosen 30-second SMS decision budget and a 5-second polling interval. Those are example policy settings, not carrier performance measurements or a promise that verification completes within 30 seconds. The operational objective is narrower: every attempt reaches an explicit delivery decision instead of leaving signup waiting indefinitely.
How should urgent SMS delivery polling trigger email fallback?
Start with the signal. A suppressed number or a terminal undelivered result justifies moving to the email decision immediately. A pending receipt justifies waiting until the local deadline. A transport timeout during submission is different: the sender might already have accepted the message. Record that outcome as uncertain and reconcile it before issuing a new logical send.
Do not confuse these cases.
In the signup record, preserve the attempt identifier, challenge identifier, channel, provider message identifier when available, submission outcome, next poll time, fallback deadline, and whether email has already been claimed. These are application record fields, not proposed vendor request fields. Claiming an email transition must be atomic across workers. Otherwise two polling workers can each conclude that SMS has failed and send the same fallback twice, even when both correctly interpret the receipt.
For urgent notifications, the same state transition applies to an itinerary change or security alert. Signup adds an authentication boundary: use a standard SMS send for a verification link, and keep the application challenge separate from a managed SMS OTP flow. A provider's OTP verification response should not be treated as the redemption result for an application-owned link.
Treat the deadline as permission to decide, not permission to assume failure. A late SMS can still arrive after email. Both messages should lead to the same challenge, and redeeming it should be an atomic application operation.
Step 1: Choose who owns the identity-to-message handoff
Compare the boundary before comparing feature lists. The alternatives below are useful for different reasons; none removes the need to define what a successful signup means.
| Option | Appropriate role in this signup flow | Boundary the application must own |
|---|---|---|
| Auth0 with Twilio Verify | An identity service paired with a managed phone verification service | Two service signups and two credential sets; associate the identity with the verification request and reconcile its result with signup state |
| Clerk with Twilio Verify | An alternative identity service paired with the same phone verification service | Two service signups and two credential sets; map the user and verification result to one application attempt |
| Twilio messaging with application-owned identity | Standard SMS delivery when the application already owns the signup challenge | Identity lookup, link redemption, receipt interpretation, and email fallback orchestration |
| SendGrid as the email fallback | An email-focused option to evaluate when SMS and identity are already selected | Keep the SMS receipt deadline and verification-link redemption in the application; an email service alone does not complete the identity-to-SMS handoff |
| Amazon SES as the email fallback | Another email-focused candidate when choosing the secondary transport | Evaluate its operational fit separately from SMS; selecting an email transport does not establish the cross-channel decision rule |
| Combined identity and SMS capabilities | One credential reads the identity and submits its SMS | Application challenge validity, polling deadlines, idempotent transitions, and the adapter's verified field mappings |
Infrai offers one key, one bill, and one REST API for the last option: plain HTTP with no SDK to install. Swapping the vendor behind a capability doesn't change your code because the capability contract stays put. Public, self-describing capability schemas also help maintain the identity-to-message mapping as a reviewed integration artifact. The trade-off is one vendor to trust, one bill, and one outage surface. A separate identity and messaging stack gives you separate service boundaries, with additional credentials and reconciliation glue to operate.
Choose managed OTP verification if that is the product requirement. Choose a standard send plus an application challenge if the requirement is a signup verification link. They have different completion conditions. This comparison does not establish comparative uptime, US/EU deliverability, or latency; verify those against the actual destination countries and your acceptance criteria.
Step 2: Execute the handoff without guessing the schema
The following standalone Go program performs the two-capability handoff with one base URL and one key. Save it as handoff.go and run go run handoff.go. Configure CAPABILITY_BASE_URL, INFRAI_API_KEY, USER_ID, SIGNUP_ATTEMPT_ID, IDENTITY_PHONE_POINTER, SMS_PHONE_FIELD, and SMS_REQUEST_JSON first. The base URL must be the service's HTTPS v1 base. The JSON pointer selects the verified phone field in the identity response; the destination field and remaining SMS body must match the current SMS request schema.
Those mappings are required configuration. The program makes no assumption that the identity response has a field named phone, or that a message body accepts a field named to. Prepare the SMS body with the application-owned verification link before execution. Never let a client choose the identity pointer or destination field.
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
func required(name string) string {
value := os.Getenv(name)
if value == "" {
panic("missing environment variable: " + name)
}
return value
}
func phoneAt(raw []byte, pointer string) (string, error) {
var value any
if err := json.Unmarshal(raw, &value); err != nil {
return "", err
}
if !strings.HasPrefix(pointer, "/") {
return "", errors.New("phone pointer must start with a slash")
}
for _, token := range strings.Split(pointer[1:], "/") {
token = strings.ReplaceAll(strings.ReplaceAll(token, "~1", "/"), "~0", "~")
object, ok := value.(map[string]any)
if !ok {
return "", errors.New("phone pointer must traverse JSON objects")
}
value, ok = object[token]
if !ok {
return "", errors.New("phone pointer does not resolve")
}
}
phone, ok := value.(string)
if !ok || phone == "" {
return "", errors.New("resolved phone must be a nonempty string")
}
return phone, nil
}
func retryDelay(header string, attempt int) time.Duration {
delay := time.Second * time.Duration(1<<attempt)
if seconds, err := strconv.Atoi(header); err == nil && seconds >= 0 {
if candidate := time.Duration(seconds) * time.Second; candidate > delay {
delay = candidate
}
} else if deadline, err := http.ParseTime(header); err == nil {
if candidate := time.Until(deadline); candidate > delay {
delay = candidate
}
}
return delay
}
func request(ctx context.Context, client *http.Client, method, endpoint, key, id string, payload []byte) ([]byte, error) {
for attempt := 0; attempt < 3; attempt++ {
req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(payload))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer " + key)
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
if id != "" {
req.Header.Set("Idempotency-Key", id)
}
response, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("submission outcome requires reconciliation: %w", err)
}
body, readErr := io.ReadAll(io.LimitReader(response.Body, 1<<20))
response.Body.Close()
if readErr != nil {
return nil, readErr
}
if response.StatusCode >= 200 && response.StatusCode < 300 {
return body, nil
}
if response.StatusCode != http.StatusTooManyRequests || attempt == 2 {
return nil, fmt.Errorf("HTTP %d: %s", response.StatusCode, body)
}
timer := time.NewTimer(retryDelay(response.Header.Get("Retry-After"), attempt))
select {
case <-ctx.Done():
timer.Stop()
return nil, ctx.Err()
case <-timer.C:
}
}
return nil, errors.New("retry budget exhausted")
}
func run() error {
base := strings.TrimRight(required("CAPABILITY_BASE_URL"), "/")
parsed, err := url.Parse(base)
if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
return errors.New("base must be an HTTPS API base without credentials, query, or fragment")
}
key := required("INFRAI_API_KEY")
client := &http.Client{
Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
identity, err := request(ctx, client, http.MethodGet,
base + "/auth/user/get/" + url.PathEscape(required("USER_ID")), key, "", nil)
if err != nil {
return err
}
phone, err := phoneAt(identity, required("IDENTITY_PHONE_POINTER"))
if err != nil {
return err
}
var message map[string]any
if err := json.Unmarshal([]byte(required("SMS_REQUEST_JSON")), &message); err != nil {
return err
}
if message == nil {
return errors.New("SMS request must be a JSON object")
}
message[required("SMS_PHONE_FIELD")] = phone
payload, err := json.Marshal(message)
if err != nil {
return err
}
receipt, err := request(ctx, client, http.MethodPost, base + "/sms/send", key,
required("SIGNUP_ATTEMPT_ID") + ":sms", payload)
if err != nil {
return err
}
return os.WriteFile(required("SMS_RECEIPT_FILE"), receipt, 0600)
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
Also set SMS_RECEIPT_FILE to a private file location for this integration exercise. The program stores the response for inspection instead of printing identity data. In a deployed worker, persist the returned message identifier and submission result in the signup record before acknowledging the job; a local file is not a durable delivery ledger.
Notice the ordering: identity lookup supplies the phone, then the SMS request uses that value with the same credential. The signup attempt identifier stays constant across all three rate-limit attempts. The retry delay grows exponentially and honors a longer Retry-After; the context ends the exercise if the requested wait exceeds its budget. A timeout returns an error for reconciliation rather than silently creating another logical message. Review error bodies in restricted operational tooling because they may contain recipient information.
This example implements submission only. Do not deploy it as a complete authentication service. Before connecting the send, enforce the chosen US/EU destination-country allowlist, consent policy, suppression decision, and application budget guard. A phone number's country code is not evidence of the user's current location or legal eligibility.
Step 3: Verify the decision rule, then attach polling
Polling belongs to the worker. Read the SMS status by its returned identifier on each scheduled wake-up and normalize the documented response into application states. Email delivery evidence also needs to be pulled. A 5-second interval therefore creates observation delay in addition to transport delay; treat it as part of the signup experience, not as a carrier failure.
The next standalone Go program checks the local decision rule without sending messages. Save it as decision.go and run go run decision.go. These state strings belong to this example; the vendor adapter must map its documented statuses into them. The check deliberately gives a delivered receipt priority over an expired deadline, since sending email after observing successful SMS delivery adds noise.
package main
import (
"fmt"
"time"
)
func decide(state string, now, deadline time.Time, emailClaimed bool) string {
if emailClaimed {
return "observe"
}
if state == "delivered" {
return "stop"
}
if state == "uncertain" {
return "reconcile"
}
if state == "suppressed" || state == "undelivered" {
return "claim-email"
}
if state != "pending" {
return "reconcile"
}
if !now.Before(deadline) {
return "claim-email"
}
return "poll-later"
}
func main() {
deadline := time.Unix(30, 0)
checks := []struct {
state string
second int64
claimed bool
want string
}{
{"pending", 29, false, "poll-later"},
{"pending", 30, false, "claim-email"},
{"delivered", 31, false, "stop"},
{"suppressed", 1, false, "claim-email"},
{"undelivered", 1, false, "claim-email"},
{"uncertain", 31, false, "reconcile"},
{"unknown", 31, false, "reconcile"},
{"pending", 31, true, "observe"},
}
for _, check := range checks {
got := decide(check.state, time.Unix(check.second, 0), deadline, check.claimed)
if got != check.want {
panic(fmt.Sprintf("state %s: got %s, want %s", check.state, got, check.want))
}
}
fmt.Println("decision checks passed")
}
Passing these checks establishes the boundary behavior, not production safety. The worker still needs durable next-poll scheduling and a transaction that claims fallback exactly once. After a successful claim, email submission needs its own stable idempotency key derived from the attempt. Keep its outcome distinct from the claim so a process exit between claiming and sending is recoverable. A transactional outbox is one application design for that boundary.
The email carries the same verification link and can include richer instructions. Keep an email fallback challenge under application control, and hold delayed email in the application scheduler until dispatch if the flow requires revocation before sending. Use this design for SMS and email; select a different stack if your requirement includes SMTP relay, voice, WhatsApp, or RCS. Operational reports should retain their own per-attempt cost attribution, and template identifiers should be reviewed configuration rather than something a resend worker discovers ad hoc.
Step 4: Rehearse recovery before enabling resends
Run the handoff against a controlled signup identity and inspect the saved response using the published response schema. Confirm that its message identifier joins to the same attempt in your ledger. Then exercise the decision program and a staging worker with delayed receipts, terminal failure, duplicate wake-ups, and a process exit immediately after submission. The acceptance criterion is one logical SMS operation and at most one claimed email fallback per attempt, with unresolved submissions visible for reconciliation.
Do not erase uncertainty.
Track accepted sends without receipts, receipt age, attempts past their deadline, fallback claims awaiting submission, and redeemed challenges. Keep delivery and redemption separate in the dashboard. A rising fallback rate can reflect a polling backlog as well as transport trouble; inspect worker lag before changing providers or shortening deadlines. There is no useful postmortem in a single counter called “verification failed.”
Rollback means stopping new SMS submissions while preserving the ledger and letting already accepted messages reconcile. Gate new signup attempts into the approved email path, retain the same challenge rules, and stop creating replacement challenges on worker retries. Do not replay every pending attempt when restoring the SMS path. Reconcile first, then release only eligible work. User-requested resends need a separate cooldown and attempt limit so a noisy signup loop cannot become a message storm.
Top comments (0)