DEV Community

PrestonCole1111
PrestonCole1111

Posted on

Healthtech Custom Domain Onboarding: Node.js Record Reconciliation Against DNS Drift

To implement custom domain onboarding in a healthtech admin console, start with a difficult constraint: saved DNS instructions and published DNS records can disagree. Add a zone and write its record, but verify against the current intent. An administrator can refresh the page, another operator can change the intended target, and verification can finish after that change. A green badge must describe the current intent.

TL;DR: To implement custom domain onboarding, add the domain, persist the returned zone_id on the tenant, upsert the complete record, and poll verification from a scheduled job. Make the sequence idempotent. Tie each verification result to the intended record revision so an older result cannot activate a newer configuration. In a Node.js application, the durable handoff deserves more attention than the HTTP wrapper.

The deciding question is whether the console can explain a disagreement between intent and published records. Provider selection comes after that design. The examples below use fictional clinic identifiers and proposed application policies, not production measurements.

How do you prevent DNS drift during custom domain onboarding?

Consider tenant clinic-17 and the fictional hostname portal.clinic.example. Revision 7 requests a CNAME pointing at intake.example; revision 8 changes the intended target to appointments.example. A successful check attached to revision 7 must not mark revision 8 ready. Store the tenant, domain, zone identifier, full intended record, revision, and verification outcome together in application state, with enough history to explain who approved the change. Otherwise an operator sees “verified” but cannot tell which target earned that result.

Keep revisions separate.

The domain-add response supplies the zone identifier needed by subsequent record operations. Persist it immediately. A refresh should resume the tenant's existing onboarding attempt. Use an application uniqueness rule for the tenant/domain pair and serialize competing changes to that pair.

Record writes require zone_id, record type, name, and content together. Treat that as a reconciliation boundary: construct the complete desired record from the saved revision before writing it. A console form that changes only content should still produce a complete operation internally. Otherwise the worker and the administrator can be talking about different versions of the record.

A verification result has a narrow meaning. Keep patient information out of DNS values and job labels. Don't make a DNS success badge imply that an intake flow, consent workflow, or clinical notification path has been reviewed.

Derive the worker from the drift constraint

The request handler should save intent and return a pending state. A worker adds the domain if the tenant lacks a stored zone identifier, persists that identifier, and upserts the desired record. A scheduled job then attempts verification. Inline verification will usually encounter propagation delay, so holding the admin request open adds waiting without providing a dependable activation boundary.

Use a bounded schedule. As an application policy, a team might start with a 60-second interval and send unresolved cases for operator review after 30 minutes. Those numbers are proposed operating policy, not a provider guarantee.

Each job needs the tenant identifier and revision. Before writing, load the current intent; before accepting a verification result, compare the job's revision again. If it has changed, retain the result as history and schedule work for the current revision. This matters even when every individual request succeeds, because a successful result can arrive after the administrator changes the configuration. The exhausted verification window should preserve pending intent and history rather than erase the disagreement an operator needs to investigate.

Success can arrive late.

A retry must retain the same operation identity for the same intended change. A new revision gets a new identity. Save that mapping durably, and distinguish the add operation from the record write. Provider deduplication helps, but the application still needs to prevent page refreshes and restarted workers from duplicating local state. On HTTP 429, honor Retry-After when present and use exponential backoff rather than retrying in a tight loop.

For an engineer responsible for OTP delivery, the analogous trap is treating request acceptance as proof of the outcome the user needs. DNS verification deserves its own state. Keep email authentication review separate: changing a portal hostname doesn't establish DMARC alignment for a notification sender. RFC 7489 describes that sender-domain concern; it is not a portal readiness check.

Make the revision check an atomic decision

The Node.js handler and scheduled worker should share the same durable intent record. An application-level check followed by an unconditional update leaves a race: an administrator can save a new target between those two operations. Accept readiness only through a conditional database update tied to the revision that was checked.

The runnable Python example below covers the first durable handoff: add the domain and save its zone identifier before doing record work. Set DNS_API_BASE_URL to the configured service base ending in /v1, INFRAI_API_KEY to the API key, and ONBOARDING_ID to the durable tenant/domain attempt identity. Standard input supplies the domain-add JSON body matching the published request schema. Keeping that input external avoids guessing undocumented field names. This is the add stage, not a complete onboarding worker; the Node.js application still needs record upsert and scheduled verification.

import email.utils
import json
import os
import sqlite3
import sys
import time
import urllib.error
import urllib.request

base = os.environ["DNS_API_BASE_URL"].rstrip("/")
key = os.environ["INFRAI_API_KEY"]
attempt = os.environ["ONBOARDING_ID"]
payload = json.load(sys.stdin)


