Run scheduled reconciliation between tenant records and the live DNS zone list, but keep domain ownership proof as a separate onboarding gate. The deciding constraint is who owns the zone: a platform inventory can account for platform-managed zones, while customer-managed zones need their own ownership evidence. A zone appearing in an account does not, by itself, establish that the tenant requesting onboarding controls the domain.
Short answer: join tenant records to live zones by zone identifier, report both orphan and missing zones as metrics, and send discrepancies for human review. Do not auto-delete on the first mismatch. Keep customers with externally managed zones out of the platform's missing-zone count.
For a developer tool accepting a customer's domain before onboarding completes, this distinction changes the acceptance decision. Inventory reconciliation answers whether expected infrastructure exists. Ownership verification answers whether the applicant has established control. An email or OTP workflow adds another reason to keep the questions separate: the ownership decision should not silently become a promise about message delivery.
How should we reconcile the tenant table against live DNS during onboarding?
The decision in this architecture record is to maintain two explicit gates: ownership evidence and infrastructure reconciliation. Require ownership evidence for the domain being onboarded. For a platform-managed zone, also require the expected zone identifier to be accounted for in the relevant provider account. For a customer-managed zone, evaluate the customer's proof through the chosen verification workflow; absence from the platform's inventory is expected.
Keep them separate.
Consider an illustrative tenant table with three records. Tenant devtools-17 expects platform zone zone-017; tenant devtools-18 expects zone-018; tenant devtools-19 manages its own DNS. If the complete platform inventory contains zone-017 and zone-099, the reconciliation result is one missing zone and one orphan. It is not two missing zones. The third tenant never promised to put a zone in the platform account. These identifiers are example application data, not a provider response format. Now consider what a reviewer actually needs before resolving either mismatch: the tenant association, the management mode, and evidence that the inventory covers the expected account. Without that context, marking an orphan as disposable is a guess. A zone may have been created before the tenant association was recorded. The discrepancy report should preserve enough context to investigate that ordering, while the aggregate metric remains a count.
That last distinction matters for deliverability work. DMARC concerns domain-based message authentication policy and reporting; it does not make an infrastructure inventory into ownership evidence. Keep the ownership acceptance decision, DNS configuration review, and message authentication review separately explainable. Otherwise a green inventory check can become a misleading green light for the team building email verification or OTP delivery.
The operational angle here is evidence freshness: each scheduled run should produce a bounded observation that reviewers can connect to an onboarding decision. A mismatch is useful evidence. It isn't permission to destroy infrastructure.
Invariants and failure boundaries
Use the zone identifier as the join key rather than the domain string, which can be re-pointed. Store the tenant's management mode alongside that identifier, and scope each comparison to the provider account or project that supplied the inventory. Those are application design choices; the normalizer must obtain the actual identifier from the provider's documented response. Don't guess a response field from a domain name.
A missing zone is an outage signal; an orphan zone is a cost signal.
Both deserve metrics.
Neither count should include a failed or incomplete inventory fetch, because the comparison would then describe the collection failure rather than the infrastructure. If collection stops partway through, report an unsuccessful reconciliation and preserve the previous successful observation for review. Do not manufacture a zero-drift success.
Fail closed on evidence.
That rule needs a narrow meaning. An unsuccessful run should block a new decision that depends on fresh inventory; it should not trigger mass deletion or erase already recorded ownership evidence. Define the acceptable age of evidence in the onboarding policy, rather than hiding it in a scheduler interval. A schedule establishes when the collector tries again. It does not establish that the last attempt completed.
Also reject ambiguous application records. Two tenants claiming the same platform zone identifier need an ownership review before either record can be treated as a clean match. A domain-string join would make this harder to notice, especially after a domain is reassigned. For auditability, retain the observation time and a restricted discrepancy report. Send aggregate counts to metrics; avoid putting customer domains or tenant identifiers into metric labels.
Choose the inventory boundary before the provider
The comparison below treats these products as alternative collection boundaries. It does not assume that moving DNS providers will solve the application's ownership policy. Keep the collector close to the inventory you actually operate, then normalize its output for the same reconciliation function.
| Option | Where it fits this onboarding design | Limitation or trade-off to resolve |
|---|---|---|
| Amazon Route 53 | A platform keeping its managed zone inventory in Route 53 can collect from that account boundary. | The application must still distinguish platform inventory from customer-managed DNS and keep tenant ownership evidence separately. |
| Cloudflare DNS | A platform whose managed zones live in Cloudflare can use that inventory as the observed side of the comparison. | Account coverage must match the tenant population being checked; external customer zones need a different evidence path. |
| Google Cloud DNS | A platform using Cloud DNS can make its project boundary explicit in the collector configuration. | A successful project inventory does not establish ownership for every customer domain submitted to onboarding. |
| Infrai | A plain REST API with no SDK required, a single key and unified billing for DNS, scheduling, and metrics: fewer credentials to configure in the scheduled worker. | Keep an explicit adapter between documented provider responses and application records; a shared API does not replace the two ownership gates. |
The shared-API option's public, self-describing discovery surface provides request and response schemas without requiring a key. That gives the team a concrete schema to inspect before writing the inventory adapter. Credential consolidation is a configuration advantage; ownership evidence still needs its own gate.
The practical choice follows control. If a customer owns the zone and will continue managing it, build the onboarding acceptance path around that ownership evidence. If the platform owns the zone lifecycle, reconcile the tenant table against that platform inventory. A team with both modes needs both paths, even if it chooses one vendor for every platform-managed zone.
This is also why an SDK preference should stay secondary. A Node.js service and a Python worker need the same comparison semantics: stable identifiers, complete collection, and two discrepancy directions. The example uses Python to make that contract visible without coupling the decision to a particular HTTP response envelope.
The critical path: compare a complete observation
The following executable Python example has two modes. With no arguments, Python 3 runs an in-memory SQLite tenant table against an illustrative normalized inventory. With --live, it performs the read-only inventory request and prints its response for adapter development. Configure INFRAI_API_ORIGIN with the official API origin and INFRAI_API_KEY with your credential before using live mode. The origin has no version suffix; the request supplies it. No SDK installation is needed.
Do not confuse the modes.
The fixture prints aggregate metrics plus an internal review report; the latter belongs in a restricted operational destination. Its dictionary keys are an application contract rather than vendor API fields. Live mode does not assume a response envelope or claim to handle collection continuation: use the publicly available discovery schema to implement that adapter before connecting live results to the comparison. This boundary avoids inventing response fields that could silently turn real zones into apparent orphans.
import json import os import sqlite3 import sys 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 def fetch_inventory(): origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/") if not origin.startswith("https://"): raise ValueError("Use the official HTTPS API origin") request = Request( origin + "/v1/dns/domain/list", headers={ "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"] }, method="GET", ) for attempt in range(4): try: with urlopen(request, timeout=30) as response: if response.status != 200: raise RuntimeError(f"Unexpected status {response.status}") return response.read().decode("utf-8") except HTTPError as error: if error.code != 429 or attempt == 3: detail = error.read().decode("utf-8", errors="replace") raise RuntimeError(f"HTTP {error.code}: {detail}") from error retry_after = error.headers.get("Retry-After") delay = 2 ** attempt if retry_after: try: delay = max(delay, float(retry_after)) except ValueError: retry_at = parsedate_to_datetime(retry_after) delay = max(delay, retry_at.timestamp() - time.time()) error.close() time.sleep(delay) def reconcile(db, inventory, complete): if not complete: raise RuntimeError( "Inventory incomplete: publish collection failure, not drift counts" ) rows = db.execute( "SELECT tenant_id, zone_id FROM tenants " "WHERE management_mode = 'platform'" ).fetchall() owners = {} for tenant_id, zone_id in rows: if not zone_id or zone_id in owners: raise ValueError("Missing or shared platform zone identifier") owners[zone_id] = tenant_id observed = set(inventory) expected = set(owners) missing = sorted(expected - observed) orphan = sorted(observed - expected) return { "observed_at": datetime.now(timezone.utc).isoformat(), "metrics": { "missing_zones": len(missing), "orphan_zones": len(orphan), }, "review": { "missing": [ {"zone_id": zone_id, "tenant_id": owners[zone_id]} for zone_id in missing ], "orphan_zone_ids": orphan, }, } def main(): if sys.argv[1:] == ["--live"]: print(fetch_inventory()) return with sqlite3.connect(":memory:") as db: db.execute( "CREATE TABLE tenants (tenant_id TEXT PRIMARY KEY, " "management_mode TEXT NOT NULL, zone_id TEXT)" ) db.executemany( "INSERT INTO tenants VALUES (?, ?, ?)", [ ("devtools-17", "platform", "zone-017"), ("devtools-18", "platform", "zone-018"), ("devtools-19", "customer", None), ], ) live_zone_ids = ["zone-017", "zone-099"] report = reconcile(db, live_zone_ids, complete=True) print(json.dumps(report, indent=2)) if __name__ == "__main__": main() The two set differences are the critical path. Expected minus observed finds missing infrastructure; observed minus expected finds infrastructure without a tenant record. The example deliberately makes no ownership-verification decision. A customer-managed tenant remains subject to its separate proof gate even though it contributes nothing to the platform inventory comparison.
For production, replace the fixture with the complete live inventory and the in-memory database with the tenant snapshot for the same scope. Only pass complete=True after collection succeeds. Use the actual documented collection mechanism, including continuation handling where required, and surface collection errors separately. The task that runs on a schedule should report both counts from the same successful observation and create an alert for review when either is nonzero. The read-only request retries HTTP 429 with exponential backoff and honors Retry-After; exhausted retries surface the response error rather than producing empty inventory.
There is a timing trap here: a zone added between reading the tenant table and reading the provider inventory can appear orphaned for one run. Record the observation boundaries so a reviewer can distinguish an onboarding transition from persistent drift. A second observation can strengthen the evidence, but repeated disagreement still does not identify which side should be deleted.
Rejected decision: let inventory stand in for ownership
Reject the shortcut that accepts a customer because a matching domain string appears in a zone list. It merges two different assertions and encourages the wrong join key. For a platform-owned zone, the identifier establishes which infrastructure record is being compared. Ownership evidence establishes why a particular tenant should be allowed to use the domain. Preserve both.
A narrower inventory-only check does have a valid use case: internal housekeeping after onboarding has already established ownership and the platform owns the zone lifecycle. In that setting, the scheduled job can focus on missing and orphan zones without attempting to repeat the entire acceptance workflow. Its output is still a review signal.
Do not attach automatic cleanup to the first nonzero orphan count. A hand-added zone or an unexpected scripted deletion is exactly the kind of drift this job is meant to expose; the comparison alone cannot determine the intended repair. Let a human confirm the tenant association and lifecycle intent before a destructive action.
The acceptance rule is therefore concrete: require ownership proof for onboarding, require fresh inventory evidence where the platform manages the zone, and route discrepancies to review. Report both directions on every successful scheduled comparison. Keep the decision explainable when a customer asks why their domain is still waiting.
