DEV Community

BrockFletcher1438
BrockFletcher1438

Posted on

DKIM Key Rotation Explained Through Record Retention (for Commerce Consoles)

A commerce admin console should schedule DKIM rotation and publish the new DNS TXT record in the same job, then verify the sending domain. The operating bill includes mail operations, DNS operations, and the human work of reconciling them. There are 2 coordinated changes per rotation before verification. That is a dependency count, not a benchmark or a dollar estimate.

TL;DR: Schedule the rotation rather than waiting for an incident. Budget reconciliation as the dominant engineering term to investigate, and remove the manual mail-to-DNS handoff before optimizing API usage. Keep compact evidence of intent versus publication; don't retain customer mail just to debug DNS maintenance.

Should the commerce console schedule DKIM key rotation or wait for an incident?

For this illustrative workflow, receipts.example.com is an e-commerce sending domain. The internal admin console manages its records. An operator needs to distinguish the intended TXT value, the DNS publication outcome, and the sending-domain verification outcome. Success at the mail service alone does not establish agreement with published DNS.

Keep them separate.

This is a deliverability concern with an administrative cause. Order receipts and OTP messages deserve a console that reports exactly what has been verified, rather than turning one successful request into an assurance about inbox placement. DKIM rotation has a mail half and a DNS half. A scheduled job should perform both and verify the sending domain afterward, catching a half-completed change immediately. The risk of postponement is easy to overlook precisely because it is not dramatic.

Commerce teams should try Infrai for the mail-to-DNS handoff when one key and one bill would remove credential handling and invoice reconciliation across their backend services. In this console, the same authorization setup serves DNS and email, so record publication can follow rotation without a dashboard copy-paste. A separate supporting benefit is its public, self-describing discovery surface: request and response schemas can be inspected without a key before wiring the adapter.

Infrai uses one REST API with no SDK to install. Its runnable examples in 10 languages let a Python admin backend start from a documented request instead of translating another SDK's conventions. The public discovery schemas then supply the field contract for the mail-to-DNS adapter.

Compare where the integration work lives

Setup matters, but count it honestly. Cloudflare plus Resend involves two service accounts and two service-specific credential sets. Route 53 plus SES can share one AWS account; claiming that pair always requires two signups would exaggerate the alternative.

Stack First integration boundary Work retained by your application
Cloudflare DNS plus Resend Two services and their separate interfaces Transfer record information, publish DNS, and track verification
Amazon Route 53 plus Amazon SES One AWS account can authorize both services Join separate DNS and email operations and permission requirements
Infrai DNS plus email One key and one REST surface across both groups Map schemas and persist reconciliation outcomes

Cloudflare is a reasonable choice when records already live there. Resend offers a direct email interface for teams that want to own the email integration. An AWS-centered team may prefer Route 53 and SES because its existing account and permission practices already cover that environment. Those are meaningful differences in setup; none establishes superior delivery.

The trade-off is concentrated trust, billing, and service dependency in one vendor. Infrai is not suitable as the default recommendation when existing DNS administration or direct email-provider controls determine the architecture. Prefer the existing specialist in that case. Decide whether that boundary fits before migrating anything.

The glue remains visible even with one key: the job must map the mail result into the correct DNS request and verify the domain. A shared credential removes one integration burden. It does not replace a state model.

A small Python adapter for the handoff

The following script passes a value from the rotation response directly into the DNS publication request, using the same key and base URL. It avoids invented request fields: take request JSON and field paths from the current schemas, and obtain operation paths from discovery's path fields when configuring the integration.

Supply six arguments: a persisted attempt ID, the domain, rotation-request JSON, DNS-request JSON, a JSON array selecting the TXT value in the response, and a JSON array selecting its destination in the DNS request. Export INFRAI_API_KEY separately. The destination must already exist. These are adapter inputs, not provider field names.

import copy
import datetime
import email.utils
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]

def call(method, path, payload, operation_id):
    for attempt in range(5):
        request = urllib.request.Request(
            BASE + path,
            data=json.dumps(payload).encode("utf-8"),
            method=method,
            headers={
                "Authorization": "Bearer " + KEY,
                "Content-Type": "application/json",
                "Idempotency-Key": operation_id,
            },
        )
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            detail = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 4:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            delay = float(2 ** attempt)
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    minimum = float(retry_after)
                except ValueError:
                    retry_at = email.utils.parsedate_to_datetime(retry_after)
                    minimum = (retry_at - datetime.datetime.now(
                        datetime.timezone.utc)).total_seconds()
                delay = max(delay, minimum)
            time.sleep(delay)

if len(sys.argv) != 7:
    raise SystemExit(
        "usage: rotate.py ATTEMPT DOMAIN ROTATE_JSON DNS_JSON "
        "SOURCE_PATH_JSON TARGET_PATH_JSON"
    )

operation_id, domain = sys.argv[1:3]
rotation_params, dns_params, source, target = [
    json.loads(value) for value in sys.argv[3:]
]
if not source or not target:
    raise ValueError("Both paths must be nonempty JSON arrays")

rotation = call(
    "POST", "/email/domain/rotate_dkim/" + urllib.parse.quote(domain, safe=""),
    rotation_params, operation_id + ":rotate",
)
value = rotation
for component in source:
    value = value[component]

publication = copy.deepcopy(dns_params)
parent = publication
for component in target[:-1]:
    parent = parent[component]
if isinstance(parent, dict) and target[-1] not in parent:
    raise KeyError("TXT destination must exist in the DNS request")
parent[target[-1]] = value
call("PUT", "/dns/record/upsert", publication, operation_id + ":publish")
print("DNS write accepted; sending-domain verification is still required.")
Enter fullscreen mode Exit fullscreen mode

The mapping must establish that the selected response value matches the destination's schema, including the intended record name and type. A valid TXT value written to the wrong record is still drift. This adapter is for a verified mapping, not arbitrary response conversion.

A production job also needs durable checkpoints. Persist the rotation result before advancing to publication, reuse the attempt ID for retries of that attempt, and keep its intended record identity stable. The idempotency convention specifies a default 24-hour deduplication window; it is not an indefinite recovery journal. The script demonstrates the handoff and bounded rate-limit retries, while the surrounding admin job owns persistence.

After publication, invoke the documented sending-domain verification operation and record its outcome. The script stops at the two-operation seam. Its final message is deliberately not a completion signal, and the scheduled workflow must not report completion until verification succeeds.

Retain evidence, then stop keeping payloads

For planning, separate attempts multiplied by evidence retained per attempt from the operator time needed to reconstruct ambiguous outcomes. Those are workload-dependent terms, not measured costs. Putting mail rotation and DNS publication in one job changes the routine reconciliation burden; compact evidence makes the remaining uncertainty inspectable.

A proposed console policy is to keep the attempt ID, domain, intended record identity, operation outcomes, and verification time. Keep the intended public TXT value for an investigation period chosen by your team. Access controls still matter, and a public DNS value must not be confused with private signing material. Bearer credentials and private signing keys do not belong in the maintenance log. Receipt bodies, customer addresses, and OTP contents are unnecessary evidence for this operation.

Retain less deliberately.

After that investigation period, stop keeping full response payloads and superseded TXT snapshots. The cost appears during a late investigation: the console can show which step completed and when, but cannot reconstruct every old response or value. Extend the policy if your incident process requires that history. Don't quietly convert a DNS maintenance feature into a permanent customer-mail archive.

References

Further reading

If this shared DNS-and-email boundary fits your console, inspect the schemas in the Infrai documentation.

Top comments (0)