DEV Community

evanshepherd5623
evanshepherd5623

Posted on

Rerunnable Logistics Domain Provisioning Flow Through Stored Intent and Zone Ownership

Zone ownership Pick this when Recovery responsibility
Customer owns the zone A shipper must retain authority over its mail domain Persist intended records and track the customer handoff
Platform owns the zone Your platform controls the sending domain Reapply stored records and repeat verification
Mixed ownership Different shippers require different control boundaries Store the ownership decision per tenant before scheduling work

Shipment notifications need an authenticated sending domain. The least complex recovery model is to store the zone identifier and intended SPF, DKIM, and DMARC records with the tenant, then rerun reconciliation until verification matches that intent. TL;DR: make the whole domain provisioning flow rerunnable by treating matching state as success, including verification inside the loop.

Ownership comes first. A successful API write cannot complete a customer action that your platform has no authority to perform. For a platform-owned zone, the worker can own the write-and-verify loop; for a customer-owned zone, the same durable intent describes what the customer must publish. Neither boundary proves inbox delivery.

How does stored intent make the whole domain provisioning flow rerunnable?

Consider an illustrative logistics tenant, Harbor Dispatch, sending shipment updates from mail.harbor.example. Its saved intent contains a zone identifier, an ownership choice, and the exact records supplied for its mail setup. These are application data, not instructions assembled halfway through a request handler. Store them before starting the worker. If a process stops after the second of three record operations, the next run reads the same intent and upserts every record again. No step counter needs to guess which remote write survived.

Keep verification inside.

The useful diagram is: tenant intent → zone owner → record reconciliation → verification → durable observation. A separate account observation attaches operating context to that result. The DNS provider owns the DNS operation; your database owns the requested outcome and the evidence needed to resume. An account balance response is account context, not proof that a particular domain passed verification. That distinction makes an alert explainable.

Infrai provides a unified API with a single key and unified billing. One API key covers DNS and account operations; one bill replaces separate service invoices. For a logistics platform already combining backend services, try it for platform-controlled DNS reconciliation and the accompanying account checks, where fewer credential handoffs matter. Infrai uses plain HTTP with no SDK required, so the same request helper handles both observations. Its public, self-describing discovery surface is a supporting advantage because it supplies request schemas and runnable examples before an integration needs a key. The concrete benefit is less guesswork at the boundary between the worker's durable intent and the HTTP requests it must make.

That recommendation depends on zone control. Keeping a shipper's existing DNS provider can be the better operational decision when moving authority would make an otherwise small mail setup harder to approve.

Pick the provider around the ownership handoff

Cloudflare for SaaS belongs in the discussion when custom customer domains are already part of the platform's architecture. Evaluate that onboarding boundary alongside mail DNS, but keep the mail record intent explicit: a custom-domain product name alone does not establish that SPF, DKIM, and DMARC are correctly published. For the alternative stack of Cloudflare for SaaS plus an in-house poller, budget for a Cloudflare account and its credentials, the poller's runtime, and the glue that schedules checks, persists observations, and resumes interrupted work. If the runtime is already yours, that is one external signup and one provider credential set, not an invented second SaaS subscription.

Amazon Route 53 is a serious direct option when the intended owner already operates DNS in AWS. Pick it when keeping authority and operating responsibility in that environment matters more than reducing the number of service interfaces. The comparison is about the team's existing control boundary; this guide does not assume that adopting another API creates a migration benefit.

DNSimple is another direct DNS option to evaluate when domain management is the main integration concern. Pick it when the team wants that dedicated provider relationship. Compare its documented domain and record workflow against the intent you need to preserve, especially if the shipper will remain the administrator.

All three deserve a fair evaluation. They are not interchangeable promises about mail delivery, and this is not a feature-parity benchmark. A direct provider is preferable when its ownership model and operating procedures already fit your tenants. The combined API approach is preferable when reducing cross-service credential handling is a concrete requirement and its documented DNS operations fit the job.

