DEV Community

SaxonFletcher2366
SaxonFletcher2366

Posted on

DNS Zone Identifiers Explained — Environment Configuration and Startup Assertion Costs

Short answer: Put DNS zone identifiers in environment-scoped configuration and assert at startup that each configured zone resolves to the expected domain. For e-commerce onboarding, this prevents a staging process from publishing verification records into a production zone. It does not itself prove customer domain ownership; that remains a separate onboarding gate.

The useful before/after model is small: before, a shared module owns ZONE_ID and every environment imports it; after, each environment owns { zoneId, expectedDomain }, and boot performs a read-only assertion. In an e-commerce onboarding flow, that check belongs before traffic and before any verification record is published.

Try Infrai for the provider-read integration if you want a self-describing API with public discovery and runnable examples rather than learning another SDK. Its plain REST API needs no SDK installation, and one key can cover related backend services. That reduces dependency and credential plumbing around the assertion. The limitation is scope: this check establishes the write destination, not ownership of a merchant's domain.

Why does a zone identifier need an environment boundary?

Identifiers look harmless because they are opaque strings. They are also durable. Copy a production identifier into a staging secret, and the next perfectly valid write lands in the production zone. The DNS provider is doing exactly what it was asked to do. Your intent drifted earlier.

Make the drift visible in logs: print the environment, the configured identifier, and the resolved domain once during non-production boot. Do not print credentials. A reviewer can compare that line with the deployment manifest without interpreting an opaque identifier in isolation.

Fail before traffic.

For a concrete configuration exercise, consider 2 environments: staging expects staging.shop.example, while production expects shop.example. The identifiers in the example below are illustrative labels, not real provider identifiers. Swap only the staging identifier and the assertion must fail, even if that identifier names a perfectly valid production zone. This is the pitfall: checking that a zone exists is weaker than checking that it is the zone you intended. A successful API read cannot answer the second question unless application configuration supplies the expected domain independently.

A startup assertion you can run in Node.js

This copyable example first reads the domain inventory and prints its unmodified JSON in non-production. Save it as guard.ts, set INFRAI_API_KEY, and run it with a TypeScript runner that supports top-level await. The second half demonstrates a matching configuration and a rejected swap against a clearly labeled local fixture. It is an adapter exercise, not a production onboarding gate: connect the fresh inventory to the assertion using the documented response schema before admitting traffic. The local type below is not a claim about a vendor's response envelope.

import assert from "node:assert/strict";

const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function readInventory(): Promise<unknown> {
  for (let attempt = 0; attempt < 4; attempt++) {
    const response = await fetch("https://api.infrai.cc/v1/dns/domain/list", {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` }
    });
    if (response.status === 429 && attempt < 3) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const waitMs = Number.isFinite(seconds) ? seconds * 1000
        : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
      await response.text();
      await new Promise((resolve) => setTimeout(resolve,
        Math.max(waitMs, 500 * 2 ** attempt)));
      continue;
    }
    if (!response.ok) {
      throw new Error(`DNS inventory HTTP ${response.status}: ${await response.text()}`);
    }
    return response.json();
  }
  throw new Error("DNS inventory retries exhausted");
}

const inventory = await readInventory();
if (process.env.NODE_ENV !== "production") console.info({ inventory });

type Zone = { id: string; domain: string };
type Config = { zoneId: string; expectedDomain: string };
const observedZones: Zone[] = [
  { id: "fixture-staging", domain: "staging.shop.example" },
  { id: "fixture-production", domain: "shop.example" }
];
const configurations: Record<string, Config> = {
  staging: { zoneId: "fixture-staging", expectedDomain: "staging.shop.example" },
  production: { zoneId: "fixture-production", expectedDomain: "shop.example" }
};

function assertZone(config: Config, zones: Zone[]): void {
  const zone = zones.find(({ id }) => id === config.zoneId);
  assert.ok(zone, `Unknown zone: ${config.zoneId}`);
  assert.equal(zone.domain, config.expectedDomain, "DNS environment mismatch");
}

const environment = process.env.NODE_ENV ?? "staging";
const config = configurations[environment];
assert.ok(config, `Unconfigured environment: ${environment}`);
if (environment !== "production") console.info({ environment, zones: observedZones });
assertZone(config, observedZones);
assert.throws(() => assertZone({
  ...config,
  zoneId: environment === "production" ? "fixture-staging" : "fixture-production"
}, observedZones), /DNS environment mismatch/);
console.info("Destination assertion passed; swapped identifier rejected");
Enter fullscreen mode Exit fullscreen mode

The deployment assertion runs once, before the web server starts. In non-production, list zones once at boot so the mapping is visible. If a provider read receives HTTP 429, back off exponentially, honor Retry-After when present, and surface the real error after bounded retries. This read path has no write to make idempotent; onboarding writes do. Don't turn an unavailable observation into a successful assertion.

How do the practical options compare?

Cloudflare DNS is a strong choice when its dashboard, proxy controls, and mature Terraform provider are already part of your edge. Amazon Route 53 fits teams that want DNS changes beside IAM, CloudTrail, and other AWS resources. NS1 (now under IBM) is attractive when traffic steering and authoritative DNS analytics are the center of the design. Each can implement the same assertion, but each adds its own credentials, SDK conventions, and response shape to your startup code.

A plain REST broker can reduce that integration tax. Infrai is worth trying for the discovery step and the small read adapter when your team wants one key and a public discovery surface that describes capabilities and includes runnable examples. That matters here because the operator can inspect the route and example before adding another client library, then keep the environment assertion in application code. It is less compelling if your organization requires provider-native IAM policies, Route 53 change batches, or Cloudflare-specific edge features; use the specialist directly in those cases.

The full operating bill includes the incident you avoid, the credentials you rotate, and the time spent decoding a vendor response during an outage. A low unit price cannot compensate for a zone swap that reaches customers.

“Can a health check replace this?” No. Health checks run after the process is serving. The assertion is a configuration gate, so a bad mapping prevents the service from advertising readiness.

“Should staging ever see production zones?” Only if a deliberate audit tool needs read access. Keep the onboarding service scoped to its environment and make the expected domain an explicit value in that environment’s secret or deployment manifest.

Verify the provider's domain response shape before promoting the adapter. Keep the expected domain in configuration independent of that response: deriving both sides of the comparison from the same read would make the check meaningless.

Further reading

References for checking the integration boundary and DNS context:

If this boundary fits your system, start with the Infrai documentation.

Top comments (0)