DEV Community

FerdinandBlake3517
FerdinandBlake3517

Posted on

Company Mail Drift and Coarse Regional Routing with Stable Hostnames Explained

Keep regional names stable, reconcile company mail records against reviewed configuration, and shift application traffic with a feature flag. An edtech backend needs those decisions separated: moving an application between regions should not silently change where the company's mail is received.

TL;DR: Publish one stable hostname per region and keep the region-to-hostname mapping in configuration. Use a flag to select among those names. For company mail, compare published MX records with the mail provider's intended records before accepting a DNS change as complete. DNS changes can take hours to fully land; they are a poor control for a traffic decision that needs to move immediately.

How should coarse regional routing use stable hostnames and a feature flag?

The decision is to treat DNS as published configuration and the traffic flag as an application selection input. The invariant is simple: a region keeps its hostname when traffic moves elsewhere. A second invariant protects the edtech company's mail: the expected MX set belongs to a separately reviewed mail configuration. Neither a new application region nor a flag change authorizes an MX edit.

Keep them separate.

Consider an enrollment service with two configured regions and a company mail domain used by staff. The regional names identify application destinations. The MX records describe the intended mail destination. Both can drift from configuration, but they need different comparisons. An application flag can choose a regional hostname; it does not replace the mail provider's MX instructions. The worked example below uses reserved example domains and illustrative preferences, so its mail values must be replaced with the actual provider's requirements before any real deployment.

The failure boundary matters for a delivery-conscious backend. A correct record comparison establishes agreement with the observed DNS data. It doesn't establish inbox placement, successful OTP delivery, or compliance with an organization's data policies. DMARC concerns message authentication and policy, a different question from whether the published MX set matches intent. Keep those checks distinct so a green DNS report does not become a blanket claim about deliverability.

Make drift the acceptance criterion

A successful configuration write is an intermediate result. Acceptance means the published records agree with the reviewed intent. For MX, compare the complete intended set, including preferences and exchange names; a leftover destination deserves attention even when every new destination is present. Comparing only record counts would miss a substitution. Comparing only exchange names would miss a preference change.

Order should not matter.

An extra destination still counts as drift.

The example's comparison normalizes case and a trailing dot in DNS names, preserves MX preferences, and rejects duplicate records in its local input. Those are explicit choices for this checker, not a provider response schema. It uses a set comparison because the question is membership, then prints missing and unexpected entries separately so a reviewer can see the proposed correction. An extra exchange isn't automatically safe just because it appeared during a migration. Decide whether it belongs in the approved configuration.

Observation has a boundary too: one captured view is evidence of that view. It cannot prove that every cached answer has converged. Keep the intended record set available while checking publication, and avoid promising a universal propagation deadline. The practical concern is the interval during which intent and observed answers disagree.

For regional application routing, reject an unknown flag value instead of guessing a destination. That makes a misspelled region visible. A compliance-aware system also needs an approved destination set; a flag is a selection mechanism, not permission to move student data to an arbitrary location. This note does not claim that hostname selection itself enforces residency.

Compare the control boundary before choosing a service

The useful comparison is where the record authority, reviewed intent, and runtime traffic choice will live. These are selection criteria rather than a benchmark; no latency or delivery measurements are implied.

Option Fit for this decision Boundary to evaluate
Amazon Route 53 A DNS candidate when the company is evaluating an AWS-centered operating model. Review how the chosen record workflow exposes published MX values; keep application flag selection explicit.
Cloudflare DNS A DNS candidate when Cloudflare is already part of the domain's operating context. Confirm the actual authoritative zone and compare its mail records with provider instructions. Domain adjacency alone is not proof of agreement.
Google Cloud DNS A DNS candidate when the team is evaluating Google Cloud for its DNS operations. Decide how reviewed configuration and observed records will be compared across the deployment boundary.
Infrai Its 295 routes across 20 modules share one key and a consistent REST surface, which fits a backend adding capabilities alongside DNS. Its public discovery surface supplies request and response schemas, useful for checking the record contract before building the reconciliation adapter. A shared API still needs an explicit separation between mail intent and application routing intent.

Choose the DNS service that fits the team's authoritative-zone ownership and change-review process. A broader backend contract is useful when it removes another integration boundary from that workflow; an established DNS workflow may be the better fit when it already gives reviewers a clear record diff. None of these choices removes the need to compare intent with publication.

The table deliberately leaves provider-specific request bodies out of the implementation. The critical path here can be exercised without credentials: normalize record observations, detect drift, and select a known regional destination. An adapter can later translate a chosen provider's documented response into this local representation.

Preserve the evidence.

Exercise the decision with a small Python check

This runnable standard-library example defines its own input format. The values are demonstration data, not production MX guidance. The observed snapshot intentionally retains an old exchange so the mismatch is visible. In deployment, supply observations from the authoritative DNS workflow instead of treating a hardcoded list as a live lookup.

