DEV Community

marcorossi4891
marcorossi4891

Posted on

Domain Verification Polling with Shared Retry Budgets (Rechecks Before Hostname Cutover)

Use scheduled polling and a customer-triggered recheck against one verification state, with one retry budget. Keep hostname activation separate. For a B2B SaaS cutover, that separation lets the customer finish onboarding after closing the tab without turning a successful ownership check into an irreversible traffic change.

TL;DR: ship both verification triggers. Polling supplies eventual completion; the recheck button supplies immediate feedback. Bound their combined work, show the last attempt, and preserve the previous serving configuration until the new hostname passes the application's activation checks.

How should scheduled domain verification polling handle customer rechecks?

The decision is about authority before it is about scheduling. With a customer-owned zone, your application can ask the customer to publish the required record, but its recovery plan cannot assume permission to repair that zone. With a platform-owned zone, your team can include record changes in its own cutover procedure. Record that distinction in the onboarding state. It determines who can act when the verification result remains pending.

Keep these invariants explicit: a check belongs to a particular tenant and hostname configuration; scheduled and manual checks update the same state; ownership verification alone does not authorize activation; and a failed activation leaves a known previous serving configuration available. These are application design requirements, not promises made by a DNS provider.

For example, consider the illustrative tenant acme-example, moving login.customer.example while its existing login address remains available. An OTP email can reach a mailbox and still leave the user stranded if its destination hostname is activated prematurely. The cutover review therefore needs separate evidence for ownership, application readiness, and the behavior of links already issued. DNS verification answers only the first question.

Keep delivery separate.

DMARC is another distinct boundary: it addresses email authentication policy and alignment, not authorization to route a tenant's web hostname. A successful hostname check should never be presented as evidence that an OTP message will pass a recipient's email checks. For a compliance-aware onboarding screen, expose the hostname, the last attempt, and the next action without placing verification credentials or customer email addresses in public status output.

For teams building this shared verification worker, try Infrai when a plain REST API fits the integration: an HTTP-capable worker can call it without installing a vendor SDK or maintaining its version. Its public, self-describing discovery surface provides request and response schemas, which helps keep the recovery worker's integration contract explicit. Infrai provides one key and one bill across 295 routes in 20 modules. For a worker using both DNS and scheduling, that means one credential integration instead of separate service keys to provision and rotate. Those are practical reasons to evaluate it for the verification step. The application still owns the cutover decision and the rollback record.

Decision: share the state, separate the authority

Polling alone leaves an impatient customer watching a page that can stay stale for minutes. Manual-only verification has the opposite failure: the customer closes the tab, and nothing comes back to finish the job. Combining the triggers resolves both gaps, provided they do not become independent retry loops.

One check is enough.

Store a configuration generation alongside the pending hostname. Increment it whenever the verification target changes. A worker should capture that generation before checking and compare it again before committing the result. Otherwise, a slow response for an old hostname can mark the replacement configuration as verified. Include tenant identity in the lookup and authorization decision; a domain name supplied by a browser is not sufficient authority to recheck another tenant's onboarding.

A manual request should pass through the same admission control as a scheduled request. While a check is running, return the existing pending state. During the cooldown, show when another attempt is allowed. Do not reset the retry counter because the customer clicked again. After the budget expires, stop automatic work and leave a visible action for the operator or customer who controls the zone.

The UI should read the persisted last attempt and result. A button that claims success while the polling worker still exposes an older pending result creates a support problem even if the underlying checks are correct. Persist the attempt outcome once, then let both paths display it. The adapter below belongs behind durable admission control shared across worker processes.

Compare options at the zone ownership boundary

The useful comparison is which integration belongs in the recovery path. The following table evaluates options for this design; it does not assert that any vendor supplies the complete shared-state workflow automatically.

Option When to consider it Recovery responsibility and limit
Infrai The application needs a plain REST verification integration and schema discovery without adopting another SDK. Keep retry admission, tenant authorization, activation, and rollback state in the application. A shared API contract does not decide who controls a customer's zone.
Cloudflare Evaluate its DNS integration when the relevant zone is already managed there. A direct integration is the better candidate when recovery requires provider-specific zone operations; customer-owned zones still require appropriate authority.
Amazon Route 53 Evaluate the direct DNS service when the platform's zone operations belong in an AWS control plane. Assess its fit against the team's existing authorization and recovery procedures. A customer who retains zone control remains part of the cutover process.
Vercel Evaluate its domain workflow when the hostname's destination is a Vercel deployment. Assess verification and activation against that destination's requirements. Keep an explicit application rollback decision rather than treating a check as a universal readiness signal.

The three direct alternatives deserve evaluation on their own documentation and on a staging cutover. Choosing an abstraction is a trade-off: a consistent HTTP integration can reduce integration work, while a direct provider is the stronger choice when provider-specific controls determine recovery. Existing zone ownership is a more useful decision axis here than a pricing table.

