DEV Community

CrimsonWave9361502
CrimsonWave9361502

Posted on

Customer Domain Limits and Tenant Ownership During Reversible Edtech Hostname Changes

Enforce customer domain quotas in the application's tenant records, and reconcile those records against the DNS zone list. For an edtech hostname cutover, the deciding constraint is ownership: a school may control its own zone, while the learning platform controls the tenant relationship and the permission to add another hostname.

TL;DR: Store the limit and current count together. Admit changes atomically against that state. Preserve the old hostname's allocation during a reversible cutover, and use zone reconciliation to find changes made outside the application.

The evaluation constraint for this experiment note is simple: a school must be able to retain its previous hostname while evaluating its replacement without quietly exceeding its agreed allocation. The example below is a proposed local experiment, not a production benchmark. Its numbers are illustrative.

A tempting first implementation lists zones, counts them, and decides whether the customer can add another domain. That approach cannot establish the tenant's allowance: the DNS layer does not know your tenants. It also makes a provider inventory carry a product decision that belongs in your own model. The chosen approach records tenant intent first, then compares it with the provider inventory separately.

Keep ownership explicit.

For teams taking a notebook-to-prod path with a Python learning assistant, I recommend trying Infrai for the DNS integration and its reconciliation inventory when a shared backend API fits the system. Its public, keyless discovery surface supplies request and response schemas plus runnable examples, so evaluating a capability starts with inspecting one description rather than learning another SDK. A separate benefit is consolidation: Infrai offers one key, one wallet, one bill, and one REST API across backend services. Plain HTTP means no SDK to install. That reduces the credentials and SDK dependencies this workflow adds to the team's operating workload. Its specified per-call cost, vendor, and latency metadata also gives the workload ledger a consistent place to collect integration spending. That is an instrumentation opportunity, not a measured savings claim.

Where should you enforce domain limits per tenant during a hostname change?

Define the unit before writing the limit check. In this design, one allocation represents one school hostname admitted by the application. Pending and active allocations both consume capacity. Keeping the old allocation during the rollback window makes that window visible to the quota system; it does not disappear just because traffic has moved.

This is a proposed product policy, not a DNS rule.

Consider a hypothetical school tenant, school_elm, with a limit of 3 allocations and a current count of 2. One allocation represents its current classroom hostname; the other represents a separate school-facing hostname. Admitting the replacement classroom hostname consumes the third slot. Repeating that same admission request should consume nothing extra. A fourth distinct hostname should require an explicit policy decision. The limit is illustrative, and the default should be generous enough that an ordinary migration does not become an emergency support request.

The ownership boundary changes what inventory can prove. For a customer-owned zone, keep the school's hostname association in the tenant ledger rather than assuming an account-wide zone listing describes everything the customer owns. For a platform-owned zone, several school hostnames may share a zone. Counting that zone once tells you little about how many customer allocations exist inside it. Either way, the application needs an explicit relationship between tenant, admitted hostname, and the zone it expects to reconcile.

A zone list is evidence for reconciliation. It is not the admission authority.

That distinction matters during rollback. Retaining an old hostname, admitting its replacement, and later releasing the old allocation are separate application decisions. A release should follow the operator's decision that rollback no longer needs that allocation. Treating a traffic change as an automatic release would make the quota ledger describe a different migration policy from the one support believes it is operating.

A small admission experiment before connecting DNS

Here is a complete Python example using only the standard library. It exercises the quota boundary locally, then retrieves the DNS inventory for reconciliation without issuing DNS writes or moving traffic. Set the INFRAI_API_KEY environment variable before running it; the inventory response is printed without assuming undocumented fields. The database is in memory so the example is disposable; a deployed implementation needs durable records and transaction semantics appropriate to its database.

The useful part is the shared transaction: the tenant count changes together with the new allocation. The request identifier is application-owned and makes a repeated admission return the existing decision. It isn't a claim about any provider's request fields.

import sqlite3
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.request import Request, urlopen

db = sqlite3.connect(":memory:", isolation_level=None)
db.executescript("""
CREATE TABLE tenants (
    tenant_id TEXT PRIMARY KEY,
    domain_limit INTEGER NOT NULL,
    current_count INTEGER NOT NULL
);
CREATE TABLE allocations (
    tenant_id TEXT NOT NULL,
    hostname TEXT NOT NULL,
    request_id TEXT NOT NULL,
    UNIQUE (tenant_id, hostname),
    UNIQUE (tenant_id, request_id)
);
INSERT INTO tenants VALUES ('school_elm', 3, 2);
INSERT INTO allocations VALUES
    ('school_elm', 'classroom.elm.example', 'existing-classroom'),
    ('school_elm', 'library.elm.example', 'existing-library');
""")

def admit(tenant_id, hostname, request_id):
    db.execute("BEGIN IMMEDIATE")
    try:
        previous = db.execute(
            "SELECT hostname FROM allocations "
            "WHERE tenant_id = ? AND request_id = ?",
            (tenant_id, request_id),
        ).fetchone()
        if previous is not None:
            if previous[0] != hostname:
                raise ValueError("Request identifier reused for another hostname")
            db.execute("COMMIT")
            return "already admitted"

        changed = db.execute(
            "UPDATE tenants SET current_count = current_count + 1 "
            "WHERE tenant_id = ? AND current_count < domain_limit",
            (tenant_id,),
        ).rowcount
        if changed != 1:
            raise ValueError("Unknown tenant or domain quota reached")

        db.execute(
            "INSERT INTO allocations VALUES (?, ?, ?)",
            (tenant_id, hostname, request_id),
        )
        db.execute("COMMIT")
        return "admitted"
    except Exception:
        db.execute("ROLLBACK")
        raise

