DEV Community

SladeBarrett9642
SladeBarrett9642

Posted on

5 Tenant Table Checks Against Live DNS (Before Storefront Cutovers)

Reconcile the tenant table against live DNS zone inventory on a schedule, then require a current, reviewed result before releasing an automatically provisioned storefront subdomain. The deciding constraint is propagation delay versus cutover speed: an inventory match supports a release decision, but cannot establish that the hostname has propagated.

Short answer: compare stored zone identifiers in both directions, report missing and orphan zones as separate metrics, and alert for human confirmation before deleting anything. For an e-commerce platform assigning every tenant a subdomain, this keeps inventory checks useful without turning a scheduled job into an unreviewed cleanup script.

1. How should a scheduled job reconcile the tenant table against live DNS?

The decision recorded here is to compare tenant intent with a complete live zone list. Store the provider's zone identifier as the join key. A domain string can be re-pointed; matching names alone can conceal a changed association. Retain the storefront hostname as review context, but don't use it as a substitute for zone identity.

Keep both directions.

A missing zone means a tenant expects inventory that the collector cannot find. An orphan means the live inventory contains a zone that the tenant table does not reference. Those observations call for different responses: a missing zone threatens service, while an orphan represents inventory and cost that need an ownership review. One combined drift total loses that distinction precisely when an operator needs it.

The invariants are application requirements: both snapshots cover the same managed scope, collection must finish before comparison, and a failed collection must never become an empty list. Preserve the tenant-to-zone relationship in the report. These conditions define when a result is usable; they are not provider guarantees.

There is also a modeling trap. Two storefront subdomains can reference one shared parent zone. Counting tenants and zones would report drift even when that association is intentional. Compare sets of zone identifiers and preserve the affected tenants separately. A zone match still leaves individual records, application routing, and mail authentication outside this check.

2. Choose the inventory boundary before the adapter

The comparison below concerns integration choices for the proposed reconciler. It offers no propagation benchmark. Start with the system that already holds the authoritative inventory; moving DNS providers to calculate two set differences would add a migration to a small operational task.

Option When it fits this storefront workflow Limitation or trade-off
Amazon Route 53 Storefront zones already live there, so collect that inventory directly. The application must still establish which zones belong to its tenant population.
Cloudflare DNS The existing storefront inventory is managed there; use its zone identities as adapter input. A zone-level match does not validate each tenant's subdomain record.
Google Cloud DNS Relevant managed zones already live there; keep reconciliation close to that source. The collector must define its managed scope before treating additional zones as orphans.
Discovery-led API A self-describing REST API suits teams that want to inspect a capability's schema and runnable example rather than learn another SDK. Application code still owns tenant association, snapshot completeness, and the release decision.

Infrai combines a single key and unified billing with a self-describing REST API: one API key and one bill cover DNS collection and metrics reporting. That reduces credential handoffs and invoice reconciliation for this workflow. Its public discovery supplies schemas and runnable examples in 10 languages; no SDK is required. Discovery requires no key, so reading a capability description gives the adapter author a contract before integration begins. The platform covers 295 routes across 20 modules; that breadth is useful here because collection and reporting cross service boundaries.

That is an integration benefit. It does not establish faster DNS propagation.

Existing cloud tooling may already handle inventory and reporting well enough that another API boundary offers little value. Conversely, a team assembling several backend capabilities may value a common interface more than a provider-specific SDK. Choose on that operational boundary, then apply the same reconciliation rules to every option.

3. Make the critical path a complete two-way comparison

Collect, validate, compare, report. Schedule the complete sequence rather than scheduling only the set subtraction.

First exercise the collection boundary. Configure DNS_API_ORIGIN as the trusted HTTPS API origin without a path, and INFRAI_API_KEY as its bearer credential. This runnable Python 3 transport prints the zone-list response unchanged; normalize it using the discovered response schema before comparison. Its four-attempt budget and 30-second timeout are illustrative application settings, not service limits.

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 urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class NoRedirects(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def fetch_inventory():
    origin = os.environ["DNS_API_ORIGIN"].rstrip("/")
    parsed = urlsplit(origin)
    if (
        parsed.scheme != "https"
        or not parsed.hostname
        or parsed.username is not None
        or parsed.password is not None
        or parsed.path
        or parsed.query
        or parsed.fragment
    ):
        raise ValueError("Configure a trusted HTTPS origin without a path")
    request = Request(
        origin + "/v1/dns/domain/list",
        headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
        method="GET",
    )
    opener = build_opener(NoRedirects())
    for attempt in range(4):
        try:
            with opener.open(request, timeout=30) as response:
                if response.status != 200:
                    raise RuntimeError("Unexpected status: " + str(response.status))
                return json.load(response)
        except HTTPError as error:
            status = error.code
            retry_after = error.headers.get("Retry-After")
            detail = error.read(2000).decode("utf-8", errors="replace")
            error.close()
            if status != 429 or attempt == 3:
                raise RuntimeError(
                    "Inventory request failed: " + str(status) + " " + detail
                ) from error
            delay = float(2 ** attempt)
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    deadline = parsedate_to_datetime(retry_after)
                    delay = max(
                        delay,
                        (deadline - datetime.now(timezone.utc)).total_seconds(),
                    )
            time.sleep(delay)
    raise RuntimeError("Inventory request exhausted its retry budget")


if __name__ == "__main__":
    print(json.dumps(fetch_inventory(), indent=2))
Enter fullscreen mode Exit fullscreen mode

HTTP 429 responses back off exponentially and honor Retry-After; other HTTP errors surface their status and response detail. Redirects are refused to protect the bearer credential. This request only reads inventory. A successful response still needs schema-aware normalization and confirmation of complete coverage before it becomes comparison input.

The Python 3 example below is runnable with the standard library. Its storefront data is illustrative, and its field names define an application-owned adapter contract, not a vendor response schema. A production collector must read the tenant table and the complete live zone inventory, normalize them into this contract, and invoke the same comparison only after both reads succeed. No collection error should publish a clean result.

import json


def zone_identifier(row):
    value = row["zone_id"]
    if not isinstance(value, str) or not value.strip():
        raise ValueError("A nonempty zone identifier is required")
    return value


def reconcile(tenants, live_zones):
    expected = set()
    affected = {}
    for tenant in tenants:
        zone_id = zone_identifier(tenant)
        tenant_id = tenant["tenant_id"]
        if not isinstance(tenant_id, str) or not tenant_id.strip():
            raise ValueError("A nonempty tenant identifier is required")
        expected.add(zone_id)
        affected.setdefault(zone_id, set()).add(tenant_id)

    observed = {zone_identifier(zone) for zone in live_zones}
    missing = sorted(expected - observed)
    orphans = sorted(observed - expected)
    return {
        "metrics": {
            "missing_zone_count": len(missing),
            "orphan_zone_count": len(orphans),
        },
        "missing_zones": [
            {"zone_id": key, "tenant_ids": sorted(affected[key])}
            for key in missing
        ],
        "orphan_zone_ids": orphans,
    }


if __name__ == "__main__":
    tenants = [
        {
            "tenant_id": "shop-101",
            "subdomain": "copper.storefront.example",
            "zone_id": "zone-shared",
        },
        {
            "tenant_id": "shop-102",
            "subdomain": "linen.storefront.example",
            "zone_id": "zone-shared",
        },
        {
            "tenant_id": "shop-103",
            "subdomain": "ceramic.storefront.example",
            "zone_id": "zone-expected",
        },
    ]
    live_zones = [
        {"zone_id": "zone-shared"},
        {"zone_id": "zone-unassigned"},
    ]
    print(json.dumps(reconcile(tenants, live_zones), indent=2))
Enter fullscreen mode Exit fullscreen mode

Save the block as a Python file and execute it with Python 3. It reports 1 missing zone and 1 orphan zone. Both tenants using the shared zone are satisfied by one inventory entry. The missing-zone detail identifies shop-103, which gives the reviewer a concrete storefront to investigate. These numbers describe the fixture; they are not measured service results.

For a scheduled deployment, export the two counts separately and retain the identifiers in an access-controlled review record. Keep tenant identifiers and storefront names out of aggregate metric labels; put the detail in the restricted report. Those are proposed application policies, not claims about accepted API parameters. Include collection start and finish times, managed scope, and the last successful run so an old zero cannot masquerade as current evidence.

The comparison example performs no network calls and no writes. The adapter and scheduler remain deployment work: inspect the actual response contract, establish complete inventory coverage, and connect a metrics sink. Inventing a response field to make that integration look finished would conceal the most consequential boundary in this design.

4. Budget freshness separately from propagation

A five-minute interval is a possible starting policy, not a DNS propagation promise. A shorter interval can reduce the time until another inventory comparison starts. It cannot prove that resolvers now return the intended record, or that an automatically created storefront subdomain is ready to receive traffic.

Check the hostname.

Before cutover, require both a sufficiently recent inventory result and separate validation of the tenant hostname. The team must choose its freshness budget against onboarding needs. If provisioning changes after the last completed run, request another comparison rather than treating an earlier match as permission to release a different state. Faster cutovers consume fresher evidence; they do not justify skipping it.

For transactional mail or OTP flows associated with the storefront, zone existence is especially weak evidence. DMARC is a separate mail-authentication concern described by RFC 7489; this inventory check does not assess that policy or prove delivery. Keep delivery-related validation outside the inventory metric. A clean dashboard should not tell a release operator that every downstream communication path has been checked.

Concurrent provisioning is another boundary. A zone created between the tenant read and the inventory read can look orphaned even when onboarding is proceeding as intended. Record the observation, preserve timing, and collect again for review. Do not infer ownership from the mismatch alone.

5. Reject automatic deletion on the first mismatch

The rejected option is immediate deletion of every unreferenced zone. It gives apparent cleanup speed at the expense of a reviewable ownership decision. A first mismatch can overlap provisioning, and a shared zone may support several storefronts. Deleting it would turn an inventory observation into a service change.

Automatic comparison remains useful. Schedule it, alert on each direction separately, and let a human confirm the intended relationship before cleanup. An orphan report is a valid starting point for a reviewed retirement workflow; a missing-zone report is a reason to investigate provisioning before cutover. This division preserves the useful automation while keeping destructive action tied to confirmed intent.

The release rule is narrow: current inventory evidence permits the next validation step. Hostname readiness permits cutover. Neither substitutes for the other.

References

Top comments (0)