A property company can own its mail domain while your platform controls the DNS account used for onboarding. Resolve that ownership boundary before accepting another domain: use the tenant table for admission, then reconcile it against complete zone inventories on a schedule. A provider-wide count cannot tell you which property company has exhausted its allowance.
TL;DR: count active domains and pending reservations in your own tenant table, enforce the quota and reserve capacity in one transaction, and reconcile against the zone list to catch out-of-band additions. For a Node.js backend pointing company mail at a provider with MX records, keep quota admission separate from permission to edit DNS. Customer-owned zones need the customer's authorized publication process; platform-owned zones need an explicit tenant mapping.
The practical trade-off is onboarding speed versus explainable ownership. An unfamiliar zone should trigger review before it changes a customer's capacity calculation. It should never trigger an automatic MX rewrite.
Why can't the live zone count enforce a tenant quota?
The DNS layer has no concept of your application's tenants. One account may hold several property companies' domains alongside the platform's operational zones, while a customer-owned zone may remain outside that account entirely. Replacing the tenant count with the length of a provider response therefore changes what you are measuring. It doesn't make the quota more accurate.
Ownership comes first.
Consider an illustrative portfolio, harbor-properties, with leasing.example and residents.example already active. Its application quota is three domains. Reserving repairs.example fills the last slot before any provider write starts. These are example policy values, not DNS service limits. Two requests that both read a count of two can both pass unless the count and reservation share transaction protection.
The ownership model also determines what reconciliation can prove. For a platform-owned zone, compare inventory within the platform's authorized account scope. For a customer-owned zone, track the domain's tenant association and the evidence available through the customer's approved access. An absence from the platform account is expected for some customer-owned zones; treating it as a missing zone would create false alarms and invite unnecessary migrations. Record the observation scope with the ownership decision rather than trying to infer either from a domain name.
Keep receiving-mail routing separate from sender authentication. MX records direct company mail to its receiving provider. DMARC alignment concerns outbound authentication, including rent reminders or OTP messages, and needs its own checks under RFC 7489. Neither a quota pass nor an MX change proves inbox delivery.
Step 1 Reserve capacity before touching DNS
Count active domains and unfinished reservations. Keep capacity occupied while a provider operation has an unresolved outcome; otherwise a retry can compete with a fresh request for a slot that was never safely released. Use a stable application operation identifier so repeated admission attempts find the same reservation.
The runnable Python reference below models the transaction a Node.js request handler must preserve. It uses the standard library and an in-memory SQLite database, so it makes no provider requests. Save it as admission.py and run it with Python 3.12 or newer. The transaction includes the count, decision event, and reservation; production database locking must protect that same boundary across all application workers.
import json import sqlite3 db = sqlite3.connect(":memory:", isolation_level=None) db.executescript(""" CREATE TABLE tenants ( tenant TEXT PRIMARY KEY, domain_limit INTEGER NOT NULL CHECK (domain_limit >= 0) ); CREATE TABLE domains ( operation_id TEXT PRIMARY KEY, tenant TEXT NOT NULL, domain TEXT NOT NULL UNIQUE, state TEXT NOT NULL CHECK (state IN ('active', 'reserved')) ); CREATE TABLE quota_events ( payload TEXT NOT NULL ); """) db.execute("INSERT INTO tenants VALUES (?, ?)", ("harbor-properties", 3)) db.executemany( "INSERT INTO domains VALUES (?, ?, ?, ?)", [ ("seed-1", "harbor-properties", "leasing.example", "active"), ("seed-2", "harbor-properties", "residents.example", "active"), ], ) def reserve(tenant, domain, operation_id, approved_limit=None): db.execute("BEGIN IMMEDIATE") try: existing = db.execute( "SELECT tenant, domain FROM domains WHERE operation_id = ?", (operation_id,), ).fetchone() if existing is not None: if existing != (tenant, domain): raise ValueError("Operation identifier reused for another request") db.commit() return {"allowed": True, "replayed": True} tenant_row = db.execute( "SELECT domain_limit FROM tenants WHERE tenant = ?", (tenant,) ).fetchone() if tenant_row is None: raise ValueError("Unknown tenant") base_limit = tenant_row[0] if approved_limit is not None and approved_limit < base_limit: raise ValueError("An override must not reduce the base limit") limit = base_limit if approved_limit is None else approved_limit occupied = db.execute( "SELECT COUNT(*) FROM domains WHERE tenant = ? " "AND state IN ('active', 'reserved')", (tenant,), ).fetchone()[0] allowed = occupied < limit event = { "tenant": tenant, "operation_id": operation_id, "occupied": occupied, "effective_limit": limit, "allowed": allowed, "override_used": allowed and occupied >= base_limit, } if allowed: db.execute( "INSERT INTO domains VALUES (?, ?, ?, ?)", (operation_id, tenant, domain, "reserved"), ) db.execute("INSERT INTO quota_events VALUES (?)", (json.dumps(event),)) db.commit() return event except Exception: db.rollback() raise first = reserve("harbor-properties", "repairs.example", "onboard-3") replay = reserve("harbor-properties", "repairs.example", "onboard-3") next_domain = reserve("harbor-properties", "annex.example", "onboard-4") assert first["allowed"] assert replay["replayed"] assert not next_domain["allowed"] print(json.dumps([first, replay, next_domain], indent=2)) The first request reserves the third slot. Its replay consumes no additional capacity. The next domain is denied. This executable checks local admission behavior; an in-memory demonstration does not establish concurrency behavior for a deployed Node.js service. Exercise the production transaction with two independent workers and one remaining slot before enabling enforcement.
The event fields are an internal application contract, not a vendor request schema. A worker can forward committed decisions to analytics so operators can see who is hitting the limit. Keep resident addresses, message contents, and OTP values out of these events. Capacity review does not need them.
An override should raise the effective limit to an approved value, rather than disable counting. In this example, approved_limit represents a value resolved by trusted server-side policy; never accept it directly from a tenant request. Store the approving operator, reason, and expiry separately. A property acquisition can justify additional domains while account administration catches up, but a permanent unexplained exception weakens every later review.
Step 2 Reconcile complete inventories within the ownership boundary
Scheduled reconciliation is what keeps the count honest over months. It catches zones added through an administrator console or another integration, then turns those observations into reviewed changes to the tenant inventory. Until ownership is established, an extra zone is an investigation item. It is not a domain to delete or an invitation to assign it to the next onboarding customer.
This second standalone program compares a complete, normalized platform-account snapshot with active application domains in that same scope. The owner_map is independent ownership evidence, not an inference from the listing. Customer-owned external zones belong in a separate observation scope. Save this as reconcile.py and run it with Python 3.
import json def reconcile(expected, observed, owner_map, complete): if not complete: raise ValueError("Defer corrections until the inventory is complete") extra = observed - expected return { "missing": sorted(expected - observed), "untracked_with_owner": [ {"domain": domain, "tenant": owner_map[domain]} for domain in sorted(extra) if domain in owner_map ], "unattributed": sorted( domain for domain in observed if domain not in owner_map ), } report = reconcile( expected={"leasing.example", "residents.example"}, observed={"leasing.example", "residents.example", "annex.example"}, owner_map={ "leasing.example": "harbor-properties", "residents.example": "harbor-properties", }, complete=True, ) assert report["unattributed"] == ["annex.example"] print(json.dumps(report, indent=2)) Here annex.example requires ownership review. After confirming attribution, update the ledger through an audited transaction and recalculate occupied capacity. If the corrected count exceeds the limit, block further ordinary admissions and offer the approved override path. Preserve existing mail while the discrepancy is resolved.
An incomplete listing is not an empty account.
The completeness flag is an adapter assertion, not proof supplied by this example. The real collector must establish that it has consumed the full documented inventory for the intended account and scope. Store snapshot time and collection status. Choose a schedule and a maximum acceptable age based on how much drift the business can tolerate; old or incomplete evidence should defer new admissions for review rather than cause deletions. Compare pending reservations separately, because they may legitimately precede a visible zone.
For the unified backend option compared below, this is a minimal live inventory read. Set INFRAI_API_KEY to your credential and INFRAI_BASE_URL to the documented HTTPS API base ending in /v1, then run the saved program with Python 3.12 or newer. It prints the actual JSON response without assuming a domain-list envelope. Map that response using the published schema before supplying normalized sets to reconciliation; one successful response alone does not establish collection completeness.
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.parse import urlsplit from urllib.request import Request, urlopen base = os.environ["INFRAI_BASE_URL"].rstrip("/") key = os.environ["INFRAI_API_KEY"] if urlsplit(base).scheme != "https" or urlsplit(base).path != "/v1": raise ValueError("Use the documented HTTPS API base ending in /v1") def delay_for(value, attempt): backoff = 2 ** attempt if value: try: return max(backoff, float(value)) except ValueError: try: deadline = parsedate_to_datetime(value) if deadline.tzinfo is None: deadline = deadline.replace(tzinfo=timezone.utc) seconds = (deadline - datetime.now(timezone.utc)).total_seconds() return max(backoff, seconds) except (ValueError, TypeError, OverflowError): pass return backoff def read_inventory(): for attempt in range(5): request = Request( base + "/dns/domain/list", headers={"Authorization": "Bearer " + key}, method="GET", ) try: with urlopen(request, timeout=30) as response: if response.status != 200: raise RuntimeError(f"Unexpected HTTP status {response.status}") return json.load(response) 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(delay_for(error.headers.get("Retry-After"), attempt)) raise RuntimeError("Retry budget exhausted") print(json.dumps(read_inventory(), indent=2)) This read does not provision a zone or publish MX records. Its five-attempt retry budget is an example client policy, not a service limit. Writes need their own idempotent request contract as well as the application reservation.
Step 3 Choose an integration without moving the ownership boundary
The useful comparison is who can authorize company MX changes and who maintains the tenant mapping. None of the choices below makes an application tenant quota emerge from a DNS account inventory. Retaining an established customer DNS administrator can be more valuable than standardizing every zone under your platform credentials.
| Option | Appropriate control boundary | Work the application still owns |
|---|---|---|
| Cloudflare DNS | A property company already manages its zone there and wants to retain that publication process. | Obtain authorized inventory access where needed, map domains to tenants, and reconcile within the correct account scope. |
| Amazon Route 53 | Platform-operated hosted zones fit the team's existing AWS account administration. | Keep tenant reservations and customer authorization separate from the hosted-zone inventory. |
| Google Cloud DNS | Managed zones fit the operator's Google Cloud project organization. | Preserve the application ownership ledger; a project boundary is not the tenant quota policy. |
Infrai provides a unified REST API with a single API key and a single bill: 295 routes across 20 modules. One key covers DNS onboarding, communications, and analytics, so adding a capability reuses the same integration contract. Plain HTTP calls require no SDK installation. Its public, self-describing discovery supplies request and response schemas, which helps build the inventory adapter without guessing fields. That breadth is useful for the combined workflow; a company retaining its own DNS administration may prefer an adapter to its existing provider instead. In either case, tenant attribution, transaction protection, and override approval remain application responsibilities.
Use each provider's published schema when implementing its collector. The examples deliberately accept application-owned inputs instead of inventing response fields or assuming that different zone-list APIs share pagination behavior.
Step 4 Roll out admission before enabling mail changes
Start with read-only reconciliation. Review unexplained differences, confirm the customer-owned versus platform-owned classification, and record the approval needed to publish the receiving provider's exact MX values. Then enable transactional reservations, decision events, and time-bounded overrides. Connect provisioning only after the admission outcome is durable.
For acceptance, run two simultaneous admissions with one slot left: exactly one should reserve capacity. Replay its operation identifier and confirm the count stays fixed. Add an illustrative unattributed zone to the collector fixture and confirm it enters review without being assigned or deleted. Supply an incomplete snapshot and confirm it cannot authorize corrections.
Finally, stage MX publication under the recorded owner's authority and check the resulting DNS state against the selected mail provider's instructions. Keep outbound authentication checks distinct. Offboarding needs the same discipline: removing a tenant association does not authorize deletion of a customer-owned zone, and an unresolved removal must not silently free capacity for another provisioning attempt.
Sources
References for receiving-mail routing, outbound authentication, and the three DNS control surfaces: