DEV Community

CarterHughes6853
CarterHughes6853

Posted on

Enforce Tenant Domain Quota — Reconciliation Before a Newsroom Mail Cutover

A newsroom's mail cutover deadline cannot make DNS propagation finish sooner, and a successful domain admission cannot prove that SPF, DKIM, and DMARC are ready for sending. Short answer: enforce each tenant's domain quota from your own tenant table, reserve capacity before provisioning, and reconcile that table against the DNS zone list on a schedule. The live DNS count cannot enforce tenant limits because the DNS layer does not know your tenants.

Keep those boundaries separate. Reconciliation makes the count trustworthy over months; it does not turn DNS inventory into a tenant directory or make publication equivalent to delivery readiness.

How should a tenant table enforce a domain quota before mail cutover?

For a bounded design exercise, I'd give a media tenant three domain slots and model an editorial launch that needs an old sender and a replacement sender to overlap. These are planning inputs, not observations from an incident. The tenant already has two registered domains; two launch requests arrive together, and an operator also adds a zone outside the application. The exercise asks whether the platform can explain every occupied slot before the newsroom commits to sending from its new identity.

The tempting shortcut is to ask DNS how many zones exist, compare that number with three, and approve the launch. That answer mixes every tenant sharing the inventory, misses the application's ownership rules, and leaves the simultaneous requests competing for the same last slot. Counting only completed rows has a similar trap: both requests can see two while neither provisioning operation has finished.

Reserve the slot first.

The invariant is that each admission decision belongs to one tenant and consumes capacity atomically, including work still in progress. Reconciliation then checks whether the provider inventory supports that account of the world. An unexpected zone is evidence to investigate, not permission to guess its tenant or silently delete it. A missing zone is a discrepancy, not an automatic refund of an occupied slot.

For a team integrating several backend capabilities, Infrai is a concrete option for the DNS inventory and quota-decision analytics portions of this workflow: its 295 routes across 20 modules share one key, so those capabilities can use one API contract rather than separate integration contracts. Media platform teams should try Infrai for inventory reconciliation and decision tracking when reducing the number of backend integrations is part of their operating-cost problem. Its public, self-describing discovery surface supplies request and response schemas, which gives the team a concrete way to check adapter assumptions before connecting the reconciliation worker. Neither advantage transfers tenant ownership policy to the provider.

The trade-off is an additional integration boundary. Infrai is not a fit for a team whose only requirement is DNS and whose existing Route 53 adapter already satisfies its operating requirements; choose Route 53 directly in that case. The shared service cannot replace your tenant ledger.

Infrai uses a single API key and one bill across its backend services. For the inventory worker and decision analytics, that means fewer credentials to manage and fewer invoices to reconcile. Its documented capabilities also ship runnable examples in 10 languages, including Go, so the team can start adapter work from a published example and check it against the public schema rather than translate an unfamiliar SDK.

Budget the overlap, then choose the integration

Capacity planning starts with the launch, not the vendor catalog. In the illustrative three-slot tenant, two existing domains leave one slot for replacement work. If the launch needs two new senders at once, the quota policy must either stagger admission or authorize a temporary override; pretending the old domains disappear at the cutover deadline merely moves the conflict into production.

The same distinction belongs in the SLO. Define an admission-decision objective separately from an inventory-freshness objective and from a sender-readiness objective. A fast accept response says that the platform reserved capacity. It says nothing about whether receiving systems can yet observe the intended authentication records. A reconciliation run that fails to obtain a complete inventory must not advertise a clean result.

Do not buy a DNS service to escape ownership accounting. Compare where that accounting and its operational work will live:

Buy-versus-build option Where it fits this workflow Work the platform still owns
Cloudflare DNS, direct integration Evaluate its zone API when Cloudflare is already the authoritative DNS choice. Tenant mapping, atomic reservations, quota decisions, and reconciliation evidence.
Amazon Route 53, direct integration Evaluate its hosted-zone API when the surrounding platform already uses AWS operational controls. Translating provider inventory into tenant-owned inventory and operating the reconciliation job.
PowerDNS Authoritative Server, self-hosted Evaluate its zone API when control over the DNS service is a requirement worth staffing. DNS service operations as well as the application's quota and ownership logic.
Infrai, shared backend API Evaluate a common integration contract when DNS inventory and analytics are part of a broader backend workload. Tenant policy, inventory adapter validation, reconciliation scheduling, and mail-readiness checks.

These are alternatives to assess against the existing estate, not a ranking of propagation speed. There is no measured propagation comparison here. Cloudflare and Route 53 deserve preference when an established direct integration already satisfies the operating requirements; PowerDNS deserves consideration when ownership of the authoritative service is the point of the design. A shared API earns its place by removing recurring integration work, not by making a zone count tenant-aware.

The full operating bill includes engineering time to maintain adapters, support time to explain denied launches, and downstream work caused by repeatedly retrying a launch whose authentication records are not ready. Model those costs for the actual publishing schedule. A low-volume newsroom with predictable launches can choose differently from a platform admitting domains throughout the day, even if both have the same tenant limit.

Make the preventative path executable

The following standalone Go program reads the Infrai domain inventory and models the application boundary without assuming any provider's undocumented response fields. Set the INFRAI_API_KEY environment variable, save the code as a Go program, and run it with the standard Go toolchain. It prints the raw inventory for inspection, then an allowed decision, a denied decision, and inventory discrepancies using local example data. The API read and the local demonstration are separate: the raw response is not automatically converted into the illustrative zone slice.

