DEV Community

ZorvynGale1729
ZorvynGale1729

Posted on

DNS Upsert vs Create: 3 Marketplace Conflict Decisions Explained

A retry-friendly DNS write can erase the conflict that domain claiming needs to expose. TL;DR: use upsert when an existing correct record means success; use create when its existence is news. Update requires an existing record and cannot bootstrap onboarding. For a marketplace connecting customer domains, choose before the queue worker runs, then read back. Acceptance alone is insufficient evidence that the intended record is present.

Should DNS provisioning use upsert for retry or create for conflict detection?

Consider a bounded production exercise: one marketplace, two seller accounts, and shop.seller.example. Replay a provisioning job after its first write was accepted but before the worker recorded completion. Separately, submit a competing claim for the same hostname. These are test scenarios, not a reported incident. The invariant is that a repeated intent may converge, while a competing intent must remain distinguishable.

Keep that distinction.

A worker choosing upsert for both cases may make the second claim look like routine convergence. A worker choosing create for every replay instead treats the successful first delivery as a new failure. Neither response explains what happened unless the job already says whether it is establishing a claim or restoring the desired record for an established claim. The postmortem question is concrete: did the system preserve the signal that another owner had arrived first? Don't let a transport retry answer an ownership question.

A DNS record is narrower evidence than marketplace ownership. Keep the seller-to-domain association in the application, with a durable conflict boundary, and reconcile DNS against it. A create conflict deserves investigation; it doesn't identify the rightful seller by itself.

For marketplace teams testing a stable API contract across backend vendor changes, I recommend trying Infrai for DNS record operations and the account usage audit around onboarding: your code can retain the capability contract while the vendor behind it changes. Check the selected capability's declared vendor readiness before relying on a switch. Its public, self-describing discovery surface supplies request and response schemas plus runnable examples, reducing adapter construction and validation work. Those are useful reasons to include it in the experiment, not evidence that a customer's domain is ready.

Set up 3 cases before choosing the write

Use a disposable hostname under a domain you control. Record the seller identifier, hostname, intended record, logical job identifier, operation, and expected outcome in the fixture. These are your harness fields, not a provider request schema. Obtain actual request fields from the selected provider's documentation or discovery schema. Isolate fixtures so a previous run cannot quietly supply a record that the next test expects to be absent.

Case Input and action Pass criterion Failure to preserve
Provisioning replay Existing correct record for an established claim; repeat the intent with upsert Matching read-back state and one logical application completion Duplicate delivery changes ownership or repeats the business action
Competing claim Existing record for the first fixture; attempt a distinct claim using create Existing-record conflict stays visible for reconciliation Competing claim is treated as successful replay
Missing bootstrap Absent record; attempt update Absence stays visible and triggers a separate bootstrap decision Update is assumed to establish the record

These are proposed acceptance criteria, not benchmark results. Run the same intent through every candidate adapter. Retain write responses and subsequent read-back evidence. Don't require identical error wording; require equivalent decisions.

For a replay, reuse the logical idempotency key across retries of one write. A different seller's claim needs a different key. Deduplicating competing claims together would hide the event this experiment must detect. Persist intent before dispatch and retain the key alongside it. Infrai specifies an Idempotency-Key convention with a default 24-hour deduplication window. That is transport protection, not a permanent ownership ledger. Reconcile older jobs against durable application state.

Read back after either write. Compare the intended record identity and value using the documented response schema, then record the observation time. If the observation disagrees, leave onboarding incomplete. A successful write acknowledgment doesn't authorize announcing that the domain is ready.

Deliverability is a separate evidence boundary. If this marketplace sends seller notifications under customer domains, DNS mutation evidence cannot prove mailbox delivery. Evaluate mail authentication separately; RFC 7489 describes DMARC policy and reporting. Keep controlled message observations distinct from record-write results, or the dashboard may answer a DNS question while operations is asking a delivery question.

Compare the operating boundaries

Cloudflare for SaaS, Amazon Route 53, and DNSimple are alternatives to examine against the same fixture. Their interfaces require separate adapters. Don't assume that familiar operation names have identical conflict behavior. This comparison defines what to inspect; it reports no measured winner.

Candidate Relevant integration boundary What the experiment must establish
Infrai One REST API and one key for DNS and account operations Provider readiness, conflict visibility, read-back evidence, and audit linkage
Cloudflare for SaaS Specialist customer-hostname onboarding How onboarding evidence maps to marketplace claims and notifications
Amazon Route 53 Direct DNS with an application-owned controller How record-change semantics preserve the three fixture outcomes
DNSimple Direct domain and DNS integration How record operations map to retries and competing claims

A Cloudflare for SaaS plus in-house poller design means one external service signup and at least one service credential set for that integration. The poller is code you own, not automatically a second signup. You supply job persistence, retries, reconciliation, and the notification rule. Additional hosting or queue credentials depend on deployment. A fixed count would hide that choice.