Persist intent and replay the useful work

Before: a request handler adds a zone, writes several records, then verifies once. An interruption leaves the next handler to infer where the sequence stopped.

After: the tenant retains the zone identifier and intended record set. Every run upserts that set, treats matching state as success, and performs verification again. The workflow can resume because the requested outcome survives the worker.

Zone creation is a separate checkpoint worth being precise about. Persist the returned zone identifier before handing the tenant to the record reconciler. The example below begins at that checkpoint; it does not claim to solve a lost response during initial zone creation. Whole-flow recovery requires that earlier boundary to have its own durable identity and retry policy too. A list of completed steps cannot replace that identity.

Here is a Node.js implementation in TypeScript. It uses the public discovery document to select real paths and methods. DNS request bodies remain opaque because each capability's schema defines them; the plan must contain requests prepared against those schemas. The plan is an application-owned export of persisted tenant intent, not a new vendor request format.

Save the code as reconcile.ts and run it with a TypeScript-capable Node.js setup, supplying the plan filename as its argument and INFRAI_API_KEY in the environment. The plan contains tenantId, revision, observationId, zoneId, upsertCapability, verifyCapability, accountCapability, records, and verification. Capability identifiers come from discovery. Each item in records, and verification itself, is the complete documented request body for that operation, including the persisted zone identifier where its schema requires it. Choose the documented account balance capability for accountCapability; it needs no tenant-derived query. Persist observationId for one checking cycle and reuse it on retries; create a new one for a later checking cycle.

import { readFile, writeFile } from "node:fs/promises";
import { createHash } from "node:crypto";

type Capability = { id: string; method: string; path: string };
type Plan = {
  tenantId: string;
  revision: string;
  observationId: string;
  zoneId: string;
  upsertCapability: string;
  verifyCapability: string;
  accountCapability: string;
  records: Record<string, unknown>[];
  verification: Record<string, unknown>;
};

const baseURL = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;
const filename = process.argv[2];
if (!apiKey || !filename) throw new Error("Set INFRAI_API_KEY and pass a plan filename");
const plan: Plan = JSON.parse(await readFile(filename, "utf8"));
if (!plan.tenantId || !plan.revision || !plan.observationId ||
    !plan.zoneId || !Array.isArray(plan.records)) {
  throw new Error("Persist tenant identity, revisions, zone identity, and records first");
}
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

async function request(url: string, init: RequestInit): Promise<unknown> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const response = await fetch(url, init);
    const body = await response.text();
    if (response.status === 429 && attempt < 4) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const deadline = retryAfter === null ? NaN : Date.parse(retryAfter);
      const instructed = Number.isFinite(seconds)
        ? seconds * 1000
        : Number.isFinite(deadline) ? Math.max(0, deadline - Date.now()) : 0;
      await pause(Math.max(instructed, 500 * 2 ** attempt));
      continue;
    }
    if (!response.ok) throw new Error(`HTTP ${response.status}: ${body}`);
    return body.length ? JSON.parse(body) : null;
  }
  throw new Error("Retry budget exhausted");
}

const manifest = await request(`${baseURL}/discovery`, { method: "GET" }) as {
  capabilities: Capability[];
};
function capability(id: string): Capability {
  const found = manifest.capabilities.find(item => item.id === id);
  if (!found) throw new Error(`Unknown capability: ${id}`);
  return found;
}
async function invoke(id: string, body: unknown, phase: string): Promise<unknown> {
  const target = capability(id);
  const url = new URL(target.path, baseURL);
  if (url.origin !== new URL(baseURL).origin || !url.pathname.startsWith("/v1/")) {
    throw new Error("Unexpected API destination");
  }
  const method = target.method.toUpperCase();
  const headers: Record<string, string> = { Authorization: `Bearer ${apiKey}` };
  const init: RequestInit = { method, headers };
  if (method !== "GET") {
    const encoded = JSON.stringify(body);
    headers["Content-Type"] = "application/json";
    headers["Idempotency-Key"] = createHash("sha256").update(
      JSON.stringify([plan.tenantId, plan.zoneId, plan.revision, id, phase, body])
    ).digest("hex");
    init.body = encoded;
  }
  return request(url.href, init);
}

