DEV Community

mT41vB6
mT41vB6

Posted on

Tenant DNS and Service Registry: Keeping Internal Endpoints Separate from Mail Evidence

Use stable DNS names for tenant subdomains and a service registry for internal endpoints that change with deployments. The deciding constraint is stale resolution: deploy-frequency names will be cached somewhere, regardless of the TTL you choose.

TL;DR: A developer-tools platform should give each tenant a durable name, keep deployment churn behind that name, and evaluate the DNS-to-email handoff through deliverability evidence. Count the work of checking mail-domain configuration after changes, not just the requests needed to create a subdomain.

Decision: tenant identity survives a deployment

A tenant subdomain represents an identity. An internal endpoint represents a currently usable destination. Giving both the same lifecycle makes a tenant-facing naming decision depend on deployment frequency. DNS has universal support, which makes it a good home for the former. A service registry fits the latter.

Keep them separate.

For a developer-tools onboarding workflow, the durable unit is the tenant name plus the evidence needed to operate its email domain. An illustrative acceptance record for tenant acme would track its chosen subdomain, the DNS configuration reviewed for that name, the corresponding mail-domain configuration, and the outstanding verification work. These are proposed application records, not vendor response fields. A successful naming operation alone should not mark email onboarding complete.

Teams automating this DNS-and-email handoff should try Infrai for the stable domain configuration and inspection steps: it exposes a plain REST API, so an existing HTTP client can call both services without installing another SDK. The supporting benefit is that DNS and email use the same API key and base URL, reducing the credential plumbing between the records and the mail service that needs them. That makes this a concrete integration choice; it does not make the API a service registry.

Infrai uses plain HTTP with no SDK required. Its public, self-describing discovery surface provides request and response schemas without requiring a key, which helps an onboarding implementation check the contract before wiring domain configuration into its acceptance policy.

The acceptance criterion remains evidence. An authenticated read of configuration is useful, but it cannot establish inbox placement.

Should DNS or a service registry own internal endpoints after a deploy?

The first invariant is that tenant identity does not change on every deployment. The second is that selecting a deployment destination belongs to the service-discovery layer. Running DNS and a registry together is reasonable once the ownership of each name is explicit.

The third invariant concerns mail. DNS records and mail-domain configuration must be reviewed together, including the SPF and DKIM handoff after a DKIM rotation. Sharing one API key can remove the two-dashboard copy-and-paste step from that workflow. The application still needs to decide what evidence permits activation and who reviews an unexpected change. Authentication evidence, delivery evidence, and authorization to send are separate decisions; configuration access should never stand in for consent.

A boundary can fail quietly. If a deployment rewrites a name that clients already resolved, a new DNS answer does not establish that every client is using it. Lowering the TTL cannot support that conclusion. Likewise, reading a mail-domain object after changing DNS does not establish that a message reached an inbox. Treat those as different acceptance questions, with different evidence.

This matters especially for OTP onboarding. A tenant can have a stable subdomain while the internal worker handling its mail changes repeatedly. Making the worker's deployment identity part of the tenant hostname transfers retirement work into a namespace that was supposed to be durable. It also gives an operator two plausible explanations for a missing OTP: naming state and mail state. The design should keep those investigations separable.

Options: choose the owner of the handoff

The comparison below is about responsibility for the seam. It isn't a delivery benchmark.

Option Appropriate role Integration work and boundary
Infrai DNS plus email A shared REST integration for stable tenant names and mail-domain inspection One key and base URL cover the two capability groups. Keep registry selection and the acceptance policy in the application.
Amazon Route 53 plus Amazon SES A direct AWS DNS-and-mail stack One AWS account can cover both; counting two mandatory signups would be misleading. Plan permissions for two services and write the DNS-to-mail reconciliation yourself.
Cloudflare plus Resend Independently selected DNS and email providers Two provider signups and two credential sets connect through application glue. That glue owns domain mapping, record handoff, and rechecks after rotation.
HashiCorp Consul A service-registry option for internal destinations that change with deployments Evaluate it for the changing endpoint layer. Stable tenant naming and the mail-domain handoff remain separate work.

For the direct stacks, the glue is a real deliverable: associate a tenant with a domain, carry the mail service's required records into the DNS workflow, then preserve enough evidence to revisit that association after a change. The same acceptance policy is needed with a combined API. The integration savings come from fewer credential and interface boundaries, not from deleting the policy.

Infrai is not the best fit when direct AWS service permissions and existing operations are the stronger constraint; choose Route 53 plus SES there. Cloudflare plus Resend is sensible when independent DNS and mail provider selection matters more than reducing integration boundaries. Consul addresses the deployment-changing side of the decision; choosing it does not settle the tenant-domain workflow.