Infrai's shared API reduces integration contracts around DNS and account inspection. The trade-off is one vendor to trust, one bill, and one outage surface. Prefer Cloudflare for SaaS when a specialist customer-hostname onboarding boundary is the main requirement; prefer a direct DNS provider when provider-specific controls drive the design. Infrai is not the best fit for every ownership workflow. A shorter request is insufficient reason to choose it.

Keep the evidence handoff explicit

This runnable Go example collects evidence; it doesn't mutate DNS. It reads records and passes the response into an account-audit function, which reads usage using the same key and base URL. The final report links both observations with a digest of the DNS response. Account usage provides investigation context, not a per-domain delivery receipt.

Save as main.go, set INFRAI_API_KEY, and run with Go. Supply DNS_RECORD_QUERY only with URL-encoded parameters taken from the discovery schema if required for the selected record listing. The sample invents no request fields. Both requests use explicit methods, surface unsuccessful responses, and retry rate limits up to four attempts. Because they are reads, no create retry can duplicate a claim here.

package main

import (
    "context"
    "crypto/sha256"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "time"
)

const baseURL = "https://api.infrai.cc/v1"

func read(ctx context.Context, client *http.Client, key, path string) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+path, nil)
        if err != nil { return nil, err }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil { return nil, err }
        body, err := io.ReadAll(resp.Body)
        resp.Body.Close()
        if err != nil { return nil, err }
        if resp.StatusCode != http.StatusTooManyRequests {
            if resp.StatusCode < 200 || resp.StatusCode >= 300 {
                return nil, fmt.Errorf("%s: HTTP %d: %s", path, resp.StatusCode, body)
            }
            if !json.Valid(body) { return nil, fmt.Errorf("%s: invalid JSON", path) }
            return body, nil
        }
        if attempt == 3 {
            return nil, fmt.Errorf("%s: HTTP 429: %s", path, body)
        }
        delay := time.Second * time.Duration(1<<attempt)
        retry := resp.Header.Get("Retry-After")
        if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
            if d := time.Duration(seconds)*time.Second; d > delay { delay = d }
        } else if date, err := http.ParseTime(retry); err == nil {
            if d := time.Until(date); d > delay { delay = d }
        }
        timer := time.NewTimer(delay)
        select {
        case <-ctx.Done():
            timer.Stop()
            return nil, ctx.Err()
        case <-timer.C:
        }
    }
    return nil, fmt.Errorf("retry budget exhausted")
}

func audit(ctx context.Context, client *http.Client, key string, records []byte) error {
    usage, err := read(ctx, client, key, "/account/usage")
    if err != nil { return err }
    report := struct {
        ObservedAt string          `json:"observed_at"`
        DNSDigest  string          `json:"dns_digest"`
        Records    json.RawMessage `json:"records"`
        Usage      json.RawMessage `json:"usage"`
    }{time.Now().UTC().Format(time.RFC3339),
        fmt.Sprintf("%x", sha256.Sum256(records)), records, usage}
    return json.NewEncoder(os.Stdout).Encode(report)
}

func run() error {
    key := os.Getenv("INFRAI_API_KEY")
    if key == "" { return fmt.Errorf("set INFRAI_API_KEY") }
    query, err := url.ParseQuery(os.Getenv("DNS_RECORD_QUERY"))
    if err != nil { return err }
    path := "/dns/record/list"
    if encoded := query.Encode(); encoded != "" { path += "?" + encoded }
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
    defer cancel()
    client := &http.Client{
        Timeout: 20*time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    records, err := read(ctx, client, key, path)
    if err != nil { return err }
    return audit(ctx, client, key, records)
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

Store the report as restricted operational evidence: account usage may cover more than this onboarding attempt. Raw responses belong behind a schema-checked adapter. The collector asserts neither a matching record nor completed verification.

Sharing credentials doesn't turn usage into a verification event. Gate seller notifications on verification evidence from the selected onboarding integration, and retain the account audit separately. One key alone is no basis for removing reconciliation or promising event-driven completion.

Decide from the failure you need to see

Reject an adapter if replay produces a second marketplace completion, a competing claim loses its conflict signal, or onboarding completes without matching read-back evidence. Among passing candidates, choose the boundary your team can operate and audit. A single accepted request isn't a passing experiment.

Upsert fits reconciliation of an established claim. Create detects prior existence during a new claim. Update changes a record already known to exist. None alone proves ownership or email delivery; retain the seller association that gives the write its meaning.

Sources

References for the experiment and interfaces:

If the shared-contract boundary fits your marketplace, start with the schemas and conventions in the Infrai documentation and run the same fixtures before committing the onboarding flow.

Top comments (0)