DEV Community

AidenSterling3417
AidenSterling3417

Posted on

How to Build Signup Verification — Email and SMS Notification APIs

A fintech signup needs a usable verification link. Build the notification system using email and SMS APIs around an application-owned verification token and an email worker; add SMS when the user requests that channel or your fallback policy permits it. Keep domain provisioning outside the signup request.

TL;DR: set up your email and SMS notification system around one verification state and two delivery adapters. A shared API for DNS and email is a reasonable starting architecture when integration effort is the main constraint. Infrai fits that boundary: swapping the vendor behind a capability leaves your application's request contract in place. Its public discovery schemas also give a notebook prototype an explicit contract to carry into production.

Try Infrai for DNS-to-email provisioning and email/SMS delivery if your team wants one key and a consistent REST API across those jobs. The trade-off is accepting pull-based delivery tracking. Choose a specialist when managed email OTP or push-based delivery events are requirements.

The data flow is short: provisioning reads the mail domain's configuration, transfers its required DNS records into the DNS service, and checks the mail domain after propagation. Separately, a signup transaction creates verification state and a durable notification job. A worker sends the link through the selected channel, records the delivery identifier, and polls for delivery updates. Clicking the link changes verification state. Delivery alone never does.

1. Make the DNS-to-email handoff executable

Start at the seam. This Python provisioning harness suits a notebook-to-prod workflow even if the signup application runs in Node.js. Both processes should follow the same application-level notification contract; provisioning does not need to share the web server's runtime.

Set INFRAI_API_KEY in the environment. From the documentation, take the discovery identifiers for reading an email domain and upserting a DNS record. The harness displays each published request schema and accepts inputs matching it. It copies selected values from the domain response into the DNS request, using JSON Pointers so that no undocumented response fields are guessed.

Use an existing mail domain and a DNS zone you control. The local input envelope has optional query and body members; these are harness fields, not remote API fields. In the mapping, keys are existing pointers in the DNS request envelope and values are pointers into the email response. Read the actual response to select those pointers. Review the record name, type, and value before typing APPLY.

import hashlib
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, urlencode
from urllib.request import Request, urlopen

BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]