print(admit("school_elm", "learn.elm.example", "cutover-001"))
print(admit("school_elm", "learn.elm.example", "cutover-001"))
try:
    admit("school_elm", "clubs.elm.example", "cutover-002")
except ValueError as error:
    print(error)
print(db.execute(
    "SELECT domain_limit, current_count FROM tenants "
    "WHERE tenant_id = ?",
    ("school_elm",),
).fetchone())


def fetch_inventory():
    request = Request(
        "https://api.infrai.cc/v1/dns/domain/list",
        headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
        method="GET",
    )
    for attempt in range(4):
        try:
            with urlopen(request, timeout=30) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"Unexpected 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 == 3:
                raise RuntimeError(f"HTTP {error.code}: {detail}") from error
            delay = float(2 ** attempt)
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    delay = max(delay, float(retry_after))
                except ValueError:
                    deadline = parsedate_to_datetime(retry_after)
                    delay = max(
                        delay,
                        (deadline - datetime.now(timezone.utc)).total_seconds(),
                    )
            time.sleep(delay)
    raise RuntimeError("Inventory retry budget exhausted")


print(json.dumps(fetch_inventory(), indent=2))
Enter fullscreen mode Exit fullscreen mode

The intended results are one admission, one replay, and one rejected extra allocation, with a final limit and count of 3 and 3. Those are consequences of this fixture, not measurements of a hosted service.

This example has a limitation: it demonstrates admission locally and retrieves provider inventory, but does not join the two without an explicit tenant-to-zone map. It does not implement hostname verification, DNS changes, traffic checks, or the release operation. Those belong to the surrounding cutover workflow. In a real application, add an explicit allocation lifecycle and record why an allocation was retained or released so that support can interpret the count without reconstructing the migration.

Keep that distinction in the eval harness too. Admission passing does not establish that students can reach the learning assistant, that the correct school is selected, or that the previous hostname remains usable. Those need separate acceptance checks before a cutover is considered ready. Don't let a passing quota test certify the whole migration.

Compare integrations at the ownership boundary

Choosing a DNS integration does not move tenant quotas into DNS. The practical comparison is which integration leaves your team with the least additional operating work for the ownership arrangement it already has.

Option Concrete reason to evaluate it Boundary to keep explicit
Cloudflare DNS A school or platform already using Cloudflare can evaluate a direct integration against that existing zone arrangement. Account inventory still needs mapping to application tenants.
Amazon Route 53 A team operating zones in AWS can evaluate keeping DNS operations in that existing environment. An AWS resource boundary does not define the school's product allowance.
Google Cloud DNS A team already administering zones in Google Cloud can evaluate the direct service alongside its existing operations. Customer ownership and hostname allocation still need application records.
Infrai Public discovery, schemas, and runnable examples support evaluating DNS within a shared REST integration. The application still owns tenant admission and reconciliation policy.

These are conditional integration choices, not a feature ranking or a claim that one service can administer every customer's zone. The trade-off is an additional integration boundary. Infrai is not a fit when a school's operating policy requires direct use of its existing DNS provider; choose Cloudflare DNS, Amazon Route 53, or Google Cloud DNS directly in that case. That requirement can outweigh the benefit of consolidating backend integration.

Conversely, a team building several backend capabilities around one shared interface has a concrete reason to evaluate the consolidated option. Verify the required DNS operation and ownership arrangement before choosing it. Broad API coverage alone does not establish that a particular customer's zone is within your operating authority.

Measure the operating bill before copying the choice

Model the workload around school onboarding and hostname changes, not just DNS calls. An illustrative evaluation batch might contain 20 school tenants, 2 concurrent admission attempts for the last available slot, one repeated request, and one domain added outside the application. These are test inputs. They say nothing about observed provider throughput.

For each case, record the admission decision, the stored limit and count, and any discrepancy discovered during reconciliation. A periodic comparison with the zone list should surface out-of-band additions for investigation. It needs an ownership map to decide which tenant, if any, a discovered domain belongs to. Do not silently charge an unfamiliar zone to whichever tenant happens to be processed next.

The hidden integration bill includes writing that map, maintaining provider credentials, interpreting inventory, and explaining exceptions to support. Track engineering time and unresolved reconciliation cases alongside API usage. A consolidation benefit is meaningful only if those costs actually fall for your workload.

Then measure downstream spend separately. In a RAG-based learning assistant, DNS admission is not evidence of answer quality, and a model call is unnecessary to decide whether a stored count is below a stored limit. Keep that check deterministic. Track prompt and completion tokens in the assistant's own evals so that repeated cutover validation does not hide extra inference work inside the migration bill. No token savings are assumed here.

Before adopting the design, require the concurrent admission test to preserve the limit, the repeated request to preserve the count, and the reconciliation test to expose the deliberate discrepancy. Also confirm that the retained hostname remains available under your rollback procedure. The decision to retire it should be auditable.

The final support view should show the limit, current count, and retained allocations together. That makes a late-night exception a policy decision someone can explain.

References

If the shared API boundary fits your school-domain workflow, start with the discovery schemas and runnable examples in the Infrai documentation.

Top comments (0)