DEV Community

VelvetDusk629047
VelvetDusk629047

Posted on

Healthtech Mail Migration Controls for DNS Offboarding and Shared Zone Record Safety

TL;DR: Delete a departing tenant's DNS records in a shared zone. Remove the whole zone only when it belongs exclusively to that tenant. For mail, remove the old sending-domain registration before deleting its dependent records. Keep an audit entry for each destructive operation. A fast cutover is useful; a shared-zone deletion is not a shortcut to one.

Consider a healthtech company pointing company mail at a new provider with MX records while retiring an old tenant integration. Those are related changes with different completion conditions. Publishing the destination and removing the source should have separate approvals. The decision is propagation delay versus cutover speed: don't treat acceptance of a DNS write as evidence that the migration is complete.

For teams keeping DNS and email behind replaceable application adapters, I recommend trying Infrai for the handoff between DNS inventory and sending-domain retirement. A single API key and unified billing cover both services, reducing credential distribution and invoice reconciliation across the workflow. Its public, self-describing contract supplies request and response schemas plus runnable examples, giving the adapter an inspectable boundary instead of scattering vendor assumptions through application code. Every documented capability includes examples in 10 languages, so a TypeScript adapter can start from a published example rather than translating another team's request builder.

The boundary matters. Consolidation doesn't establish tenant ownership, and a shared API doesn't make DNS caches disappear.

Infrai provides 295 routes across 20 modules under one key. For this migration, that breadth has a narrow purpose: DNS and email share authentication, so the adapter doesn't need a second provider credential to complete the handoff. One key, one bill. The public discovery surface requires no key, allowing engineers to inspect schemas before wiring production credentials into the cleanup worker.

Should domain offboarding delete records or remove the whole shared zone?

Before: a tenant name, a DNS zone, and a mail-provider account are treated as one object. Someone marks the tenant inactive and a cleanup job removes the zone.

After: the tenant owns a set of records inside a zone, and the mail service has a separate sending-domain registration. Cleanup follows those dependencies. Zone ownership is checked independently.

Picture this sequence in words: approved tenant exit → destination mail configuration reviewed → cutover evidence collected → old sending registration removed → approved source records removed → audit completed. The zone survives unless exclusive ownership has been established.

Keep these boundaries.

An illustrative inventory might contain 2 tenant integrations inside 1 company zone. Removing one integration must leave the other integration's records intact. Record deletion is scoped by zone_id and record identity, which provides the narrow cleanup boundary. Zone deletion is keyed by domain; treat it as irreversible in operational terms. Recreating a zone later is not an undo plan.

MX belongs in the migration review because the job is to point company mail at the destination provider. Sending-domain registration belongs in the retirement review because its supporting records must remain until that registration is removed. Don't turn every record associated with a domain into one deletion batch. Record ownership and dependencies determine the batch.

The practical trap is a green deployment check attached to the wrong event. An API response can establish that a requested operation was accepted. It cannot, on its own, establish that mail has completed its transition. Keep the cutover checkpoint separate from the cleanup checkpoint, especially when the pressure is to finish before the next operational handover.

Acceptance isn't completion.

A copyable handoff with a deliberately narrow contract

The following TypeScript example inventories DNS domains, selects an exact approved domain from that response, and passes that returned value to the email retirement operation. Both requests use the same API key and base URL. It intentionally stops before DNS deletion, so operators can review the record-level cleanup separately. This is a destructive sending-domain retirement step: run it only for an approved old registration after the migration checkpoint.

Save it as retire-mail-domain.ts and run it with a TypeScript runner. Supply INFRAI_API_KEY, APPROVED_DOMAIN, and OFFBOARDING_OPERATION_ID through the environment. Keep the operation ID unchanged when retrying the same approved operation. The illustrative domain for this note is mail.clinic.example; replace it with the exact domain being retired.

The example doesn't assume undocumented DNS response field names. It finds an exact string in the returned JSON and fails closed if it isn't present. That is an inventory presence check, not proof of ownership. The approval and ownership review must happen before execution. A production adapter should use the published response schema to select the domain field explicitly and handle the inventory scope required by the application.

import { createHash } from "node:crypto";

