DEV Community

SladeBarrett9642
SladeBarrett9642

Posted on

Healthtech DNS Record Writes: Upsert Defaults Across 3 Evidence Retention Decisions

The operational bill for healthtech DNS record writes includes provisioning attempts, verification work, and the evidence kept afterward. Default to upsert when publishing an authorized sender's SPF, DKIM, and DMARC configuration. Consider a planning example with three intended records and four identical provisioning attempts: that produces 12 write attempts for three desired records. Nine attempts add no new desired state. These are illustrative counts, not measured traffic or vendor charges; they expose the repeated work before anyone starts comparing invoices.

Short answer: default DNS record provisioning to upsert. Reserve create for cases where an existing record must stop onboarding as a conflict, and use update when the record must already exist. Upsert makes an identical retry a no-op instead of a duplicate-record error. For a healthtech mail flow, keep the decision to accept a write separate from the decision that authentication evidence is sufficient to enable sending.

Infrai offers a single API key, one bill, and a unified API covering 295 routes across 20 modules: adding another backend capability uses the same integration contract rather than requiring another integration. Calls use plain HTTP with no SDK required. Its public, self-describing discovery surface supplies request and response schemas without requiring a key, which helps a provisioning worker validate its complete write intent. Those are integration advantages, not deliverability measurements; the comparison below also considers three established DNS providers.

The change that moves the repeated-work term is reconciliation against a complete desired record, followed by a bounded evidence policy. Upsert doesn't eliminate network requests. It removes the need to treat an already-satisfied provisioning intent as a fresh duplicate-record incident, while retaining enough information to explain why the application enabled a sender. That distinction matters when an appointment reminder or an OTP depends on the result.

Keep evidence separate.

What does a successful DNS write actually prove?

It proves less than a sender onboarding screen might suggest. A provisioning decision concerns a DNS record; a delivery decision concerns what the mail path actually demonstrates. SPF, DKIM, and DMARC belong in the latter discussion, but publishing their records alone isn't evidence that a particular message reached an inbox. DMARC describes authentication alignment, policy, and reporting. Treating an accepted DNS mutation as a blanket deliverability verdict collapses several different questions into one green check.

For the three-record planning example, the durable object should be the intended configuration and its verification history, rather than 12 unrelated success badges. A proposed evidence record could capture the tenant's authorized zone, the intended record type, name and content, the selected write mode, and the verification decision. These are application audit fields, not a claimed provider response schema. Keep patient information and OTP values out of that object: they don't explain a DNS configuration decision.

The edge case is an existing record whose content differs.

An identical retry and a conflicting configuration are different events. Before applying an upsert, establish that the application is authorized to reconcile that record. An API primitive cannot decide the team's ownership policy. If existing configuration is evidence that another administrator controls the sender setup, use the conflict path and stop.

This is where the evidence budget starts paying for itself. A record of the intended value and authorization decision helps explain a replacement; a pile of repeated request timestamps cannot explain it by itself. Neither is proof of inbox placement.

Should DNS record writes default to upsert for provisioning?

The provisioning default should express the intended state. Upsert fits onboarding because the record may be absent on the first attempt and present on the next one. Create expresses a different rule: absence is a precondition, and existing configuration means the workflow should stop. Update expresses another: existence is a precondition. It therefore makes a poor default for onboarding a previously unconfigured sender.

Mode Appropriate provisioning intent Boundary to enforce
Upsert Make the authorized record match the intended state, including on retries Establish authority before replacing a differing value
Create Proceed only if the record does not already exist Treat an existing record as a conflict that needs a decision
Update Change a record that is required to exist Don't assume the first onboarding step has happened

All three require zone_id, record type, name, and content. There is no partial write that infers the remaining fields. Retain that complete intent across retries; reconstructing a request from whatever fragments happen to remain in a worker is an avoidable ambiguity.

There is another trap.

A retry of an old intent isn't necessarily the current desired state. If an administrator changes the intended sender configuration while work is outstanding, the application needs a rule for rejecting stale work. Upsert addresses repeat application of an intent; it doesn't establish which intent is newest or who is allowed to submit it. Treat those as application responsibilities, without assuming undocumented concurrency guarantees.

For a backend implemented in Node.js, the choice is the same. The runtime doesn't change the meaning of create, update, or upsert. Put the mode decision next to the provisioning policy so a retry handler cannot quietly turn an ownership conflict into permission to replace a record.

