Programming

Domain Provisioning Clocks: Python Retry Control Across 2 MX Cutover Boundaries

Idempotent domain provisioning for an e-commerce mail cutover has a timing constraint: a retry can converge the configured MX set without making every sender observe that set immediately. That constraint should determine the workflow. A successful configuration write and a completed mail cutover need separate evidence, even when both appear behind one setup button. Short answer: make domain provisioning a reconciliation loop over a versioned, complete desired MX record set. Let retries read and

Idempotent domain provisioning for an e-commerce mail cutover has a timing constraint: a retry can converge the configured MX set without making every sender observe that set immediately. That constraint should determine the workflow. A successful configuration write and a completed mail cutover need separate evidence, even when both appear behind one setup button.

Short answer: make domain provisioning a reconciliation loop over a versioned, complete desired MX record set. Let retries read and converge that set; track mail readiness separately from write completion. A retry should resume the same intent, while a newer cutover intent must prevent older work from restoring the previous destination. Choose cutover speed only within the overlap window your mail operations can support.

There are two clocks. One belongs to configuration changes. The other belongs to cached DNS answers and the mail systems still using them. Treating those clocks as interchangeable creates an awkward result: an onboarding screen can say complete while company mail still follows the earlier route.

What should an idempotent domain provisioning retry actually repeat?

Start with the unit of intent. For this design, it's the complete MX record set for one company domain, with an explicit revision and an authorized owner. It isn't an instruction to append another record every time a worker receives a message. The distinction matters during an ambiguous timeout: the write may have completed even though its acknowledgment never reached the worker. Replaying an append can change configuration; reconciling the same desired set should produce no additional change once the target is satisfied.

Consider an illustrative storefront, shop.example. Its approved target consists of preference 10 for mx-a.mail.example and preference 20 for mx-b.mail.example. These names are example data, not public services. The intended configuration contains both records. A worker that checks only for the first hostname hasn't established that the whole set matches, and a worker that adds both without inspecting existing records hasn't established that obsolete destinations are gone.

Compare complete sets.

Use a stable identity for the domain resource and a separate revision for each approved change. Retrying revision 7 should mean revision 7 again. Approving revision 8 should create a new intent, even if both operations concern the same domain. An idempotency key can identify repeated submissions, but it doesn't by itself establish that a delayed revision 7 worker still has permission to write. That requires a freshness check at the mutation boundary.

This is a proposed control-plane contract: store the desired revision durably, reject a reused request key with a different payload, and make the currently approved revision the authority for mutations. Keep company authorization attached to that resource. A matching domain string is insufficient evidence that a different tenant may take over its configuration.

Derive the write contract before choosing an upsert

The useful invariant is simple: replaying a revision cannot introduce additional MX destinations, and an obsolete revision cannot overwrite the current one. Build the adapter around that invariant. Normalize equivalent representations before comparison, preserve the preference associated with each destination, and scope replacement to the authorized MX record set. Broadly rewriting a zone would make unrelated mail authentication records collateral damage.

The following Python sketch illustrates the decision boundary. It computes a plan only; the final write still needs concurrency protection. The dataset is deliberately small so the stale-work case stays visible.

from dataclasses import dataclass

@dataclass(frozen=True, order=True)
class MX:
    preference: int
    exchange: str

def normalize(records):
    return frozenset(
        MX(record.preference, record.exchange.rstrip(".").lower())
        for record in records
    )

def plan_mx_change(job_revision, current_revision, observed, desired):
    if job_revision != current_revision:
        return "stale", None
    target = normalize(desired)
    if normalize(observed) == target:
        return "converged", None
    return "replace_mx_set", tuple(sorted(target))

desired = [MX(10, "mx-a.mail.example."),
           MX(20, "mx-b.mail.example.")]
assert plan_mx_change(7, 8, [], desired) == ("stale", None)
assert plan_mx_change(8, 8, list(reversed(desired)), desired) == (
    "converged", None
)

A check followed by an unprotected write leaves a race: a new revision can be approved between those two operations. Prefer a conditional mutation that rejects an outdated version when the underlying interface supports it. Otherwise, serialize this resource's writes in your control plane, including revision changes, and explicitly account for an outstanding write whose result is unknown. Merely canceling a worker doesn't prove its remote request stopped. For example, suppose revision 7 has passed a local freshness check and its remote write is still pending when revision 8 is approved. If that pending request eventually lands after revision 8's write, a local check that looked correct has still allowed the wrong destination to win. The adapter contract must address that ordering before the controller claims stale-work protection.

