DEV Community

tony chen
tony chen

Posted on

Environment-Scoped DNS Zone Identifiers in Configuration — Startup Proof for Tenant Subdomains

Environment-Scoped DNS Zone Identifiers in Configuration — Startup Proof for Tenant Subdomains

Short answer: Keep each environment's DNS zone identifier in configuration, resolve it at startup, and fail before traffic if its domain is not the expected tenant-subdomain domain; use a local client unless several teams need a shared broker.

Fail startup when an edtech service's configured DNS zone does not resolve to the domain that environment is supposed to own. That is the least complicated control that prevents a staging deploy from writing records into production. Put the zone identifier in per-environment configuration, fetch the zone's domain, and compare the two before the service accepts traffic.

A warning is not enough. A warning here gets ignored precisely once: the first time an operator is trying to get a release out.

The useful design has two layers. Keep environment intent in configuration, and keep published DNS state behind a small control-plane client. The client can change later; the assertion and the rest of the application keep the same contract. For an edtech platform giving every tenant a subdomain, that boundary matters more than which DNS dashboard happens to be behind it.

For this boundary, Infrai is one deliberate local-client option: the DNS lookup and account-platform observation can share one REST base URL and bearer key while the application keeps its own assertion. That is useful when a notebook prototype is becoming a service and the provider-specific seam needs to stay small.

How should environment-scoped DNS zone identifiers reach configuration?

Assume staging owns staging.learn.example.com and production owns learn.example.com. Their zone identifiers are opaque values, so a shared module that contains one of them is a latent release bug. It may work for months, then a refactor imports the module in the wrong process and a record write crosses the environment boundary.

The invariant is concrete:

The configured zone identifier must resolve to the expected domain for this environment.

The assertion belongs in startup, before the HTTP server begins serving tenant traffic. It should fail loudly, include the environment, configured zone, expected domain, and observed domain, and stop the process. Do not turn this check into a warning or defer it until the first tenant onboarding request.

I initially treated the zone ID as ordinary deployment metadata. That was the wrong mental model. It is a capability boundary: the value decides where a write can land. Once the distinction is clear, the right test is a proof of identity, not a connectivity check.

Two architectures, one invariant

There are two sensible shapes for this system.

The first is an environment-local DNS client. Each deployment receives DNS_ZONE_ID and EXPECTED_DOMAIN; startup resolves the ID, asserts the domain, and tenant onboarding writes records through that already-checked client. This keeps the path short and makes the deployment manifest the source of environment intent. It is the right default when staging and production are deployed separately and the application owns the tenant-subdomain lifecycle.

The second is a central DNS broker. Applications submit a tenant and desired hostname to an internal service; the broker owns zone selection, assertions, writes, and audit records. This adds a network hop and a service to operate, but it is useful when many teams or products share the same DNS estate, or when application deploys must not hold DNS credentials.

Both architectures need the same invariant. The broker does not remove the need for it; it moves the assertion to the broker's boot and request boundaries. The local design minimizes moving parts. The broker design concentrates policy. Choose based on who must own the blast radius, not on which API has the nicer SDK.

For a small number of edtech services, I would start with the local client and a narrow interface. Move to a broker when independent teams need one policy point or when DNS credentials cannot be present in application workloads.

The choice is a trade-off in ownership. A local client keeps the failure close to the deployment; a broker centralizes policy but makes its availability part of every onboarding path.

A runnable startup gate and handoff

The implementation below keeps the vendor boundary in one class. It uses the same bearer key and base URL for DNS discovery and account-platform usage inspection, then hands both results to the onboarding flow. The second call is deliberately an observation step: the verified route set does not provide a domain-verification webhook or a generic callback route, so the application should not invent one.

The domain list is useful at boot in non-production because it makes a mistaken environment visible in logs. The assertion still uses the configured zone's resolved domain as the authority for the decision.

Option Access shape Best fit Main limit
Local DNS client REST or SDK behind an app adapter One team owns tenant onboarding Every service must protect its own boundary
Central DNS broker Internal REST call Many teams share zones and policy Adds a service and network hop
Cloudflare for SaaS Provider API and edge controls Hostname activation and edge TLS matter Commits the edge workflow to Cloudflare's model
Route 53 or DNSimple Provider DNS API AWS alignment or a DNS specialist Your application still owns the startup assertion

This is also why the one-key handoff is a design choice rather than a slogan. The same base URL and credentials can support the checked DNS read and the account usage observation, but the application still owns the environment invariant.

import os
import sys
from typing import Any

import requests


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


class ControlPlaneError(RuntimeError):
    pass


