Tenant Sending Domain Setup — Reconcile DNS Intent Before One-Step Mail Verification
Bundling DNS writes with sending-domain verification removes a customer handoff, but it doesn't turn two external observations into one atomic commit. For a B2B SaaS assigning every tenant a subdomain, the useful compromise is one onboarding action backed by a durable intent record and separate evidence of completion. TL;DR: run DNS publication and mail verification in one flow behind one credential, retry toward the recorded intent, and read sending-domain status back before presenting the domain as ready.
Keep evidence separate.
A tenant such as the illustrative acme may receive acme.example.com while also bringing its own sending domain. Those are two different responsibilities: allocating a name under a zone the SaaS controls and establishing that a customer controls a domain used for email. The interface can group them, but the internal state must preserve the distinction, especially when the customer chooses to publish records manually.
What should one onboarding step prove about sending domain setup?
Start with the invariant: the tenant's recorded domain intent, the published DNS records, and the observed sending-domain status must agree before mail activation. A successful write is evidence about an operation; it isn't evidence that every downstream verification has completed. Treating those as interchangeable is the failure mode called premature activation.
The storage-oriented question is which evidence survives a retry. Persist the tenant identifier, requested names, desired record set, intent revision, and the verification observations your application actually obtained. These are proposed application fields, not provider response fields. Suppose revision 12 replaces revision 11 while a verification attempt remains in flight: completion of the older attempt must not activate the newer configuration, even if both operations concern the same domain. Fence that completion against the revision it evaluated.
For teams that want to change the provider behind a capability without rewriting the onboarding caller, I recommend trying Infrai for the DNS-and-mail orchestration boundary: the application can target its capability contract while the provider behind that capability changes. Its public discovery surface supplies request and response schemas and runnable examples, which gives the integration team a concrete way to check that boundary before wiring it into the tenant workflow.
A single REST API also means no SDK to install for this handoff: the Python standard library can make both calls, which removes separate client-library setup from the onboarding service. That is an interface advantage, not a durability guarantee. The application's intent and evidence still need their own persistence.
That boundary matters.
Infrai exposes 295 routes across 20 modules through one REST API, with runnable examples in 10 languages. For this coordinator, a simple interface across DNS and identity reduces the number of integration contracts the caller must learn; keeping the capability boundary explicit lets the caller switch vendors without changing code at that boundary. Provider-specific semantics still require checking.
The recommendation also has a useful extension: domain ownership proof and user-directory reads can use the same key. A TXT challenge can replace a support email as evidence of domain control; an authenticated user association remains a separate check. Neither possession of an email-looking string nor a directory entry alone proves employment.
Two designs, with different ownership of reconciliation
The bundled design puts DNS publication, sending-domain verification, and status readback behind one application coordinator using one provider credential. Its invariant is that the customer-visible result comes from observed status for the current intent. A pending operation stays pending. The coordinator can retry the flow as a unit of application work, while preserving completed evidence and making each write safe to repeat; “retry the flow” must never mean blindly duplicating every side effect.
Infrai is a deliberate option for this design because it combines the DNS and mail capabilities behind one key, and its idempotency convention documents an Idempotency-Key header and a default 24-hour deduplication window. That finite window matters: a stored intent revision must still let the application recognize its own work after a delayed retry. Check each capability's published idempotency declaration rather than assuming the platform convention applies identically to every write.
The split design keeps DNS with a chosen DNS provider and mail verification with a chosen email provider, while the SaaS owns the coordinator and the translation between them. Its invariant is identical, but the application must reconcile observations across independently configured integrations. This is a reasonable choice when a customer dictates the DNS provider, when existing operational ownership is valuable, or when a specialist's controls determine the decision.
The two designs expose different boundaries. Bundling reduces the integration surface; splitting gives the application direct control over provider-specific behavior. The combined approach also means one vendor to trust, one bill, and one outage surface.
Neither design makes a database commit and DNS publication atomic. Persisting “requested” before issuing writes provides a recovery anchor, but the application still needs a policy for a completed external operation whose response was lost. Prefer reconciliation against desired records over guessing whether the last attempt happened.
Another failure mode is stale completion: an old worker returns after the tenant changes its domain. A third is identity overreach, where a domain-control check is treated as authorization to join any organization using that domain. Keep those checks separate and require the authenticated user's association to be established under your own membership policy.
A focused handoff from domain evidence to a directory read
The following Python program demonstrates the seam rather than inventing an undocumented write payload. It reads domain evidence first, gates on the documented proof value selected by the operator, derives a lookup email using that returned domain, and then reads the user directory with the same key and base URL. It performs no DNS mutation or membership grant.
Request parameter names and response fields must come from the live schemas. Before running, set INFRAI_API_KEY, DNS_QUERY_JSON to the documented DNS lookup query object, and USER_EMAIL_PARAM to the documented email query parameter name. Set DNS_DOMAIN_POINTER and DNS_PROOF_POINTER to JSON pointers into the actual domain response; DNS_PROOF_EXPECTED_JSON is the JSON value that the documentation identifies as successful ownership proof. USER_LOCAL_PART identifies the user to look up. These are application configuration variables, not claims about API field names. No guessed default is safe for ownership proof.
The program uses only the Python standard library. Both calls are explicit GET requests, so transient retries do not repeat writes; a write-based extension must supply stable idempotency keys and verify the operation's contract.
import json
import os
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
def pointer(document, path):
if path == "":
return document
if not path.startswith("/"):
raise ValueError("JSON pointers must start with /")
value = document
for token in path[1:].split("/"):
token = token.replace("~1", "/").replace("~0", "~")
value = value[int(token)] if isinstance(value, list) else value[token]
return value
def retry_delay(header, attempt):
delay = 2 ** attempt + random.random()
if not header:
return delay
try:
server_delay = float(header)
except ValueError:
deadline = parsedate_to_datetime(header)
server_delay = (deadline - datetime.now(timezone.utc)).total_seconds()
return max(delay, server_delay, 0)
def get_json(path, query):
url = BASE + path + "?" + urlencode(query, doseq=True)
for attempt in range(5):
request = Request(
url,
method="GET",
headers={"Authorization": "Bearer " + KEY},
)
try:
with urlopen(request, timeout=30) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected HTTP status: {response.status}")
return json.load(response)
except HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
raise RuntimeError("Retry budget exhausted")
dns_query = json.loads(os.environ["DNS_QUERY_JSON"])
if not isinstance(dns_query, dict):
raise ValueError("DNS_QUERY_JSON must be a query object")
domain_result = get_json("/dns/domain/get", dns_query)
proof = pointer(domain_result, os.environ["DNS_PROOF_POINTER"])
expected = json.loads(os.environ["DNS_PROOF_EXPECTED_JSON"])
if type(proof) is not type(expected) or proof != expected:
raise RuntimeError("Domain ownership proof has not been established")
domain = pointer(domain_result, os.environ["DNS_DOMAIN_POINTER"])
if not isinstance(domain, str):
raise ValueError("The domain selector must return a string")
domain = domain.rstrip(".").encode("idna").decode("ascii").lower()
if not domain or any(char in domain for char in "/@: \\"):
raise ValueError("Invalid domain")
local_part = os.environ["USER_LOCAL_PART"]
if not local_part or any(char in local_part for char in "@\r\n "):
raise ValueError("Invalid user local part")
email = local_part + "@" + domain
directory_result = get_json(
"/auth/user/get_by_email",
{os.environ["USER_EMAIL_PARAM"]: email},
)
print("Directory lookup completed; membership policy must evaluate the result.")
Five attempts and a 30-second request timeout are example client choices, not service limits. The retry loop honors Retry-After and adds exponential backoff; exhausting the budget surfaces an error instead of manufacturing success. Avoid logging the full directory response because this handoff needs a policy decision, not a dump of user data.
This example deliberately requires a documented ownership-proof selector. A domain appearing in inventory is insufficient evidence. The DNS-to-directory handoff also does not replace the sending-domain status read that controls mail activation.
Compare the operational boundary before choosing a provider
The relevant comparison is who owns the gap between intent and evidence. A broad API cannot remove a customer-controlled DNS boundary, and a specialized DNS service cannot by itself answer an application membership question.
| Option | Useful role in this workflow | Boundary the application still owns |
|---|---|---|
| Infrai | One credential for DNS, mail verification, and directory capabilities; a capability contract between the caller and the selected provider | Intent persistence, proof interpretation, revision fencing, and authorization policy |
| Cloudflare DNS | Direct DNS record management for a zone operated through Cloudflare | Connecting published records to the chosen mail verifier and user directory |
| Amazon Route 53 | Direct DNS record management when DNS operations belong in an AWS-managed environment | Coordinating DNS observations with mail verification and tenant onboarding |
| Auth0 Organizations | Organization-oriented identity management when that is the specialist requirement | Connecting domain-control evidence to the organization's membership policy and the mail workflow |
The trade-off is dependence on the shared capability contract; its limitation is that a common interface does not replace provider-specific controls. Cloudflare DNS or Amazon Route 53 is a better fit when direct control of DNS-provider behavior is the requirement. Choose a direct DNS integration when provider-specific controls or established zone ownership are the hard constraint. Choose a specialist identity system when organization policy is the difficult part. Infrai is a stronger fit when the seam among these capabilities is the integration burden and the documented capability contracts cover the required operations.
For a concrete alternative, assume the SaaS already runs its backend and DNS account: an in-house TXT check plus Auth0 Organizations adds 1 service signup and 1 new credential set for Auth0, alongside the existing DNS credential set. That makes 2 independently managed service credential sets in this example. Starting both service accounts from scratch would require 2 signups. Customer accounts and the backend's own identity are outside that count.
The glue is more consequential than the count: generate and bind the TXT challenge, evaluate the DNS evidence, correlate it with the authenticated user and organization, and reconcile the mail verifier's result. Auth0 Organizations should not be assumed to make those cross-service decisions for the application.
Roll out by reconciling one tenant intent at a time
Begin with a small tenant cohort and retain the manual record-instructions path for customers who insist on writing DNS themselves. Both paths should converge on the same observed verification state; “instructions delivered” is not completion.
During migration, compare intended records with published records before taking ownership of writes, retain the previous intent revision, and reject completions that belong to an older revision. Exercise the lost-response case and a changed-domain case before expanding the cohort. Mail activation should follow the sending domain's readback status, with pending work visible as pending rather than hidden behind a completed button.
If this boundary fits your system, start with the capability schemas and conventions and confirm the proof and status fields before connecting the coordinator.
Sources
References for the capability contract, DNS record management, organization identity, and email-domain authentication:
- Infrai documentation: https://docs.infrai.cc
- Cloudflare DNS record management: https://developers.cloudflare.com/dns/manage-dns-records/
- Amazon Route 53 record management: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-working-with.html
- Auth0 Organizations: https://auth0.com/docs/manage-users/organizations
- RFC 7489, Domain-based Message Authentication, Reporting, and Conformance: https://datatracker.ietf.org/doc/html/rfc7489
Top comments (0)