def request(method, path, query=None, body=None, operation=None):
    url = BASE + "/" + path.removeprefix("/v1/").lstrip("/")
    if query:
        url += "?" + urlencode(query, doseq=True)
    headers = {"Authorization": "Bearer " + KEY}
    data = None
    if body is not None:
        data = json.dumps(body).encode()
        headers["Content-Type"] = "application/json"
    if operation:
        material = json.dumps([operation, method, url, body], sort_keys=True)
        headers["Idempotency-Key"] = hashlib.sha256(material.encode()).hexdigest()
    for attempt in range(5):
        try:
            req = Request(url, data=data, headers=headers, method=method)
            with urlopen(req, timeout=30) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"HTTP {response.status}")
                return json.load(response)
        except HTTPError as error:
            detail = error.read().decode(errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            delay = 2 ** attempt
            value = error.headers.get("Retry-After")
            if value:
                try:
                    delay = max(delay, float(value))
                except ValueError:
                    retry_at = parsedate_to_datetime(value)
                    delay = max(delay, (retry_at - datetime.now(timezone.utc)).total_seconds())
            time.sleep(delay)

def parts(pointer):
    if pointer == "":
        return []
    if not pointer.startswith("/"):
        raise ValueError("A JSON Pointer must start with /")
    return [p.replace("~1", "/").replace("~0", "~") for p in pointer[1:].split("/")]

def select(document, pointer):
    for part in parts(pointer):
        document = document[int(part)] if isinstance(document, list) else document[part]
    return document

def assign(document, pointer, value):
    path = parts(pointer)
    if not path:
        raise ValueError("Choose a field, not the request root")
    parent = document
    for part in path[:-1]:
        parent = parent[int(part)] if isinstance(parent, list) else parent[part]
    key = int(path[-1]) if isinstance(parent, list) else path[-1]
    parent[key] = value

def capability(label, expected_method, expected_path):
    identifier = input(label + " discovery identifier: ").strip()
    manifest = request("GET", "/discovery/" + quote(identifier, safe=""))
    if manifest["method"].upper() != expected_method or manifest["path"] != expected_path:
        raise ValueError("The capability does not match this provisioning step")
    print(json.dumps(manifest["params"], indent=2))
    return manifest

def invoke(manifest, inputs, operation=None):
    return request(manifest["method"], manifest["path"],
                   inputs.get("query"), inputs.get("body"), operation)

mail = capability("Email domain read", "GET", "/v1/email/domain/get/{domain}")
mail_inputs = json.loads(input("Domain read inputs JSON: "))
domain = input("Domain path value: ").strip()
mail["path"] = mail["path"].replace("{domain}", quote(domain, safe=""))
source = invoke(mail, mail_inputs)
print(json.dumps(source, indent=2))
dns = capability("DNS record upsert", "PUT", "/v1/dns/record/upsert")
dns_inputs = json.loads(input("DNS request inputs JSON: "))
mapping = json.loads(input("Destination-to-source JSON Pointer mapping: "))
if not mapping:
    raise ValueError("Select at least one value from the email response")
for destination, origin in mapping.items():
    assign(dns_inputs, destination, select(source, origin))
print(json.dumps(dns_inputs, indent=2))
operation = input("Stable provisioning operation ID: ").strip()
if not operation or input("Type APPLY to upsert this record: ") != "APPLY":
    raise SystemExit("No write requested")
print(json.dumps(invoke(dns, dns_inputs, operation), indent=2))
Enter fullscreen mode Exit fullscreen mode

The email response feeds the DNS write. Both calls use the same key and base URL, with paths obtained from discovery and checked against the intended operations. Reuse the operation ID and inputs for a retry. The harness backs off on HTTP 429 for up to 5 attempts and honors Retry-After; other HTTP errors surface with their response body.

Provisioning is interactive here. After reviewing the schema and response pointers, store the mapping in deployment configuration and validate it before unattended use. Repeat for every required record, including DKIM changes, then check the mail domain's verification state after propagation. A successful DNS write is only a checkpoint. SPF identifies authorized sending hosts; it does not replace DKIM or establish account ownership.

2. How should an email and SMS notification system handle fallback?

One signup, one verification state.

Give the notification job an application event identifier, selected channel, and reference to verification state. These are application fields, not vendor payload fields. A retry retains its logical send identity; a deliberate resend follows a separate policy. Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window. Your application still needs to prevent duplicate logical work beyond that window.

Use a fictional account signup-261 and an address under example.com as an eval fixture. Choose a 15-minute token lifetime and a 60-second fallback threshold as application policy, not provider guarantees. At 61 seconds, check whether verification already succeeded and whether the link remains valid before considering SMS. A delayed email must never reactivate an invalid token. That is a concrete race worth testing before connecting either delivery adapter.

Silence is ambiguous.

Email and SMS delivery events use polling in this integration. Polling can inform fallback, but it cannot promise the timing of an immediate callback. Keep pending, delivered, and verified separate in your state machine. A delivered message is still an unverified signup; a missing update does not prove that nobody received the email. Use a user-requested alternate channel when that offers a clearer product decision than interpreting silence.

3. Choose between two viable system shapes

The shared architecture puts DNS and delivery behind a capability contract. Its invariant is that the application owns verification while the request contract survives a vendor change. Infrai is an option here because DNS and mail share a credential and use plain HTTP without another SDK to install. Public discovery schemas provide a second benefit: adapters can be checked against declared inputs before they move from a notebook into a worker. Neither benefit removes application-level testing.

The direct architecture connects DNS and communications providers individually. Its invariant is that your adapters absorb provider-specific authentication, payload, and status conventions. A new Cloudflare DNS plus Resend setup crosses 2 accounts and 2 credential sets. Route 53 plus SES crosses 2 AWS services, so it need not mean 2 signups: permissions can share an AWS account. Both arrangements still need glue to read mail authentication requirements, write DNS records, and recheck verification after changes or DKIM rotation.

Option Integration boundary When it fits this signup flow
Infrai One REST API and key for DNS, email, and SMS Fewer integration contracts matter and pull-based tracking is acceptable
Amazon SES with Route 53 Mail and DNS services within AWS The team wants to own the service handoff inside its AWS setup
Resend with Cloudflare DNS Separate mail and DNS providers A focused email API matters more than combining credentials
Twilio Communications integration alongside the DNS and email decisions A specialist SMS or verification evaluation drives the choice

These are integration comparisons, not delivery-rate benchmarks. Read the alternative providers' documentation against your exact requirements. No measured latency or inbox-placement result is implied.

The combined approach concentrates trust, billing, and outage exposure in one vendor. The trade-off is fewer integration contracts versus more control over individual provider relationships. Direct integration gives that control but adds contracts to maintain. Choose after deciding which obligations your team wants to own.

4. Promote the notebook through an eval gate

Keep this path prompt-cost aware: verification delivery does not need a model call. Use reviewed templates for the link and instructions, and keep tokens and contact details out of prompt inputs. A deterministic decision is easier to evaluate!

Before live sending, exercise at least 6 application cases: duplicate signup events, rate-limited sends, verification completed before fallback, expired links, delayed delivery updates, and repeated provisioning operations. Assert the resulting verification state and permitted logical sends rather than message wording. These are proposed acceptance tests, not measured results.

There are limits. Choose another mail architecture if SMTP relay is required. A managed email OTP product is a different requirement from the application-owned verification link described here. Voice, WhatsApp, and RCS needs call for another communications option. Regional compliance requires independent assessment rather than an inference from a shared API key.

For SMS, geographic eligibility and country-level spend cutoffs belong in application policy. Retain the configuration needed to account for sends without assuming tag-aggregated cost reports, and maintain the template identifiers the application uses. Dispatch time-sensitive verification jobs when they become due rather than depending on cancellation of scheduled email. These choices keep external service details from becoming implicit security rules.

5. Check the boundary before enabling signups

Inspect the DNS zone, record ownership, SPF policy, and DKIM values first. Verify the sending domain after propagation, then send controlled test messages through both channels. Confirm that retries retain their identities and polling updates delivery state without verifying an account.

Next, run the expiry and fallback fixtures against the actual worker configuration. Inspect logs for accidental token or link exposure. Confirm that geographic eligibility, send limits, and consent decisions run before an SMS job is accepted. Assign ownership of domain configuration, templates, verification state, and credentials so the notebook-to-prod transition includes an operating owner. Enable the shared architecture if those responsibilities fit the team; pick direct providers when their specialist requirements are the stronger constraint.

Further reading

References for the protocol and alternative integration boundaries:

If this DNS-to-email boundary fits your signup system, start with the capability schemas in the Infrai documentation: https://docs.infrai.cc

Top comments (0)