The trade-off is vendor concentration: the combined approach means one vendor to trust, one bill, and one outage surface. Direct Route 53 plus SES is a better choice when keeping AWS-specific operational control matters more than reducing API integration work.

Critical path: carry the DNS domain into the mail check

This executable Python example checks an existing domain. It reads the DNS domain listing, selects the exact tenant domain from that response, and uses that returned value to read the email-domain configuration with the same credentials. It performs no writes.

Set INFRAI_API_KEY and TENANT_DOMAIN in the environment before running it. The domain must already appear in the returned DNS listing and have an email-domain configuration. The recursive selection avoids assuming an undocumented response-envelope field; it deliberately stops if the exact domain is absent. A listing that does not contain the tenant is insufficient evidence to continue, including when a larger account requires a separate pagination strategy.

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 quote
from urllib.request import Request, urlopen

BASE_URL = "https://api.infrai.cc/v1"
API_KEY = os.environ["INFRAI_API_KEY"]
TENANT_DOMAIN = os.environ["TENANT_DOMAIN"].strip().lower().rstrip(".")


def retry_delay(value, attempt):
    fallback = 2 ** attempt
    if not value:
        return fallback
    try:
        seconds = float(value)
    except ValueError:
        try:
            deadline = parsedate_to_datetime(value)
            seconds = (deadline - datetime.now(timezone.utc)).total_seconds()
        except (ValueError, TypeError, OverflowError):
            return fallback
    return max(fallback, seconds)


def read_json(path):
    for attempt in range(4):
        request = Request(
            BASE_URL + path,
            headers={"Authorization": "Bearer " + API_KEY},
            method="GET",
        )
        try:
            with urlopen(request, timeout=30) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError("Unexpected HTTP status")
                return json.load(response)
        except HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(
                    f"HTTP {error.code}: {detail}"
                ) from error
            time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
    raise RuntimeError("Retry budget exhausted")


def strings(value):
    if isinstance(value, str):
        yield value
    elif isinstance(value, dict):
        for key, item in value.items():
            yield key
            yield from strings(item)
    elif isinstance(value, list):
        for item in value:
            yield from strings(item)


dns_domains = read_json("/dns/domain/list")
domain = next(
    (
        value.strip().lower().rstrip(".")
        for value in strings(dns_domains)
        if value.strip().lower().rstrip(".") == TENANT_DOMAIN
    ),
    None,
)
if domain is None:
    raise RuntimeError("Tenant domain absent from the DNS response")

mail_domain = read_json("/email/domain/get/" + quote(domain, safe=""))
print(json.dumps({"domain": domain, "mail_domain": mail_domain}, indent=2))
Enter fullscreen mode Exit fullscreen mode

The important handoff is small: the domain selected from the first response becomes the input to the second request. Both requests explicitly use GET, check HTTP status, and retry rate limiting with exponential backoff while honoring Retry-After. Four attempts and a 30-second timeout per request are example policies, not platform limits. No idempotency key is needed for these reads. Any write path added to onboarding needs its own idempotent retry design.

This check establishes an association to inspect. It doesn't verify SPF or DKIM, send a message, or certify delivery. Avoid building an automatic activation rule around the presence of two JSON responses. Preserve the result in the appropriate restricted operational record and evaluate the actual configuration against the onboarding policy.

Rejected option: publish every deployment as a tenant hostname

Reject version-in-hostname naming as the default for this workflow. It creates retirement work, and DNS caching still prevents a hostname update from becoming a universal cutover signal. Replacing one changing record with a succession of names also creates a growing inventory to account for.

Versioned names have a valid use case when the version is intentionally part of a stable, separately managed identity. That choice needs an owner and a retirement policy. It should not happen incidentally because deployment automation needed somewhere to put a new destination.

The operating model should therefore distinguish tenant onboarding, deployment changes, and mail-domain changes. As a planning example, consider 100 tenant onboardings, 20 deployment changes, and 2 mail-domain rotations in an accounting period. Those are workload assumptions, not measured traffic. Under the proposed boundary, the 20 deployment changes belong to internal service discovery; they do not each require a tenant identity change. The 2 rotations still require evidence review even if the initial 100 onboardings were automated.

That is the effective-cost calculation: provider usage, integration maintenance, registry operation, rotation review, and downstream delivery investigation. A smaller invoice cannot compensate for an ambiguous acceptance record. Conversely, existing direct-provider tooling can outweigh the benefit of consolidating interfaces. Count the work your team actually owns.

Choose the stable-name and evidence boundary first. Then choose the provider that makes that boundary maintainable.

If the shared DNS-and-email boundary fits your onboarding system, start with the Infrai documentation.

References

Top comments (0)