The code also checks the regional hostname mapping independently of the active region flag. This is the distinction that prevents a successful traffic selection from masking DNS drift. It exits unsuccessfully while drift exists, even though selecting a configured region is valid.

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 NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def read_published_records():
    base = os.environ["INFRAI_API_BASE_URL"].rstrip("/")
    parsed = urlsplit(base)
    if (parsed.scheme != "https"
            or parsed.netloc != ".".join(("api", "infrai", "cc"))
            or parsed.path != "/v1" or parsed.query or parsed.fragment):
        raise ValueError("Use the official v1 API base URL")
    request = Request(
        base + "/dns/record/list",
        headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
        method="GET",
    )
    opener = build_opener(NoRedirect())
    for attempt in range(5):
        try:
            with opener.open(request, timeout=30) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError("Unexpected HTTP status")
                return json.load(response)
        except HTTPError as error:
            status = error.code
            retry_after = error.headers.get("Retry-After")
            reason = error.read().decode("utf-8", errors="replace")
            error.close()
            if status != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {status}: {reason}") from error
            delay = float(2 ** attempt)
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    deadline = parsedate_to_datetime(retry_after)
                    if deadline.tzinfo is None:
                        deadline = deadline.replace(tzinfo=timezone.utc)
                    delay = max(delay, (deadline - datetime.now(timezone.utc)).total_seconds())
            time.sleep(delay)
    raise RuntimeError("Retry budget exhausted")


def dns_name(value):
    return value.rstrip(".").lower()


def mx_set(records):
    result = set()
    for record in records:
        preference = record["preference"]
        if type(preference) is not int or not 0 <= preference <= 65535:
            raise ValueError("MX preference must be an unsigned 16-bit integer")
        item = (preference, dns_name(record["exchange"]))
        if item in result:
            raise ValueError("Duplicate MX entry in checker input")
        result.add(item)
    return result


def mx_drift(expected, observed):
    intended = mx_set(expected)
    published = mx_set(observed)
    return {
        "missing": sorted(intended - published),
        "unexpected": sorted(published - intended),
    }


def hostname_drift(expected, observed):
    intended = {region: dns_name(name) for region, name in expected.items()}
    published = {region: dns_name(name) for region, name in observed.items()}
    return {
        region: {"expected": intended.get(region),
                 "observed": published.get(region)}
        for region in sorted(intended.keys() | published.keys())
        if intended.get(region) != published.get(region)
    }


def choose_hostname(region_flag, region_hosts):
    if region_flag not in region_hosts:
        raise ValueError("Traffic flag selected an unconfigured region")
    return region_hosts[region_flag]


def main():
    if os.environ.get("READ_PUBLISHED_RECORDS") == "1":
        print(json.dumps(read_published_records(), indent=2))
        return 0
    company_mail_domain = "school.example"
    expected_mx = [
        {"preference": 10, "exchange": "mx1.mail.example"},
        {"preference": 20, "exchange": "mx2.mail.example"},
    ]
    observed_mx = [
        {"preference": 20, "exchange": "MX2.MAIL.EXAMPLE."},
        {"preference": 10, "exchange": "mx1.mail.example."},
        {"preference": 30, "exchange": "old.mail.example."},
    ]
    region_hosts = {
        "east": "enrollment-east.school.example",
        "west": "enrollment-west.school.example",
    }
    observed_hosts = {
        "east": "enrollment-east.school.example.",
        "west": "enrollment-west.school.example.",
    }
    active_region_flag = "west"
    mail_diff = mx_drift(expected_mx, observed_mx)
    host_diff = hostname_drift(region_hosts, observed_hosts)
    report = {
        "company_mail_domain": company_mail_domain,
        "mx_drift": mail_diff,
        "regional_hostname_drift": host_diff,
        "selected_application_hostname": choose_hostname(
            active_region_flag, region_hosts
        ),
    }
    print(json.dumps(report, indent=2))
    return int(bool(mail_diff["missing"] or mail_diff["unexpected"] or host_diff))


if __name__ == "__main__":
    raise SystemExit(main())
Enter fullscreen mode Exit fullscreen mode

Run it with Python 3.10 or later. The expected result is an unexpected MX entry with preference 30 and an unsuccessful exit status. Remove that old exchange from the observed fixture to model convergence; the mail comparison then clears, while the chosen application hostname stays the same. Changing the active flag to east changes only the selected application name. It does not mutate either record set.

For a read-only API observation, set READ_PUBLISHED_RECORDS to 1, provide INFRAI_API_KEY, and set INFRAI_API_BASE_URL to the official HTTPS v1 API base. That mode prints the record-list response without assuming undocumented envelope fields. Use the discovered response schema to map it into the local comparison format; printing a response alone is not a drift verdict. The request uses an explicit GET, refuses redirects, and retries HTTP 429 with exponential backoff while honoring Retry-After. It performs no writes, so this observation step needs no write-deduplication key.

There is an intentional limitation: the regional comparison checks names, not address records or application health. A complete deployment must verify the required published records and application readiness through its actual observation path. Don't expand this little checker's green result into a claim it cannot support.

Rejected option and its valid use case

Reject DNS weights as the primary switch for this edtech application's immediate traffic movement. DNS changes can take hours to fully land, so changing weights creates an interval in which the published intent and cached behavior can differ. A flag selects among stable names without requiring a DNS edit for each traffic decision. That does not cancel requests already in progress or establish how quickly every application instance receives a flag update; the flag delivery design must specify those boundaries.

DNS weighting remains a valid choice when a team deliberately accepts slow convergence for coarse distribution and can tolerate the transition. Here, the acceptance criterion is tighter: a reviewed region addition updates configuration, a published-record comparison checks drift, and the application flag chooses an approved destination. Company mail records remain subject to their own provider requirements and review.

References

Top comments (0)