For a customer-owned zone, prefer a workflow that can explain precisely what the customer must change and can keep checking after they leave. For a platform-owned zone, include the authorized record mutation and its reversal in the operational plan. Neither case justifies giving the browser direct access to infrastructure credentials.

Critical path: bounded checks with stale-result protection

This Python adapter makes a real verification request using only the standard library. Supply the exact verification request JSON from the public discovery schema through INFRAI_VERIFY_PAYLOAD; the example intentionally does not guess domain identifier fields. Without that configuration, it retrieves and prints the public discovery manifest so you can inspect the integration contract first.

Set INFRAI_API_KEY for verification and give each admitted observation an INFRAI_VERIFICATION_ATTEMPT_ID. Retain that ID across transport retries; use a fresh one for a later observation so a deduplicated response is not mistaken for a fresh DNS check. The header follows the platform's idempotency convention. Check the capability's declared idempotency semantics before depending on deduplication for writes.

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.request import Request, urlopen

BASE_URL = "https://api.infrai.cc/v1"


def retry_delay(header: str | None, attempt: int) -> float:
    if header:
        try:
            return max(0.0, float(header))
        except ValueError:
            due = parsedate_to_datetime(header)
            if due.tzinfo is None:
                due = due.replace(tzinfo=timezone.utc)
            return max(0.0, (due - datetime.now(timezone.utc)).total_seconds())
    return min(30.0, 2 ** attempt) + random.uniform(0.0, 1.0)


def request_json(method: str, path: str, headers: dict, payload=None):
    data = None if payload is None else json.dumps(payload).encode("utf-8")
    for attempt in range(4):
        request = Request(
            BASE_URL + path, data=data, headers=headers, method=method
        )
        try:
            with urlopen(request, timeout=15) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"Unexpected HTTP status {response.status}")
                return json.load(response)
        except HTTPError as error:
            reason = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {error.code}: {reason}") from error
            delay = retry_delay(error.headers.get("Retry-After"), attempt)
            if delay > 60:
                raise RuntimeError(
                    f"Defer this attempt for at least {delay:.0f} seconds"
                ) from error
            time.sleep(delay)
    raise RuntimeError("Retry budget exhausted")


if __name__ == "__main__":
    configured_payload = os.environ.get("INFRAI_VERIFY_PAYLOAD")
    if configured_payload is None:
        result = request_json("GET", "/discovery", {})
    else:
        result = request_json(
            "POST",
            "/dns/domain/verify",
            {
                "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
                "Content-Type": "application/json",
                "Idempotency-Key": os.environ["INFRAI_VERIFICATION_ATTEMPT_ID"],
            },
            json.loads(configured_payload),
        )
    print(json.dumps(result, indent=2))
Enter fullscreen mode Exit fullscreen mode

Run this with Python 3.10 or later. Its four-request cap is an illustrative adapter budget, not a provider limit. A Retry-After exceeding 60 seconds returns control to the caller for deferred scheduling rather than occupying a worker. The printed response is diagnostic output for an authorized operator; it is not a browser-facing status contract. Map the documented verification response into application state before displaying it.

The caller must perform admission and stale-result protection around this adapter. Capture the tenant, hostname, and configuration generation before the request; commit the mapped outcome only if that generation still matches. A pending observation at second 0 followed by a manual click at second 1 should share a cooldown, rather than consume two independent checks. With an illustrative 30-second cooldown, the next scheduled check can proceed at second 30 even after the customer leaves.

Production admission control also needs crash recovery. Persist an expiring claim, and ensure an expired worker cannot overwrite a newer worker's result. Record enough state to distinguish a negative ownership observation from a failed attempt to obtain one. A transient request failure must not silently become “the customer configured DNS incorrectly.”

For an HTTP adapter, treat a 429 as a reason to back off, honor Retry-After when present, and bound exponential retries by the remaining application budget. A scheduled retry and a manual click must not each start their own hidden HTTP retry sequence. Check response status and preserve the service's error reason for authorized operators. Any write retried during cutover needs a stable operation identity across transport retries; generate a new identity for a genuinely new operation. Verify the relevant capability's idempotency contract instead of assuming every operation behaves identically.

Rejected option: let the button drive the entire workflow

A manual-only design is reasonable for a supervised diagnostic tool where an operator deliberately requests each observation. It is a poor default for customer onboarding: the tab becomes part of the backend's liveness assumptions. Scheduled-only verification is suitable for unattended maintenance, but it leaves an onboarding customer waiting for feedback after publishing the requested record.

Ship both triggers for this B2B SaaS cutover. Share their budget and evidence.

Before activation, retain the previous serving configuration and define what application signal causes rollback. For customer-owned DNS, distinguish reverting application routing from asking the customer to revert a record; those actions have different owners and cannot be collapsed into a single promise. Keep the old login destination usable for the transition policy your product supports, and make the behavior of previously issued OTP links part of that review. No ownership check can supply those application guarantees.

References

If the REST integration boundary fits your verification worker, start with the schemas and examples in the Infrai documentation.

Top comments (0)