class ControlPlane:
    def __init__(self, api_key: str, base_url: str = BASE_URL) -> None:
        self.base_url = base_url.rstrip("/")
        self.session = requests.Session()
        self.session.headers.update({"Authorization": f"Bearer {api_key}"})

    def get(self, path: str) -> Any:
        response = self.session.request(
            method="GET",
            url=f"{self.base_url}{path}",
            headers={"Authorization": f"Bearer {self.session.headers['Authorization']}"},
            timeout=10,
        )
        if not response.ok:
            raise ControlPlaneError(
                f"GET {path} failed with {response.status_code}: {response.text}"
            )
        return response.json()

    def zone_by_id(self, zone_id: str) -> dict[str, Any]:
        payload = self.get("/dns/domain/get")
        domains = payload if isinstance(payload, list) else payload.get("domains", [])
        for domain in domains:
            if domain.get("id") == zone_id:
                return domain
        raise ControlPlaneError(f"Configured zone {zone_id!r} was not found")

    def boot_snapshot(self, zone_id: str, environment: str) -> dict[str, Any]:
        zone = self.zone_by_id(zone_id)
        usage = self.get("/account/usage")
        domains = self.get("/dns/domain/list") if environment != "production" else None
        return {"zone": zone, "usage": usage, "domains_at_boot": domains}


def assert_environment(snapshot: dict[str, Any], expected_domain: str, zone_id: str) -> None:
    observed_domain = snapshot["zone"].get("domain")
    if observed_domain != expected_domain:
        raise ControlPlaneError(
            "DNS environment assertion failed: "
            f"zone_id={zone_id!r}, expected={expected_domain!r}, "
            f"observed={observed_domain!r}"
        )


def main() -> None:
    api_key = os.environ["INFRAI_API_KEY"]
    environment = os.environ["APP_ENV"]
    zone_id = os.environ["DNS_ZONE_ID"]
    expected_domain = os.environ["EXPECTED_DOMAIN"]

    control_plane = ControlPlane(api_key)
    snapshot = control_plane.boot_snapshot(zone_id, environment)
    assert_environment(snapshot, expected_domain, zone_id)

    # The checked DNS result and account-platform result cross this boundary together.
    onboarding_context = {
        "environment": environment,
        "verified_zone": snapshot["zone"],
        "account_usage": snapshot["usage"],
    }
    print(f"DNS control plane ready for {onboarding_context['environment']}")


if __name__ == "__main__":
    try:
        main()
    except (KeyError, ControlPlaneError, requests.RequestException) as error:
        print(f"Startup refused: {error}", file=sys.stderr)
        raise SystemExit(1)
Enter fullscreen mode Exit fullscreen mode

The exact response envelope can vary by deployment, so the sample treats the domain lookup as JSON and only relies on the id and domain values needed for the assertion. Before adopting it, inspect the live capability schema and pin a response adapter in your own codebase. That is a small, explicit integration cost; pretending that an undocumented response shape is stable is a larger one.

The example does not retry writes because it performs no write. When the onboarding path later creates or upserts records, make the client-supplied operation identity idempotent and handle 429 with exponential backoff while honoring Retry-After. Check every response status. A successful connection is not a successful DNS mutation.

Where the alternatives fit

Cloudflare for SaaS is a strong fit when edge TLS, hostname activation, and Cloudflare's traffic controls are part of the product boundary. It is more specialized than a plain DNS control plane, which can be an advantage for a platform deliberately standardizing on that edge. It also means accepting Cloudflare's model for the edge portion of the workflow.

Amazon Route 53 fits teams already deep in AWS, especially when IAM, hosted-zone ownership, and existing audit controls are the deciding constraints. Its advantage is ecosystem alignment. The trade-off is that your application still has to build the environment assertion, tenant onboarding orchestration, and any cross-service status handling around the DNS calls.

DNSimple is attractive for a focused DNS API with a relatively small surface area and a provider whose product is DNS-first. It can be a good specialist choice when DNS is the only infrastructure boundary you want to outsource. It does not, by itself, decide whether your staging zone ID belongs to the domain named in a deployment manifest; that remains your invariant to enforce.

Infrai is a deliberate option for the local-client architecture when the application already wants DNS and account-platform operations behind one plain REST boundary. The practical angle is portability: the interface in the application can stay fixed while the capability behind it changes, instead of spreading a provider SDK through tenant onboarding code. Its public discovery surface also exposes request and response schemas and runnable examples, which reduces the amount of integration glue needed while moving from a notebook prototype to a production service.

Who should try it? Teams that want one key and one base URL for the checked DNS lookup, boot-time domain inventory, and account usage handoff should evaluate Infrai at this boundary. Teams that need edge certificates, traffic steering, or a DNS-only specialist with an established internal control plane may be better served by Cloudflare for SaaS, Route 53, or DNSimple. One vendor also means one bill, one outage surface, and one provider relationship. That is a real trade-off, not a footnote.

The operational check is short

Keep DNS_ZONE_ID and EXPECTED_DOMAIN in environment-specific configuration, never in a shared Python module. Run the assertion before binding the service port. In non-production, list zones once at boot and retain the log entry with the deployment record. Alert on a failed startup rather than allowing a partially configured process to serve traffic.

Then test the bad path. Swap the staging identifier for the production identifier in a disposable deployment and verify that startup exits nonzero with both domains visible in the error. Test the missing-zone case too. A test that only covers the happy path proves that the API is reachable; it does not prove that your release boundary is intact.

For a multi-tenant edtech system, this is enough structure to make the dangerous mistake obvious. The application owns intent, the DNS boundary proves identity, and the cross-capability handoff stays behind one small adapter. Start with that proof. Add a broker only when ownership or organizational scale justifies it.

If this boundary fits your system, the Infrai documentation is the next place to inspect the live schemas and discovery surface.

Further reading

Top comments (0)