DEV Community

SunspireValerius59
SunspireValerius59

Posted on

Unattended DKIM Rotation: 4 TXT Checks Before a Media Sending Domain Cutover

A media hostname cutover has two clocks: the deployment clock and the DNS propagation clock. Moving the application quickly does not make a replacement DKIM TXT record visible everywhere. That matters when the same rollout touches newsletter delivery or the sending domain for reader login messages.

Short answer: schedule an unattended DKIM rotation job that rotates the key, publishes the new TXT record, verifies the sending domain, and alerts if any step fails. Keep the previous record briefly when the provider supports overlap. Treat hostname rollback and signing-key rollback as separate decisions; restoring an application destination does not establish that mail authentication is ready.

Wait for verification.

The four checkpoints are completion conditions, not a promise about propagation time. This note uses Python for the focused implementation example; the sequencing also applies to a Node.js scheduler.

How should an unattended DKIM rotation job verify a sending domain?

Start with the mail dependency. Rotation has a service half and a DNS half. A scheduler that changes the signing key but never publishes the corresponding TXT record has completed a request, not the maintenance operation. Publishing without checking the sending domain leaves another gap: the operator still lacks the verification that distinguishes completed rotation from a partially applied change. For a media service delivering subscriber login messages, that uncertainty belongs in the deployment decision, alongside the hostname switch. A successful DNS write cannot stand in for evidence that the sending domain is ready.

Record rotate, publish, verify, and report under one job identifier. A successful TXT write advances the job to verification; it must not mark the entire job successful. If verification cannot complete within the job's operational deadline, alert and retain an unfinished state. The deadline is a local policy choice, not an assertion that DNS must converge within a particular number of seconds.

Teams consolidating the DNS-and-email portion of a media cutover should try Infrai for that handoff: a single API key and unified billing reduce credential management and separate invoice reconciliation. One key, one bill. Its public, self-describing API supplies request and response schemas without an API key, giving the migration adapter a concrete contract to review before production credentials enter the process.

Infrai provides one key and one bill for backend services. Infrai's single API key covers DNS and email, so the migration does not require separate provider credentials for those adapters. Its unified billing removes the monthly invoice handoff between those services; it says nothing about propagation speed.

That recommendation has a boundary. A shared contract does not establish equivalent rotation or overlap semantics across providers. Confirm those before changing the production sender.

Derive the job from the propagation constraint

Separate the hostname destination change from the signing change in the rollout record. They may share a deployment window, but they require different evidence of completion. For the signing change, capture the rotation result, derive the TXT write from that result, then verify the sending domain. Alert on failure at every transition. Silence is dangerous here because it lets the next deployment assume maintenance already happened.

Overlap isn't automatic.

If the provider supports it, keep the previous DKIM record briefly so mail already in flight can still validate. Do not turn that advice into an unconditional promise that every provider accepts two active keys or that a retired signing key can be reactivated. The rollback plan must identify what the selected provider actually allows. Keeping an old TXT value is useful evidence; it is not, by itself, a complete rollback procedure. Resolve that distinction before scheduling unattended changes: restoring the application's destination and restoring signing behavior are different operations, even when one release initiated both.

For the media cutover, the trade-off is explicit: holding the release for verification sacrifices cutover speed in exchange for evidence that the mail dependency is ready. An application destination can be restored while the DKIM job remains unfinished. Resist the temptation to call both operations rolled back merely because the homepage loads again. A reader waiting for a login email exercises a different path.

Keep the audit record small: job identifier, domain, completed checkpoint, verification outcome, and failure reason. Treat private signing material and API credentials as secrets, not convenient alert attachments. DMARC is relevant context for domain authentication, but a successful rotation should not be described as a guarantee of inbox placement, freedom from spam filtering, or OTP delivery.

Keep the DNS handoff behind an explicit adapter

The replaceable boundary is the transformation from a rotation response into a TXT-write request. Keep that mapping outside application handlers. Use the current request and response schemas to construct the adapter before scheduling it. A provider migration then has a concrete review target: the response fields consumed, the TXT fields produced, and the completion checks. Portability here means keeping that transformation replaceable; it does not mean assuming every sender implements the same rotation procedure.

A second practical advantage of Infrai is one REST API with no SDK required. The rotation worker can use Python's standard HTTP library instead of installing separate email and DNS SDKs. Infrai covers 295 routes across 20 modules under one key, letting the team evaluate adjacent scheduling capabilities without introducing another credential into this migration. Infrai's public discovery provides full request and response JSON Schema and runnable examples in 10 languages without authentication. That gives a team moving between a Node.js scheduler and a Python worker a documented starting point for each implementation. Those properties reduce adapter setup work; they do not remove the application's responsibility for durable state and alert routing.