def add_domain():
    headers = {
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
        "Idempotency-Key": attempt + ":add",
    }
    for retry in range(4):
        req = urllib.request.Request(
            base + "/dns/domain/add",
            data=json.dumps(payload).encode(),
            headers=headers,
            method="POST",
        )
        try:
            with urllib.request.urlopen(req, timeout=20) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            reason = error.read().decode(errors="replace")
            if error.code != 429 or retry == 3:
                raise RuntimeError(f"HTTP {error.code}: {reason}") from error
            delay = 2 ** retry
            value = error.headers.get("Retry-After")
            if value:
                try:
                    delay = max(delay, float(value))
                except ValueError:
                    date = email.utils.parsedate_to_datetime(value)
                    delay = max(delay, date.timestamp() - time.time())
            time.sleep(delay)


def zone_ids(value):
    if isinstance(value, dict):
        for name, child in value.items():
            if name == "zone_id" and isinstance(child, str) and child:
                yield child
            else:
                yield from zone_ids(child)
    elif isinstance(value, list):
        for child in value:
            yield from zone_ids(child)


with sqlite3.connect("onboarding.sqlite3") as db:
    db.execute(
        "CREATE TABLE IF NOT EXISTS onboarding "
        "(attempt TEXT PRIMARY KEY, zone_id TEXT NOT NULL)"
    )
    saved = db.execute(
        "SELECT zone_id FROM onboarding WHERE attempt = ?", (attempt,)
    ).fetchone()
    if saved:
        zone_id = saved[0]
    else:
        found = set(zone_ids(add_domain()))
        if len(found) != 1:
            raise RuntimeError("Expected one unambiguous zone_id")
        zone_id = found.pop()
        db.execute(
            "INSERT INTO onboarding VALUES (?, ?)", (attempt, zone_id)
        )
        db.commit()
print(json.dumps({"attempt": attempt, "zone_id": zone_id}))
Enter fullscreen mode Exit fullscreen mode

The response walker rejects ambiguous identifiers without assuming an undocumented envelope layout. The immediate commit preserves the zone identifier for a restart. This compact example assumes one process at a time; a production console needs concurrency controls around its tenant/domain mapping. Keep a conditional revision update at the later acceptance boundary, and retain the observation for review.

There is a second boundary before the write. Serialize record changes for the same tenant/domain so an old worker cannot overwrite a newer target. A conditional readiness update prevents a stale badge, but it cannot undo a stale DNS write. After a superseded job finishes, reconcile the current complete record again before scheduling its verification.

Compare providers at the control boundary

Choose around where authoritative DNS and hostname onboarding responsibilities already live. These options expose different integration surfaces; they are not interchangeable feature bundles. The source documentation identifies those surfaces rather than establishing comparative performance.

Option Relevant documented surface Fit and boundary to evaluate
Cloudflare for SaaS Custom hostnames and hostname validation Evaluate for customer hostname onboarding in that platform. Keep hostname validation distinct from the application's intended DNS revision.
Amazon Route 53 Hosted zones and resource record sets Evaluate when authoritative DNS is already there. Tenant mapping and revision-aware verification remain application work.
DNSimple Domain, zone, and record APIs Evaluate for an existing domain-management workflow. Check how zone identity maps to the application's durable onboarding attempt.

Infrai offers one key, one bill across 295 routes and 20 modules through a plain REST API, with no SDK to install. For the console, a single API key covers DNS and scheduling, and unified billing means one invoice to reconcile for that workflow. Any HTTP-capable runtime can call the API without maintaining a client-library version. This is a concrete reduction in integration work: a team can manage DNS records and schedule their verification without provisioning separate service credentials. Public discovery is self-describing, with request and response schemas available without a key, so the console team can inspect the complete record contract before implementing forms and workers.

The trade-off is a shared vendor dependency. This approach is not a fit when the console must preserve an existing Route 53 operational boundary; choose that provider directly instead. Shared credentials do not replace tenant authorization, durable intent, or concurrency control. Choose the combined service when reducing integration surfaces matters; favor an established DNS provider when preserving the team's existing DNS controls matters more. No provider choice removes the stale-result race.

For Cloudflare for SaaS plus an in-house poller, assume one provider signup and one provider credential set, with the poller running on existing infrastructure. A separately hosted scheduler adds its own account and credentials. The glue remains yours: store hostname identifiers, schedule checks, handle retries, correlate results to revisions, and expose pending status. An in-house process is not automatically a second SaaS signup.

Roll out against intent, then enable writes

Start by recording intended records while retaining the existing change process. Compare observed records with the saved intent, not merely the last successful job. Test a refresh during onboarding, two conflicting edits, a rate-limited request, and a verification result that arrives after its revision has been replaced.

Then enable writes for a limited tenant cohort. Require a persisted zone identifier before record work, a complete record at the write boundary, and a matching revision before readiness changes. Keep unresolved attempts visible for operator review. The migration is ready to expand when the console can explain which intended target was written, which revision was checked, and why the tenant is still pending.

Sources

References for the standards and provider surfaces discussed above:

Top comments (0)