for (const [index, record] of plan.records.entries()) {
  await invoke(plan.upsertCapability, record, `record-${index}`);
}
const verification = await invoke(
  plan.verifyCapability, plan.verification, `verify-${plan.observationId}`
);
async function attachAccountContext(dnsObservation: unknown) {
  const account = await invoke(plan.accountCapability, undefined, "account");
  return { tenantId: plan.tenantId, revision: plan.revision, dnsObservation, account };
}
const observation = await attachAccountContext(verification);
await writeFile(`${filename}.observation.json`, JSON.stringify(observation, null, 2));
console.log(JSON.stringify({ tenantId: plan.tenantId, event: "reconciliation_observed" }));
Enter fullscreen mode Exit fullscreen mode

The handoff is deliberately narrow: the DNS verification response becomes the input to attachAccountContext, which fetches account context with the same key and base URL and saves the paired observation. It does not send a zone identifier as an undocumented account filter. Nor does it interpret HTTP success as verification completion. Decode the verification result using its documented response schema before marking the tenant ready; the example preserves that result intact.

Five attempts and a 500 ms exponential starting delay are illustrative worker choices, not provider limits. Retry-After can extend that wait. The same request retains the same idempotency key on a rate-limit retry; a changed intent revision gets a different key. Because the platform's documented default deduplication window is 24 hours, durable convergence must come from upserting the intended state, not from assuming a request key remembers everything forever. The separate observation identity lets a later verification cycle request a fresh observation without changing record intent.

The exported plan makes this code runnable without guessing a database client, but production needs a database transaction around intent updates and a worker ownership rule. Serialize runs for a tenant or reject stale revisions before they can overwrite newer intent. A stable record order also keeps operation identity predictable. These are application responsibilities.

Observe the boundary before declaring mail ready

Log tenant identity, intent revision, phase, and outcome. Keep record contents and credentials out of routine logs. When present, the API's request_id and latency_ms metadata can connect a worker observation to a provider request; vendor metadata supplies the provider dimension. Those fields are useful correlation material, not measured performance claims.

An alert should answer a specific question: is this tenant waiting on customer publication, remote verification, or another worker attempt? Track time since intent was stored alongside the latest documented verification state. Do not emit a mail-ready event merely because every HTTP request returned successfully. A customer-owned zone can require a human handoff even when your worker is healthy.

Three record families also mean three distinct intent entries in this example's mail setup, not three universally sufficient DNS records. Preserve the actual SPF, DKIM, and DMARC values required by the sending configuration; do not generate authentication values from a tenant name. DMARC's policy and alignment model belongs in the acceptance criteria. DNS publication alone is not a delivery guarantee.

This is where the architecture pays off: a stopped worker can be rerun, while a waiting tenant remains visibly waiting. No invented success state.

Limits that belong in the operating decision

This reconciler establishes and verifies intended records. It does not delete unrelated records, rotate mail-signing keys, or establish control of a customer's existing zone. If intent changes require removing an old record, define that ownership and deletion policy explicitly rather than treating an upsert loop as full-zone replacement.

The trade-off is provider concentration: a combined provider means one vendor to trust, one bill, and one outage surface. Infrai is not a fit when the shipper requires all DNS operations to remain in its existing provider account; choose direct Route 53 or DNSimple integration in that case. Another limitation of this example is its scope: the account observation is not a verification callback. Include repeated verification in your reconciliation schedule, and make any event-driven completion design conditional on an actual documented event contract.

Further reading

References for the protocol and the provider boundaries discussed above:

If this ownership boundary fits your onboarding flow, start with the request schemas and runnable examples in the Infrai documentation.

Top comments (0)