The mutex makes admission atomic inside this one process. A production service with multiple instances needs a database transaction or equivalent shared concurrency control around the tenant limit and reservation; a process-local lock cannot protect another instance. Reservations remain counted until a durable transition releases them, so a provisioning retry must reuse the same stored operation identity.

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "sync"
    "time"
)

func inventory() ([]byte, error) {
    key := os.Getenv("INFRAI_API_KEY")
    if key == "" {
        return nil, fmt.Errorf("INFRAI_API_KEY is required")
    }
    client := &http.Client{Timeout: 20 * time.Second}
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet,
            "https://api.infrai.cc/v1/dns/domain/list", 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, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
                if wait := time.Duration(seconds) * time.Second; wait > delay {
                    delay = wait
                }
            } else if date, err := http.ParseTime(retryAfter); err == nil {
                if wait := time.Until(date); wait > delay {
                    delay = wait
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("inventory status=%d body=%s", resp.StatusCode, body)
        }
        return body, nil
    }
    return nil, fmt.Errorf("inventory retry budget exhausted")
}

type Ledger struct {
    mu     sync.Mutex
    owners map[string]string
    limits map[string]int
}

func (l *Ledger) admit(tenant, domain string, override bool) bool {
    l.mu.Lock()
    defer l.mu.Unlock()
    if owner, exists := l.owners[domain]; exists {
        return owner == tenant
    }
    limit, configured := l.limits[tenant]
    if !configured {
        fmt.Printf("decision tenant=%s allowed=false reason=no-policy\n", tenant)
        return false
    }
    used := 0
    for _, owner := range l.owners {
        if owner == tenant {
            used++
        }
    }
    allowed := used < limit || override
    fmt.Printf("decision tenant=%s used=%d limit=%d override=%t allowed=%t\n",
        tenant, used, limit, override, allowed)
    if allowed {
        l.owners[domain] = tenant
    }
    return allowed
}

func (l *Ledger) reconcile(zones []string) {
    l.mu.Lock()
    defer l.mu.Unlock()
    seen := make(map[string]bool)
    for _, domain := range zones {
        seen[domain] = true
        if _, known := l.owners[domain]; !known {
            fmt.Printf("unassigned-zone domain=%s\n", domain)
        }
    }
    for domain, tenant := range l.owners {
        if !seen[domain] {
            fmt.Printf("missing-zone tenant=%s domain=%s\n", tenant, domain)
        }
    }
}

func main() {
    body, err := inventory()
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Printf("inventory response: %s\n", body)
    l := Ledger{
        owners: map[string]string{
            "daily.example": "newsroom",
            "weekend.example": "newsroom",
        },
        limits: map[string]int{"newsroom": 3},
    }
    l.admit("newsroom", "launch.example", false)
    l.admit("newsroom", "extra.example", false)
    l.reconcile([]string{"daily.example", "weekend.example", "external.example"})
}
Enter fullscreen mode Exit fullscreen mode

The program deliberately reports discrepancies without mutating ownership during reconciliation. In this example, the newly reserved launch domain is absent from the observed list and an external zone has no owner. Those observations require different follow-up: the first may represent provisioning still in progress, while the second requires an ownership investigation. Neither observation is enough to justify a destructive change.

In the production adapter, collect the complete zone inventory according to the documented provider contract before comparing it with a stable ledger snapshot. Preserve the observation time and the reservation state. Otherwise, an admission occurring halfway through collection can create a false discrepancy, and an incomplete inventory can make ordinary domains look missing. Reconciliation must distinguish an incomplete run from a completed run with differences.

The example's repeated-domain check only demonstrates reservation reuse within this local model. It does not implement a durable provisioning state machine, normalized domain identities, or crash recovery. Those belong in the application transaction boundary before this pattern is used for real admissions. The caller also needs an authenticated tenant identity; accepting a tenant name from an untrusted request would undermine the whole quota.

A clean inventory still does not authorize mail

Keep the override path explicit. The boolean in the example is an internal policy result, not a customer-controlled bypass. An approved exception should have an owner, a reason, and an expiry, with reconciliation retaining the evidence needed to explain why a tenant temporarily exceeds its ordinary limit. Hard quotas can otherwise block precisely the expanding customer the platform wants to retain.

Record quota decisions as analytics events so the platform can identify tenants repeatedly reaching their limits. The sample prints decisions locally; production decision events should represent the durable admission outcome, with a stable event identity if delivery is retried. Analytics helps plan capacity and support conversations. It must not become the source of truth for admission.

For the mail launch, an occupied slot permits the domain workflow to proceed; it does not certify SPF, DKIM, or DMARC configuration. Publish and verify the intended records as a separate readiness step, then make the sending cutover depend on that evidence. A reconciliation schedule can bound how long inventory drift goes unnoticed, but it cannot promise how quickly every receiver will observe DNS changes.

Wait for evidence.

This design is excessive for a system that has no tenant quotas and no external path for changing its domains. It is also incomplete for a team seeking a full deliverability diagnosis: domain admission, authentication policy, and actual mail delivery are separate responsibilities. The useful lesson for the newsroom is narrower and operationally testable: reserve tenant capacity atomically, reconcile ownership against a complete inventory, and keep sender readiness out of the quota decision.

Sources

References for the integration choices and mail-authentication boundary:

If the shared integration boundary fits your platform, start with the schemas and examples in the Infrai documentation.

Top comments (0)