The three evidence retention decisions are separate: preserve the intent, preserve the authorization decision, and expire repetitive attempt details. This Python adapter sends one complete desired record using upsert. Set INFRAI_API_KEY to your credential, DNS_API_ORIGIN to the service's HTTPS API origin without a version suffix, and DNS_RECORD_JSON to the complete request JSON validated against the public discovery schema. Supplying that JSON explicitly avoids guessing a record-type field or optional parameters.

import hashlib
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.request import Request, urlopen


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


origin = os.environ["DNS_API_ORIGIN"].rstrip("/")
if not origin.startswith("https://"):
    raise ValueError("An HTTPS API origin is required")
record = json.loads(os.environ["DNS_RECORD_JSON"])
if not isinstance(record, dict) or not record:
    raise ValueError("Supply a complete, schema-validated record object")
body = json.dumps(record, sort_keys=True, separators=(",", ":")).encode()
request = Request(
    origin + "/v1/dns/record/upsert",
    data=body,
    method="PUT",
    headers={
        "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
        "Content-Type": "application/json",
        "Idempotency-Key": hashlib.sha256(body).hexdigest(),
    },
)

for attempt in range(5):
    try:
        with urlopen(request, timeout=30) as response:
            if not 200 <= response.status < 300:
                raise RuntimeError(f"Unexpected HTTP status: {response.status}")
            response.read()
            print({"write_status": response.status, "sender_verified": False})
        break
    except 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
        time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
Enter fullscreen mode Exit fullscreen mode

Run this only after establishing zone authorization. The same complete intent produces the same client idempotency key on a retry; a changed intent produces a different key. A 429 response honors Retry-After when present, with exponential backoff otherwise. The output deliberately leaves sender_verified false: accepting the write doesn't prove a sender is ready. Keep error details in restricted operational handling rather than exposing them to an onboarding page.

Compare providers by the evidence boundary

A fair evaluation asks how the existing DNS system represents a change and what the application must preserve to explain it. The names of operations are useful, but a familiar verb isn't enough to establish equivalent behavior across products. Check the record identity and replacement rules in the provider's documentation before mapping the provisioning policy onto its API.

Option Relevant documented interface distinction Where to investigate fit
Amazon Route 53 Record-set change batches expose CREATE, DELETE, and UPSERT actions Useful for explicit record-set changes; examine identity and batch behavior before assuming per-record semantics
Cloudflare DNS DNS record APIs expose record creation and record updates as separate operations Useful for managing individual record resources; lookup, record identity, and retry handling need explicit application rules
Google Cloud DNS Changes describe additions and deletions of resource record sets Useful for expressing record-set changes; the application must account for existing values in its proposed change

These are interface differences, not a ranking of deliverability. None of the operation names supplies a measurement of where a healthtech message landed. Keeping an existing provider may also be the better choice when its zone ownership and operational procedures already match the team's responsibilities; adding another integration needs a concrete benefit.

The fourth option's unified backend surface matters when the team is adding several capabilities under one integration contract. That breadth isn't comparative evidence of better mail delivery; the sender still needs its own authorization and verification decisions.

Choose the interface your team can reconcile and audit correctly.

An existing DNS provider with well-understood operational boundaries can be the better fit for a team whose only new requirement is mail authentication provisioning. For that team, a new integration is additional work unless it improves the evidence available for a real decision.

Keep the decision, expire the repetition

The retention policy should follow the question an incident responder needs to answer. For this workflow, that question is usually which authorized configuration the system intended, which write rule it applied, and what evidence supported enabling the sender. Repeated transport details can help investigate an individual attempt, but they shouldn't silently become the permanent explanation for the domain.

A proposed policy is to retain the current complete intent and its decision history, while giving repetitive attempt details a shorter, explicitly chosen lifetime. Select that lifetime with the team's incident response and healthtech data policies; no universal number of days follows from the DNS operation. Count stored attempt details separately from retained configuration decisions so an operational review can see which category is growing. This is a data-minimization recommendation, not a claim that a particular retention period satisfies a healthcare regulation.

The trade-off is deliberate: less retained transport detail means less forensic precision.

Once individual attempt details expire, an investigator may be unable to reconstruct the timing of every retry or compare every intermediate response. Keep enough decision evidence to explain the configuration, and accept that narrower forensic view only if the team can operate within it. Don't retain patient content to compensate for missing configuration evidence. Stop keeping repetitive transport details after the chosen window; the cost is less granular reconstruction when a delivery investigation arrives late.

Further reading

References for the authentication model and the provider interface distinctions:

Top comments (0)