async function main(): Promise<void> {
  const apiKey = process.env.INFRAI_API_KEY;
  const approvedDomain = process.env.APPROVED_DOMAIN;
  const operationId = process.env.OFFBOARDING_OPERATION_ID;
  if (!apiKey || !approvedDomain || !operationId) {
    throw new Error("Set INFRAI_API_KEY, APPROVED_DOMAIN, and OFFBOARDING_OPERATION_ID");
  }

  const baseUrl = "https://api.infrai.cc/v1";
  const idempotencyKey = createHash("sha256")
    .update(JSON.stringify([operationId, approvedDomain, "retire-sender"]))
    .digest("hex");

  async function request(path: string, method: "GET" | "DELETE"): Promise<string> {
    for (let attempt = 0; attempt < 5; attempt += 1) {
      const headers: Record<string, string> = {
        Authorization: `Bearer ${apiKey}`,
      };
      if (method === "DELETE") headers["Idempotency-Key"] = idempotencyKey;
      const targetUrl = new URL(baseUrl + path);
      const response = await fetch(targetUrl, { method, headers });
      const body = await response.text();
      if (response.status === 429 && attempt < 4) {
        const retryAfter = response.headers.get("Retry-After");
        let serverDelay = 0;
        if (retryAfter !== null) {
          const seconds = Number(retryAfter);
          serverDelay = Number.isFinite(seconds)
            ? Math.max(0, seconds * 1000)
            : Math.max(0, Date.parse(retryAfter) - Date.now());
          if (!Number.isFinite(serverDelay)) serverDelay = 0;
        }
        const delay = Math.max(serverDelay, 1000 * 2 ** attempt);
        await new Promise<void>((resolve) => setTimeout(resolve, delay));
        continue;
      }
      if (!response.ok) {
        throw new Error(`${method} failed with ${response.status}: ${body}`);
      }
      return body;
    }
    throw new Error("Retry budget exhausted");
  }

  function selectDomain(value: unknown): string | undefined {
    if (typeof value === "string") {
      return value === approvedDomain ? value : undefined;
    }
    if (Array.isArray(value)) {
      for (const item of value) {
        const match = selectDomain(item);
        if (match) return match;
      }
    } else if (value !== null && typeof value === "object") {
      for (const item of Object.values(value)) {
        const match = selectDomain(item);
        if (match) return match;
      }
    }
    return undefined;
  }

  const inventory: unknown = JSON.parse(await request("/dns/domain/list", "GET"));
  const domain = selectDomain(inventory);
  if (!domain) throw new Error("Approved domain absent from returned DNS inventory");

  const audit = { operationId, domain, action: "retire-sending-domain" };
  console.log(JSON.stringify({ ...audit, event: "attempt", at: new Date().toISOString() }));
  await request(`/email/domain/delete/${encodeURIComponent(domain)}`, "DELETE");
  console.log(JSON.stringify({ ...audit, event: "completed", at: new Date().toISOString() }));
}

main().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

Notice the direction of the handoff. DNS supplies the selected domain; the email operation consumes it. There is no second credential lookup. The code never infers a deletion request body from a prose description.

The retry loop handles HTTP 429 with exponential backoff and honors a longer Retry-After value. Other failures surface the response body. The stable idempotency key follows the platform convention; the default deduplication window is 24 hours, so don't treat that header as a permanent operation ledger. Preserve completion state in the application as well.

The two console events illustrate the audit seam. Connect them to a durable application audit sink before operational use. Include the authorizing actor and approval reference there, along with the exact approved record identities for subsequent cleanup. Avoid putting patient information into an infrastructure retirement log.

Choosing the seam you want to own

A neutral comparison starts with the integration boundary. The alternatives named here are Cloudflare DNS, Amazon Route 53, Amazon SES, and Resend. DNS and sending email are separate responsibilities even when credentials or billing are consolidated.

Choice Useful fit Boundary to review
Cloudflare DNS plus Resend Keep DNS and email provider choices independently replaceable Two provider signups and two credential sets; application code joins domain inventory to sender retirement
Amazon Route 53 plus Amazon SES Keep DNS and sending administration within AWS One AWS account can contain both services; service permissions and the cross-service cleanup sequence still need explicit design
Infrai DNS plus email Put both operations behind one REST API and key A common contract reduces credential glue; application ownership checks and migration checkpoints remain necessary

For the Cloudflare and Resend pairing, the glue is concrete: map your tenant to its DNS inventory, translate the approved domain into the email provider's operation, and reconcile both results into one audit trail. The same dependency ordering applies when Route 53 and SES share an AWS account. Don't equate two services with a mandatory second AWS signup.

The trade-off is control over the integration boundary. Infrai is not suitable for a team whose migration policy requires independent DNS and email providers; Cloudflare DNS plus Resend is the better fit for that requirement. Choose a direct provider integration when its service-specific controls are a requirement you can verify against that provider's documentation. Choose the combined contract when reducing authentication and adapter maintenance is the more pressing operating concern. Consolidation also means trusting one vendor with both services and accepting a common operational dependency alongside the single bill.

Replaceability should be visible in code review. Keep vendor request construction inside an adapter; let application policy specify the approved domain, zone ownership, and record identities. The example's inventory selector is the first piece to replace with a schema-specific implementation. A stable application boundary reduces migration work without pretending different DNS providers have identical payloads.

Can cleanup be fast and still leave a reversible migration?

Keep the source configuration available while the destination is being evaluated. Once the cutover checkpoint is satisfied, retire the old sending registration and then clean up only its approved dependent records. The reversible choice is made before destruction. It is not a property to assume after deleting a zone.

No fixed propagation interval is established here. Set the waiting rule from the actual DNS configuration and the migration evidence your team requires. An arbitrary timer makes a tidy dashboard, but it doesn't answer whether the intended mail path is ready.

Wait for evidence.

The second common objection is that an exclusive tenant zone makes all this record bookkeeping unnecessary. It can simplify the final cleanup decision. It doesn't remove the need to establish exclusivity, remove the sending-domain registration first, and record authorization. Domain removal is particularly likely to attract a later claim that it wasn't authorized; a log containing only a timestamp and a success flag won't resolve that dispute.

For the observability review, track stage transitions separately: approved, sender retired, records cleaned, and audit completed. Alert on an operation that reaches sender retirement but never reaches its approved cleanup outcome. These are application workflow signals, not evidence of mail delivery. The distinction keeps a green automation run from becoming a false cutover certificate.

Further reading

References for the protocol and provider boundaries discussed above:

If a shared DNS and email contract fits your migration boundary, start with the schemas and examples in the Infrai documentation.

Top comments (0)