Timeouts leave uncertainty.

If the interface offers only individual record edits, intermediate states become part of the migration design. Adding before deleting preserves overlap but temporarily retains destinations; deleting before adding can leave an incomplete set. Neither sequence is equivalent to an atomic replacement. Document which intermediate states are acceptable before calling the adapter an upsert.

After an uncertain result, read the observed set and reconcile. Retry transient failures with a bounded policy; route authorization failures and rejected configuration to an operator instead of repeatedly replaying an unchanged request. Keep the last observation and its time so an acknowledgment is never mistaken for a fresh read.

DNS visibility and mail acceptance need separate evidence

The next boundary is operational. MX records direct incoming mail. DMARC evaluates authentication and identifier alignment for messages using a domain in the visible From address; RFC 7489 describes that policy and reporting framework. Moving MX records therefore doesn't, by itself, establish that order confirmations or password-reset messages authenticate correctly. Maintain a separate check for the outbound identities the storefront actually uses.

Don't combine those checks into a single green DNS badge.

For incoming mail, record the authoritative MX observation separately from observations through recursive resolvers. A recursive answer is evidence from that resolver at that moment, not proof that every sender has switched. Cached answers can outlive the configuration operation. Lowering a TTL immediately before a change doesn't retroactively shorten the lifetime of answers already cached under the earlier TTL. Plan the waiting period using the previous configuration, rather than starting the clock from the last successful API response.

For this proposed rollout, retain both mail destinations during an approved overlap window and verify that the destination intended to receive company mail is ready before changing the record set. Readiness should include an authorized test message reaching the expected mailbox. Preserve a minimal audit record of the test outcome; copying message bodies or customer information into provisioning logs adds an unnecessary data handling burden. A delivery test is a sampled observation, so name it that way in the operator view.

The awkward edge case is rollback. Restoring an earlier MX set is another configuration change, with another period of mixed observations. It cannot recall cached answers. Treat rollback as a new approved revision and keep the relevant receiving paths available under the same operational policy.

Replaying an old job isn't a rollback procedure.

Compare the waiting policies after defining the invariant

Once retries preserve intent, the remaining decision is how much uncertainty the business accepts during the transition. The comparison below describes design choices, not measured performance.

Waiting policy Evidence used to advance Operational consequence
Advance after configuration acknowledgment The write request was accepted Fast operator feedback; mail readiness still needs a separate status
Advance after authoritative verification The intended MX set is observed at the authority Better evidence of published configuration; cached routes can remain
Advance after verification and planned overlap Published configuration, sampled delivery, and the approved waiting window Slower retirement of the old destination; more explicit protection for mixed routing

For company mail at a storefront, a practical default is to separate early configuration feedback from permission to retire the old destination. That lets the UI show progress without promising universal propagation. The trade-off is continued operation of both receiving paths and a longer handover for whoever owns the mailboxes. If the organization cannot support overlap, that constraint must change the migration plan before the first write.

Track desired revision, observed MX set, last successful read, unresolved write attempts, sampled delivery results, and the operator responsible for retirement. These fields answer different questions. A queue retry count cannot explain which revision is live, and a successful test message cannot show that a delayed worker is harmless.

Roll out with replay and retirement as explicit gates

Before deploying the controller, exercise the failure that makes idempotency necessary: apply the intended write, discard its acknowledgment, then replay the job. The expected result is an unchanged complete MX set. Also delay revision 7 until revision 8 is approved, and verify that the stale job cannot mutate the resource. Test record ordering differences and partial observations without using live customer mail as test traffic.

Then stage one authorized domain through destination readiness, the approved revision, authoritative verification, and the planned overlap. Keep the old destination's retirement as a separate operator decision supported by recorded observations. Don't infer it from a worker finishing.

The completion criterion is precise: retries converge the current approved configuration, and the cutover record explains why the old receiving path can be retired. Configuration speed remains useful. It just needs its own clock.

References

The standards below support the DNS and authentication mechanisms discussed here. The versioning contract and rollout gates are proposed engineering policies.

Sources