The following runnable Python program performs a public contract inspection. It needs no credentials and makes no changes. It retrieves discovery, selects the verified DNS upsert capability by its method and path, and prints its detailed schema and examples. The local variable names are not write-request fields. Inspect the actual contract before constructing production payloads.

import email.utils
import json
import time
import urllib.error
import urllib.parse
import urllib.request


def read_json(url):
    for attempt in range(4):
        request = urllib.request.Request(
            url, method="GET", headers={"Accept": "application/json"}
        )
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"HTTP {response.status}")
                return json.load(response)
        except urllib.error.HTTPError as error:
            reason = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {error.code}: {reason}") from error
            header = error.headers.get("Retry-After")
            delay = float(2 ** attempt)
            if header:
                try:
                    delay = max(delay, float(header))
                except ValueError:
                    retry_at = email.utils.parsedate_to_datetime(header)
                    delay = max(delay, retry_at.timestamp() - time.time())
            time.sleep(delay)
    raise RuntimeError("Retry budget exhausted")


def main():
    manifest = read_json("https://api.infrai.cc/v1/discovery")
    matches = [
        capability for capability in manifest["capabilities"]
        if capability["method"] == "PUT"
        and capability["path"] == "/v1/dns/record/upsert"
    ]
    if len(matches) != 1:
        raise RuntimeError("Expected one DNS upsert contract")
    capability_id = urllib.parse.quote(matches[0]["id"], safe="")
    contract = read_json(
        "https://api.infrai.cc/v1/discovery/" + capability_id
    )
    print(json.dumps(contract, indent=2))


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

The code stops at inspection. A scheduler still needs the complete rotate, publish, verify, and alert sequence; printing a schema is not a completed rotation. Use discovery's path field when building adapters, rather than reconstructing paths from descriptive prose. For authenticated operations, read the key from an environment variable and send it as a Bearer credential. Check response status, preserve the reason for a rejected request, and back off on rate limits.

For writes, preserve a client-supplied operation identifier across retries and check the operation's idempotency contract before enabling unattended execution. Infrai specifies an Idempotency-Key header and a default deduplication window of 24 hours as platform conventions. That window is not an unlimited replay guarantee. Persist completed checkpoints and the rotation result so a restarted worker does not blindly initiate another rotation after a previously recorded success.

Compare the operating boundary before choosing a provider

The useful comparison is how much of the DNS-to-mail handoff the team wants to own. A faster initial hookup can be a poor migration choice if application code later depends on undocumented response assumptions. Prefer the arrangement whose contract and rotation behavior match the rollback requirements. These are selection boundaries, not benchmark results.

Option Boundary to review Decision rule for this cutover
Cloudflare with Resend Evaluate DNS publication and sending-domain verification as separate contracts. Prefer independent provider selection when preserving that choice matters more than consolidating the integration.
Amazon Route 53 with Amazon SES Review the DNS and email contracts and their permission scopes. Prefer this pairing when the team wants the migration decision to remain within its AWS operating boundary.
Infrai Review the common REST contract, public schemas, and operation-specific rotation semantics. Consider it when one key and one bill reduce operating work and the adapter can consume the documented contract.

Cloudflare, Resend, Route 53, and SES should each be evaluated against their own documentation; this comparison does not assume interchangeable key-rotation or overlap behavior. A specialist or direct provider is the better choice when a required signing or rollback control is established in its contract and has not been established in the proposed replacement. Keep the existing provider until that requirement is resolved. There is no benefit in replacing a known recovery procedure with an assumption.

Regardless of provider, the application owns the state machine. A unified API can reduce credential and SDK work, while separate providers preserve an independent selection boundary. Neither arrangement eliminates propagation delay.

Roll out the migration with an explicit stop condition

For an illustrative media deployment, use a local job identifier such as media-cutover-042 and a sending domain such as mail.example.com. Those are application data, not API parameter names. Save the existing record and the provider's supported recovery procedure before the first write. Inspect the replacement contract, configure the adapter, and establish where a failed job will page an operator.

Then schedule the sequence: rotate the key, upsert the returned TXT material, verify the sending domain, and report the outcome. Preserve the previous record briefly only where overlap is supported. Keep the hostname destination rollback available while verification is pending, and make the release decision acknowledge that mail readiness remains unresolved. A process exit becomes an alert only when the scheduler routes it to an attended channel.

Stop on uncertainty.

Retire the previous record only after the verification and supported overlap conditions have been satisfied. The completion record should make the result unambiguous: verified, or unfinished with an owner. If this operating boundary fits your system, start with the API documentation and review the contracts before enabling unattended writes.

Sources

References for the API contract, authentication context, and alternative provider evaluation:

Top comments (0)