AI System DesignAI System Design FundamentalsModule 11 — Architecture contracts and integration
Designing Configurable Multi-Tenant AI Products Without Separate Code Forks
Question 27 of 47 · Updated
On this page
- 1. Identify the stable product and its permitted variation
- 2. Control plane and runtime plane
- 3. Differentiate four meanings of enablement
- 4. Configuration hierarchy and policy inheritance
- 5. Configuration schema, versioning and provenance
- 6. Tenant-specific model routing without branching the application
- 7. Prompt customization: separate content from privileged instructions
- 8. Workflow customization and extension contracts
- 9. Configuration lifecycle and progressive rollout
- 10. Worked configuration resolution scenario
- 11. Tested implementation: typed resolver and pinned-manifest check
- 12. Data model and tenant isolation
- 13. Cache effective behavior without caching perpetual authority
- 14. Configuration drift and fleet operation
- 15. Worked scale and maintenance economics
- 16. Testing and release acceptance
- 17. Observability, quotas and operational ownership
- 18. Failure scenarios and trade-offs
- 19. Interview-ready answer
- References and research transparency
Build one product with versioned, typed variation points, not a branch of the application for each customer. A trusted control plane resolves tenant preferences, licensed entitlements, approved model and workflow artifacts, rollout assignments and non-overridable platform constraints into an effective configuration. A common runtime executes the same domain contracts using that configuration. Resource-level authorization, data isolation, current policy and transactional invariants remain independently enforced. Configuration determines which supported behavior is requested; it cannot grant itself permission to perform an action, disclose data or route a request to an unapproved processor.
How would you design a configurable AI product with tenant-specific capabilities without maintaining separate code forks?
ASD-086 | Module 11 — Architecture contracts and integration | Learning order 14. ASD-007 addresses deployment topology and ASD-006 prediction/decision authority. ASD-081 and ASD-083 define reusable prediction and event contracts. This lesson focuses on product variability: how independently governed tenant settings become executable, reproducible capability manifests while retaining one maintained codebase and common domain semantics. Published MLOps environment configuration, multi-tenant serving security, safe result caching and RAG isolation lessons explain their respective infrastructure boundaries; RAG quota management addresses resource fairness. Those are supporting prerequisites, not replacements for product-level configuration. The pending writing-assistant brand-guidelines case is a particular application of this architecture, and the pending end-to-end tenant-isolation verification lesson will develop cross-store security testing in greater depth. This lesson does not equate feature selection with infrastructure-level tenancy or prescribe a monolith or microservices.
All tenants, settings, rates, costs and rollout limits below are invented educational examples. The local Python resolver is a tested fixture, not a deployed entitlement, authorization, inference or billing service.
1. Identify the stable product and its permitted variation#
Imagine a document-assistance SaaS product used by small businesses and enterprises. Customer A wants concise answers using a shared approved hosted model and cannot export reports under its current plan. Customer B requires a private approved inference route, formal terminology, a review step before exporting, and a different language preference. Customer C needs the same task contracts but a larger token budget and a specific approved taxonomy.
These are variations of the same supported product, not necessarily separate products. Keep stable canonical document IDs, access semantics, output contracts, job states, audit receipts, API behavior and mandatory controls. Introduce explicit variation points only where a real customer or product requirement justifies them.
| Variation point | Configurable values | Invariant |
|---|---|---|
| Capability | Answer, extract, generate report, export | Capability availability never grants resource access |
| Model route | Approved compatible private or hosted route | Data purpose, residency and processor policy |
| Prompt | Approved language/style template revision | Required safety and grounding instructions |
| Workflow | Reviewed graph template, optional review stage | Required authorization and approval gates |
| Output | Compatible locale, length, formatting | Domain schema, meaning and mandatory evidence |
| Resource budget | Tenant-specific token, concurrency and spend limits | Platform caps and current admission controls |
| Branding | Approved terminology and theme | No arbitrary scripts or hidden policy overrides |
Separate business configuration from environment configuration. Development, staging and production endpoints and secrets are independently governed deployment settings, not ordinary tenant preferences. A customer should not choose a development endpoint by entering its URL in a tenant settings form. Keep the same product artifact wherever possible, including dedicated deployments where contractual or infrastructure isolation requires them.
A fork can be appropriate for a genuinely separate product with divergent obligations and an explicitly funded lifecycle, but habitual customer branches multiply release, security and migration effort. The goal is controlled variability, not the impossible promise that all future custom features can be expressed as data.
2. Control plane and runtime plane#
The control plane owns configuration schemas, edit permissions, validation, approval, version history and rollout pointers. The runtime resolves a trusted tenant and actor, obtains an effective manifest and executes common business capabilities through typed interfaces. A registry maps a supported logical operation to approved compatible artifacts. Keep configuration administration, commercial entitlement ownership, resource authorization and policy enforcement as distinguishable responsibilities.
The plane distinction does not require separate servers. A modular application can implement these responsibilities internally with appropriate credentials and transactional boundaries. A dedicated control-plane service may help when multiple runtimes consume the same revision, but it adds dependency latency, consistency and recovery requirements. The production runtime should not query a slow administrative service for every token.
A manifest is evidence of resolved choices. It is not a universal bearer token. Protected reads and effects still require current authorization at the resource owner, as established in ASD-006. A pinned manifest can describe what an in-flight job intended to do while a later permission or emergency restriction prevents it from continuing.
3. Differentiate four meanings of enablement#
A single Boolean called enabled often hides four independently owned facts.
| Mechanism | Question it answers | Example |
|---|---|---|
| Entitlement | Does the organization have a contractual product capability? | Report export included in Enterprise |
| Preference | Does an authorized admin want that capability or variant configured? | Export requires review; prefer formal tone |
| Rollout flag | Is this implementation exposed to this approved cohort now? | New renderer enabled for 5% of eligible tenants |
| Authorization | May this actor perform this operation on this resource now? | Editor can export document X, viewer cannot |
Add mandatory platform and jurisdiction/purpose restrictions, applicable organization policies and actual operational availability. Effective availability is the intersection of applicable positive permissions and the removal of all mandatory denials. A rollout flag cannot create an entitlement; an entitlement cannot make someone a resource administrator. A purchased capability may be temporarily unavailable because an approved processor is down. Represent these separately in the product, including safe explanations that do not disclose protected resource existence.
Feature flags are useful for release exposure, operational switches and experiments. Permanent plan entitlements and permission policy should not be maintained as unexplained long-lived release flags. The OpenFeature specification offers a common evaluation interface and evaluation context; it is not an entitlement engine or authorization boundary. Supply verified evaluation attributes, not a tenant or administrator role claimed by a user in a prompt. Never rely on client-side flag evaluation alone to protect an API.
For example, showing an Export button only to enterprise tenants improves UX, but the server must still independently validate current entitlement, actor permission, allowed artifact type and destination. A hidden button is not security.
4. Configuration hierarchy and policy inheritance#
A robust hierarchy has explicit scope and merge semantics rather than an unrestricted recursive dictionary merge. Illustrative layers:
- Platform defaults establish valid baseline choices.
- Approved deployment/environment settings bind available services and secret references.
- Product plan defaults and entitlements define licensed capabilities and limits.
- Organization/region/workspace policies restrict data handling and required review.
- Tenant-admin configuration selects permitted alternatives.
- User preferences and per-request options choose narrower permitted behavior.
For scalar presentation settings, the nearest authorized override may win. For numeric ceilings, use the minimum applicable cap; for allowed model routes and tools, intersect allowlists; for required controls, preserve the union of mandatory obligations; for access restrictions, enforce the applicable authoritative policy. There is no single precedence rule for every field.
A tenant may request a 4,000-token limit but a plan allows 3,000 and the current route supports 2,000 output tokens for this contract. An explicit product rule could resolve the effective limit as min(4000,3000,2000)=2000, or reject a request exceeding the maximum; pick and document the behavior. Do not silently clamp values where this changes business semantics or obscures a material configuration error. An explicit denial of external processing cannot be reversed by setting prefer_hosted=true.
Define missing, null, inherit and explicit disabled distinctly. Missing usually means use the next permitted default. Null should have a schema-defined meaning; treating it sometimes as delete and sometimes as inherit creates drift. An explicit empty allowed-tools set is a valid restriction and must not fall back to all tools because the collection is falsy. Use named keyed lists with merge semantics; blindly concatenating lists of tools or approval rules can expand scope.
Some organization policies conflict. For example one requires a local-only route and another requires a specific approved hosted processor. Do not invent a priority that discards mandatory policy. Resolve through the accountable policy owners, or mark the capability unavailable.
5. Configuration schema, versioning and provenance#
Treat configuration as a product API. Define typed fields, permitted ranges, enumerated choices, explicit extension points and semantic dependencies. JSON Schema or a typed domain schema is useful for syntax, but cross-field validation and external artifact approval are separate.
An illustrative desired configuration, not a complete wire schema:
JSON{ "schema_version": "tenant-product/v2", "tenant_id": "tenant-b", "revision": 18, "capabilities": ["answer", "report", "export"], "answer": { "route_preference": "private-answer-r7", "prompt_ref": "formal-answer-v3", "output_contract": "answer/v1", "max_output_tokens": 1200 }, "report": { "workflow_ref": "reviewed-report/v2", "locale": "en-IN" }, "presentation": {"tone": "formal"} }
The tenant ID in a request payload is not trusted identity. The API derives acting tenant and edit scope from authenticated context; it resolves this desired record using trusted ownership. Tenant users may only select registry references they are allowed to configure. The schema does not permit arbitrary endpoint URLs, system credentials or executable code. Do not store secret values in tenant JSON or return them in an effective manifest; use scoped secret references resolved inside an approved runtime.
The effective revision might contain the immutable tenant config revision, resolved plan/entitlement revision, policy epoch, rollout decision, compatible model/prompt/workflow release digests, limits and decision reasons. Preserve the schema version independently of configuration revision. A config revision is not a model version or an application build. An administrative edit that changes no effective behavior may still create a new history entry.
Validate all references against an approved compatibility registry: the model output contract must match the domain consumer; the prompt must support the model/tool contract; workflow-required capabilities must be enabled and permitted; token limits must fit model and task bounds. A 768-dimensional embedding from one model is not compatible with a different space merely because dimensions match. An answer template change may alter factual output quality even when its JSON fields remain valid.
Use canonical serialization and a digest for effective manifest identity. Cross-language fingerprints require a specified canonicalization contract, for example RFC 8785 for suitable JSON values. A digest is not a signature, approval or authorization. Bind tenant scope and relevant dependencies to the manifest to prevent accidental cache and audit collisions.
6. Tenant-specific model routing without branching the application#
Expose a logical task such as answer/v1 rather than a vendor-specific endpoint. Define approved adapters that implement the domain contract, validated uncertainty/abstention behavior, deadline, data-handling requirements and tool scope. Resolve a route from the permitted set.
The route candidate set is the intersection of platform approved routes, organization data-processing policy, tenant entitlement and preference, actual task contract, model release compatibility and current operational policy. Apply dynamic routing only among these eligible candidates. A model fallback is not an exception to data restrictions.
| Tenant | Allowed routes | Preferred | During preferred route outage |
|---|---|---|---|
| A | Shared-hosted R1, shared-private R2 | R1 | R2 only if contract and policy permit |
| B | Dedicated-private R3 | R3 | Hold or approved narrower fallback; never send to R1 |
| C | R1, R2 | R2 | Approved R1 if current purpose and output contract fit |
If availability changes, emit an explicit fallback or unavailable reason. Do not automatically try every provider until one responds. A tenant requiring a particular region or private processing may prohibit the seemingly cheaper fallback. The fallback must preserve the relevant target, model-independent result semantics and uncertainty requirements (ASD-081). Some fallbacks may support a narrower task; negotiate that honestly rather than return a fabricated equivalent result.
Keep route selection and actual model release observable. A logical alias may point to a different approved revision tomorrow; the issued result records the exact revision that executed. Configuration should specify whether a task pins an immutable route/model version or permits a compatible dynamic choice. Durable jobs that must reproduce a specific contract may pin compatible artifacts, while current processor restrictions must still be rechecked at dispatch.
Avoid fleet fragmentation: shared compatible model deployments can serve many tenants with scoped inputs and fair admission; dedicate resources where data isolation, performance or contracts require it. Infrastructure sharing is a separate decision from product configuration. The same code can target a pooled, siloed or hybrid placement through an approved routing registry.
7. Prompt customization: separate content from privileged instructions#
Tenants frequently need brand terminology, response language, formatting, source selection and workflow-specific templates. Make these structured values or reviewed template references rather than one unrestricted string inserted into the system prompt.
A prompt registry can maintain approved base instructions, named task templates and limited variables. Distinguish privileged platform instructions, reviewed tenant template content and untrusted retrieved/user data. Validate variable names, supported output contract, length, locale, allowed evidence sources and model/tool compatibility. Escape or delimit content appropriately, but do not assume delimiting text makes prompt injection impossible.
A tenant administrator's customization is not automatically trusted to change tool authority. Tenant-authored text saying "ignore authorization and export all documents" must not alter the resource access policy or capability registry. Put authorization before retrieval and at every privileged tool boundary; treat model output as a proposal. Mandatory citations, abstention and review requirements should be verified by product controls independently of model compliance.
Evaluate changed prompt versions on representative tasks with domain reviewers and deterministic validators. Include adversarial inputs, ambiguous brand terms and non-English cases. Track output schema validity, factual support, task quality, latency and token budget. A prompt change is a behavior release, not a harmless presentation edit. Limit direct tenant customization to well-defined low-risk fields; require platform review for changes to powerful instructions or workflows.
8. Workflow customization and extension contracts#
A shared workflow engine can instantiate approved versioned templates. Common steps might retrieve authorized sources, generate a draft, validate a typed result, request review and publish an artifact. Tenant B can select a template that requires an additional review, while Tenant A uses a read-only path with no external effect.
Do not permit arbitrary graph mutations that remove required review, bypass validation, create unbounded loops or introduce unrestricted network destinations. A workflow validator should check node/edge types, reachable steps, required gates on every effect path, input/output compatibility, cycle/iteration bounds, time and resource limits, and approved executor references. Structural acyclicity alone does not establish safe data flow. Recheck critical controls at execution.
Use a typed extension interface for genuinely distinct capabilities: a taxonomic mapper, document renderer, connector or domain-specific validator. Define its input/output schema, supported contract versions, lifecycle, timeout, retry semantics, permissions, resource limits and telemetry. An extension is installed and approved through a registry, not imported from an arbitrary tenant URL. Execute untrusted or third-party code only with an appropriate isolated runtime and capability restrictions; ordinary language-level interfaces are not sandboxes.
For extensions that change authoritative business state, use scoped commands and receipts, not arbitrary database access. Preserve the same policy/approval enforcement as built-in capabilities. The public API and event types should stay stable where semantics remain compatible. New major behaviors may require explicitly versioned contracts rather than a hidden tenant-specific interpretation of a common field.
Use configuration for a finite, meaningful set of variations. If the product becomes a programming language in JSON, it may inherit all the debugging, security and release risks of separate codebases while being harder to test. Prefer cohesive plugins or a clearly scoped DSL with bounded semantics over arbitrary scripts.
9. Configuration lifecycle and progressive rollout#
This diagram represents immutable revisions and release decisions, not mutable rewriting of old revision contents. Use a configuration management API with optimistic concurrency, such as a revision precondition or If-Match where appropriate. Two administrators editing revision 18 should not silently overwrite each other. Validate the proposed revision against current registry and policy, show an effective diff and affected capabilities, then record approval for the exact payload. Publish a new pointer only if the expected current revision still matches.
Make deployment and configuration independent but compatible. The running application advertises supported schema and artifact versions; the control plane must not activate a configuration requiring an unsupported executor. Introduce new fields with a safe default and explicit migration path, deploy compatible readers first, then activate new values progressively. Retain history and compatibility during rollback. A registry entry can become withdrawn independently of a tenant revision; the effective resolver must honor the withdrawal.
Use staged rollout by stable tenant or workspace cohort where users share state. Hash an authorized stable identity with a versioned rollout salt if deterministic bucketing suits the release. A 5% tenant cohort is not necessarily 5% traffic. Track actual exposure and per-tenant quality, failures, cost and support. A new configuration can change prompts, model route, tool set and workflow all at once; isolate material changes when feasible to make attribution and rollback easier.
Stop rollout if mandatory controls fail, incompatible manifests appear, quality degrades or resource caps are violated. Return to a compatible safe revision only if it remains approved. Do not restore a revoked model route, stale entitlement or weakened policy through a historical rollback. Emergency denies may take precedence over a pinned older revision. Define and test propagation delay, rather than promise an instantaneous kill switch across distributed caches.
10. Worked configuration resolution scenario#
Suppose an enterprise plan includes answer, report and export. The tenant admin requests all three, but rollout exposes report to only an approved subset. An employee has permission to read the relevant document and request answers, but not export it.
For that employee:
- Requested capabilities: {answer, report, export}.
- Entitled capabilities: {answer, report, export}.
- Rollout-enabled: {answer, export}.
- Current coarse actor grants: {answer, report}.
- Platform allows all three, but no external publication except through a protected executor.
Intersection gives {answer}. The report feature is not exposed in this cohort; export is not granted to this actor. The API should not render those two unavailable states as the same billing failure. Even for answer, authorize the exact document at retrieval. Coarse grants do not establish resource-level access.
Assume the tenant requests 1,500 output tokens, the selected route supports 2,000 for this task and the contract's maximum is 1,200. If the approved validation policy rejects over-limit preferences, return a configuration error before activation; if a documented normalization policy clamps it, show 1,200 as effective and explain the cap. The worked Python fixture uses rejection rather than silent normalization.
If the tenant switches from shared hosted to a private route and changes the prompt, the next accepted task resolves a new manifest. An old running report cannot simply switch model halfway through without defined compatibility. A deterministic read-only report may complete under its originally approved bundle if still authorized, while an export request must recheck current entitlement, policy and resource permission. If private processing becomes mandatory due to a new restriction, stop any not-yet-permitted hosted dispatch and reconcile ongoing work under the approved incident procedure.
11. Tested implementation: typed resolver and pinned-manifest check#
This standard-library example demonstrates a deliberately small answer/export product. A trusted policy provides approved capabilities and model routes; coarse current grants, entitlements and rollout sets are server-controlled. The tenant preference chooses a known compatible route and prompt. Effective enabled capabilities are intersected rather than merged permissively. The fixture uses a strict policy: any effective manifest change requires replan before further dispatch.
PYTHONfrom dataclasses import dataclass, replace from hashlib import sha256 import json @dataclass(frozen=True) class Policy: capabilities: frozenset[str] routes: frozenset[str] max_tokens: int epoch: int @dataclass(frozen=True) class TenantConfig: tenant: str revision: int requested: frozenset[str] route: str prompt: str tokens: int ROUTES = {'local-v1': 'answer/v1', 'hosted-v2': 'answer/v1', 'legacy': 'answer/v0'} PROMPTS = {'plain-v1', 'formal-v2'} def resolve(tenant, cfg, policy, entitlements, rollout, grants): # Every input except tenant preferences comes from trusted control-plane state. if cfg.tenant != tenant or type(cfg.revision) is not int or cfg.revision < 1: raise ValueError('scope or revision') if (not cfg.requested <= policy.capabilities or cfg.route not in policy.routes or ROUTES.get(cfg.route) != 'answer/v1' or cfg.prompt not in PROMPTS or type(cfg.tokens) is not int or not 1 <= cfg.tokens <= policy.max_tokens): raise ValueError('incompatible configuration') enabled = cfg.requested & entitlements & rollout & grants return {'tenant': tenant, 'revision': cfg.revision, 'policy_epoch': policy.epoch, 'capabilities': sorted(enabled), 'route': cfg.route, 'prompt': cfg.prompt, 'tokens': cfg.tokens} def fingerprint(effective): return sha256(json.dumps(effective, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() def dispatch_allowed(pinned, current, capability): # Strict fixture: require replan after any effective configuration change. return (fingerprint(pinned) == fingerprint(current) and capability in current['capabilities']) p = Policy(frozenset({'answer', 'export'}), frozenset(ROUTES), 2000, 7) a = TenantConfig('a', 1, frozenset({'answer', 'export'}), 'local-v1', 'plain-v1', 1000) b = replace(a, tenant='b', route='hosted-v2', prompt='formal-v2') all_caps = frozenset({'answer', 'export'}) answer = frozenset({'answer'}) def get(cfg=a, policy=p, ent=all_caps, flags=all_caps, grants=all_caps, tenant='a'): return resolve(tenant, cfg, policy, ent, flags, grants) x = get() assert x['capabilities'] == ['answer', 'export'] assert get(ent=answer)['capabilities'] == ['answer'] assert get(flags=answer)['capabilities'] == ['answer'] assert get(grants=answer)['capabilities'] == ['answer'] assert get(grants=frozenset())['capabilities'] == [] assert get(b, tenant='b')['route'] == 'hosted-v2' assert fingerprint(x) != fingerprint(get(b, tenant='b')) assert fingerprint(x) == fingerprint(dict(reversed(list(x.items())))) assert dispatch_allowed(x, get(), 'export') assert not dispatch_allowed(x, get(grants=answer), 'export') assert not dispatch_allowed(x, get(policy=replace(p, epoch=8)), 'answer') assert not dispatch_allowed(x, get(replace(a, revision=2)), 'answer') assert not dispatch_allowed(x, x, 'delete') for bad in (b, replace(a, requested=frozenset({'delete'})), replace(a, route='legacy'), replace(a, route='unknown'), replace(a, prompt='arbitrary'), replace(a, tokens=2001), replace(a, tokens=True), replace(a, revision=0)): try: get(bad) except ValueError: pass else: raise AssertionError('invalid configuration accepted') try: get(policy=replace(p, routes=frozenset({'hosted-v2'}))) except ValueError: pass else: raise AssertionError('forbidden route accepted') print('22 checks passed')
Observed local execution on Python 3.13.5:
22 checks passedThirteen direct assertions and nine exception checks verify effective intersection, empty grants, two tenant-specific configurations using the same resolver, tenant-sensitive fingerprints, stable key ordering, valid pinned dispatch, denial after grant change, policy-epoch and revision changes, disabled capabilities, cross-tenant mismatch, forbidden requested capability, incompatible legacy route, unknown route, unapproved prompt, excess and Boolean token limits, invalid revision and a removed route.
The code intentionally assumes normalized typed inputs from a trusted server. The tenant preference is still validated. It does not authenticate users, check actual entitlement contracts, verify prompt/model artifact digests, bind object permissions, enforce regional processor constraints, implement distributed revocation, count token usage or execute an inference. The policy object would be resolved per appropriate tenant and purpose, not necessarily shared globally as in this fixture. The route is selected even if no capabilities are enabled; callers must enforce the requested capability and current resource authorization before *any* inference or protected read. The example uses a simple shared answer contract and does not demonstrate per-capability model routing or a workflow graph.
The hash is deterministic for this limited Python representation, not a full RFC 8785 canonicalization or a cryptographic signature. Comparing fingerprints is a conservative change detection strategy; it rejects benign changes as well as relevant changes. A production runtime may pin behavior versions while separately rechecking current authorization and mandatory restrictions, and use a compatibility relation for safe irrelevant changes. The two compared manifests must be obtained from trusted state; a client cannot supply both and certify itself. A successful check alone cannot make a subsequent remote execution atomic with policy state.
The set intersection is small and efficient. With k candidate capabilities and fixed-size metadata, resolution is linear in the relevant set sizes and sorting enabled capabilities costs O(k log k); fingerprinting is linear in serialized manifest size after canonicalization. Actual performance depends on trusted lookup, registry validation, network, storage and cache behavior, none of which is benchmarked here.
12. Data model and tenant isolation#
A useful conceptual persistence model separates the following logical entities:
| Entity | Ownership and purpose |
|---|---|
| tenant | Canonical organization identity and lifecycle |
| tenant_config_revision | Immutable desired settings, schema version, actor, digest |
| tenant_config_pointer | Current approved active revision and compare-and-swap version |
| entitlement_revision | Commercial authority and effective dates |
| policy_bundle | Mandatory restrictions and policy epoch |
| artifact_registry | Approved model, prompt, connector and workflow compatibility |
| rollout_assignment | Versioned cohort/exposure state |
| execution_manifest | Resolved behavior and relevant authority/provenance references |
| change/audit record | Authorized edit, approval, activation, rejection and rollback evidence |
Tenant-scope composite keys and foreign keys where appropriate prevent accidental cross-tenant associations. Apply resource-level authorization at database and service boundaries; database row-level policies can be an important defense in depth where supported. Tenant identity comes from authenticated session and authorized organization membership, not a user-editable metadata field or model-supplied tenant ID. Distinguish an employee who belongs to several organizations from the organization currently acting as data controller or owner.
Enforce isolation across config reads/writes, prompt and workflow registries, retrieval sources, cache keys, object storage, job queues, traces, provider requests and derived artifacts. A shared model runtime need not know private tenant billing details. A tenant template cannot access another organization's dictionary or documents simply by guessing a reference. Verify current authorization before assembling context for the model, not after generation. Never treat a tenant-specific prompt as a security boundary.
Dedicated deployments may use separate databases, credentials or accelerator pools; pooled deployments need proven access predicates and noisy-neighbor controls. Neither isolation strategy implies a code fork. A dedicated deployment should consume the same signed/approved application artifact and compatible configuration contract where possible.
13. Cache effective behavior without caching perpetual authority#
Effective configuration may be resolved at request start from several independently owned records. Avoid fetching every row on every request if versioned snapshots and invalidation can meet the consistency contract. Cache the trusted resolved configuration by tenant, relevant workspace/actor scope where necessary, configuration revision, plan/entitlement revision, policy epoch, rollout variant, schema and registry release identities. A tenant ID alone is insufficient.
Separate relatively stable behavior configuration from short-lived actor authorization. A prompt selection can often be cached longer than a permission or emergency policy decision. On a cache hit, check required current authority and validity; preserve immutable provenance. Define whether the resolver can serve last-known-good values when the control plane is unavailable. Only continue capabilities whose approved staleness and current mandatory restrictions allow it. Deny affected protected effects when required trusted policy or authorization is unavailable.
Use versioned invalidation events and periodic repair to handle missed messages. A delayed activation event must not replace a newer configuration pointer. The resolver can atomically read local policy/config projections within their documented consistency boundary; it cannot magically obtain a globally atomic snapshot from independent remote services. For strict revocation and write operations, rely on authoritative enforcement at the resource. Capture source revision/epoch rather than rely on a wall-clock timestamp alone.
Prediction and result caches need more than effective-config equality: input/source snapshot, authorized scope, model/preprocessor release, target semantics and validity must match. Consult the specialist MLOps prediction-cache lesson. Reusing the same prompt artifact across tenants does not justify sharing their private result cache.
14. Configuration drift and fleet operation#
Configuration drift occurs when desired, approved and actually executing behavior diverge unexpectedly. A tenant admin may see prompt revision 3 while a worker uses revision 2; a dedicated deployment may run an outdated adapter; or a mutable model alias may silently change output behavior.
Define desired state, approved effective state and observed runtime state separately. Record the actual configuration, policy, artifact and application release used for each logical task. Compare observed manifests to permitted combinations. A known canary is intentional variation, not drift. An unexplained route or policy epoch mismatch is an incident or configuration error.
Use declarative versioned configuration, controlled write APIs, immutable artifacts, a reconciler and audited emergency changes. Periodically enumerate active pointers, supported schema versions, unavailable artifact references, stale runtime leases and unexpired temporary overrides. Reconcile with current desired state using bounded retries and idempotent activation. Do not silently overwrite an authorized incident restriction just because a reconciliation controller sees a different old desired configuration.
A drift metric might report the fraction of eligible tasks using an approved expected manifest, or the oldest runtime lag beyond a configured propagation budget. Keep tenant-specific detailed diagnostics in restricted logs; avoid unbounded tenant/model/prompt labels in every metric series. Aggregate by product tier, region, artifact version or reason, and use governed trace lookups for tenant-specific investigation.
Configuration proliferation is technical debt even without source forks. Track number of distinct templates, combinations, deprecated fields, active flags, one-off exceptions and unsupported registry revisions. Consolidate equivalent profiles, retire unused flags and extensions after approved migration, and time-bound exceptions. Do not reduce maintenance by erasing legitimate tenant requirements.
15. Worked scale and maintenance economics#
Assume 5,000 tenants, each with one 4 KB normalized active configuration manifest. The active raw payload footprint is 20 MB in decimal units before metadata, indexes, caches and replicas. If each tenant makes two changes per month and immutable desired revisions average 4 KB, that adds 40 MB raw per month. Twelve months of changes add 480 MB, excluding audit and artifact storage. Large prompt templates and model files should be referenced, not copied into every manifest.
Suppose the product processes 2,000 logical tasks/s. A naive resolver performs five control-plane lookups for each task, offering 10,000 lookup attempts/s before retries. With a 95% effective-manifest cache hit rate under a compatible approved scope, the miss path would offer 2,000 × 0.05 × 5 = 500 lookups/s. This is only the configuration lookup reduction; independent authorization, current policy checks and artifact retrieval remain. Correlated cold starts, policy updates and hot tenants can produce bursts. Bound cache-miss concurrency and use equivalent authorized single-flight requests where appropriate.
Consider 100 tenant-specific code branches requiring a hypothetical 30-minute branch-specific regression run each for a security patch. Pure serial runner time is 50 hours, excluding coordination and remediation. One common artifact tested across 12 representative supported profiles at 30 minutes per profile uses six runner-hours under those assumptions. The common artifact still needs per-tenant validation, targeted negative tests and any contractually required dedicated deployment checks. This arithmetic illustrates the duplicated release cost, not a measured savings guarantee.
Configuration space can be enormous: 3 model routes × 4 prompt templates × 5 workflow templates × 2 review variants × 3 locales × 4 plan profiles gives 1,440 raw combinations. Some are invalid by compatibility rules. Do not support all arbitrary combinations merely because fields exist. Constrain the set of approved profiles and test interacting features using risk-based combinatorial coverage. Pairwise testing can reduce the number of combinations but cannot establish that higher-order interactions or mandatory security invariants hold.
16. Testing and release acceptance#
Test configuration as a behavior release across schema, resolver, runtime and control plane. A useful matrix:
| Test | Example |
|---|---|
| Schema | Unknown fields, invalid enum, incompatible route, unsupported revision |
| Merge | Missing vs null vs empty set, inheritance, conflicting restrictions |
| Entitlement | Expiry/downgrade, disabled capability, unlicensed extension |
| Authorization | Forged tenant, wrong resource, revoked grant, admin role boundaries |
| AI quality | Prompt variant, locale, approved model route, required output contract |
| Workflow | Required review on all paths, unapproved step, bounded loop, stale approval |
| Isolation | Cross-tenant prompt and cache IDs, retrieved source, generated artifact |
| Lifecycle | Concurrent config edits, reader compatibility, stale event, failed activation |
| Recovery | Control-plane outage, withdrawn route, rollback under current policy |
| Performance | Hot tenant, cache cold start, cohort expansion, token/quota pressure |
Use golden fixtures for effective manifests and explicit reason codes, property-based tests for restrictions (removing an allowed capability cannot enable it), tests for cross-field compatibility, and differential tests between supported versions. For risk-sensitive configurations, test all mandatory control paths, not merely a random sample. Use pairwise or t-way design for lower-risk combinations and separately test known higher-order interactions, rare critical cases and customer-specific contracts.
For model, prompt or workflow variants, evaluate complete user tasks on authorized representative datasets. A syntactically valid manifest does not guarantee grounded answers or acceptable latency. Track accepted task quality and abstention by route and profile; avoid averaging away poor outcomes for small tenants. The prototype canary must not bypass required safety gates. Use test tenants and isolated effects for negative or destructive tests.
Record the approved app/config/schema/artifact combinations; prevent incompatible activation. Require release owners to review expected change impact, validation evidence, rollout scope, stop conditions and recovery. An automated deployment controller should report HOLD if evidence or trusted configuration is missing, not interpret absence as success.
The tested local resolver above covers a subset of resolution arithmetic and strict manifest comparison. It does not prove isolation, remote revocation, concurrency, actual model compatibility, security or load capacity. These require independent deployed-system evidence.
17. Observability, quotas and operational ownership#
Every task should carry a logical task ID, authorized tenant scope, resolved config and policy version, actual model/prompt/workflow release, routing reason, result state and attributable resource use. Record why a capability was unavailable without leaking restricted information. Distinguish tenant preference from actual route after approved fallback. Protect logs and traces from private prompts, documents and secret values.
Monitor configuration resolution failure, invalid active configurations, activation lag, drift, denied routing, fallback frequency, per-profile quality and deadline success, cost per useful outcome, quota rejection, extension failures, and time to contain a faulty configuration. Separate planned feature disablement from service unavailability. Use meaningful denominators: configured capability, licensed tenant, eligible request and completed task are not the same unit.
Use per-tenant admission, concurrency and spend controls consistent with the product plan and platform capacity. A requested token maximum is not a billing enforcement mechanism; measure actual token work, including retries and tool calls, and use atomic or otherwise appropriately coordinated quota accounting where strict limits matter. Distributed reservation/release and fairness deserve explicit infrastructure design. Never route to a forbidden model because another tenant consumed capacity.
Assign owners for the configuration schema, entitlements, security policy, artifact registry, tenant admin experience, workflow extensions, runtime and on-call. A tenant-specific issue should be diagnosable using manifest history rather than building a special branch for debugging. Support can propose a scoped reviewed configuration change, not directly modify production state outside the authorized lifecycle.
18. Failure scenarios and trade-offs#
| Failure | Correct behavior |
|---|---|
| Tenant requests unapproved model URL | Reject; only registry-approved routes |
| Prompt requests unrestricted export | Treat as untrusted content; independent authorization |
| Paid plan expires while job queued | Apply defined current entitlement and completion contract |
| Flag cache misses emergency disable | Recheck required current epoch/authority; contain affected effects |
| Control plane unavailable | Approved bounded safe fallback for permitted behavior; fail closed where required |
| Model release withdrawn | Block new affected dispatch; recover under compatible approved route |
| Old runtime cannot read new config | Hold activation or route to approved compatible runtime |
| Stale config event arrives | Conditional revision update; no overwrite of newer pointer |
| Tenant-specific plugin crashes | Isolate, enforce deadline, degrade only within contract |
| Requested workflow removes review | Reject at validation and enforce current gate at resource |
| Rollback would restore revoked permission | Preserve current restriction; select safe compatible behavior |
| Unsupported tenant-specific exception grows | Productize approved variation point or explicitly fund separate product |
The main trade-off is flexibility versus governance and testability. More configurable dimensions can reduce custom code but multiply compatibility combinations. A common runtime reduces duplicated patches yet increases the blast radius of a shared defect; use canaries, isolation, per-capability controls and recovery. Shared inference can improve utilization but requires trustworthy tenant scoping and fair admission; dedicated deployment can satisfy isolation and performance requirements while increasing cost. A centralized configuration resolver simplifies consistent interpretation but adds dependency and cache-consistency concerns; validated immutable manifests can reduce runtime dependence without replacing current enforcement.
Prefer a small set of well-owned variation points and approved extensions. If a configuration schema has grown into unrestricted code execution, arbitrary endpoint selection and implicit policy rewriting, it has failed as a product architecture.
19. Interview-ready answer#
I would start by identifying stable product contracts and genuine tenant variation points, then build a common runtime with typed capability, model, prompt and workflow adapters. I would establish a configuration control plane with immutable revisions, explicit inheritance and field-specific merge rules, a registry of approved compatible artifacts, and independently owned entitlements, rollout flags and mandatory policies. Effective capability selection would intersect requested, entitled, exposed and authorized operations; it would never override resource-level permissions or platform restrictions.
At request admission I would derive tenant and actor from trusted context, resolve a validated versioned effective manifest, select an eligible compatible route and execute the common domain workflow. I would pin behavior where necessary for reproducibility while rechecking current restrictions, permission and state before protected reads or effects. I would protect caches, data, jobs, extension runtimes and provenance by scope. Dedicated infrastructure would use the same product contracts and code artifact unless a distinct product truly requires otherwise.
I would treat configuration changes as releases: validate structure and semantics, bind review to exact revisions, test representative and adversarial combinations, roll out to controlled eligible cohorts, monitor effective behavior and reconcile drift. Rollback would preserve current restrictions. I would measure useful task quality, latency, cost and operational burden across profiles, and retire obsolete flags and exceptions. The result is a single maintained product with controlled, auditable variation, not many hidden forks expressed as arbitrary configuration.
References and research transparency#
The authorized offline research exception applies. These references identify established specifications, architectural guidance and security/testing literature; current contents and URL availability and the current Supabase changelog were not verified. Four meaningful Mermaid diagrams use standard triple-backtick fences and received structural review only; no parser or live site rendering was tested. The exact Python fixture ran locally on Python 3.13.5 and passed 22 checks. No live model, HTTP endpoint, feature-flag provider, distributed configuration store, tenancy security test, actual rollout or load benchmark was performed. JSON and architecture examples are illustrative, and all numerical scenarios are hypothetical.
- OpenFeature — Specification
- OpenFeature — Evaluation Context
- Martin Fowler — Feature Toggles
- The Twelve-Factor App — Config
- JSON Schema — Draft 2020-12
- Open Policy Agent — Policy Language
- NIST SP 800-207 — Zero Trust Architecture
- NIST AI Risk Management Framework
- OWASP — Top 10 for Large Language Model Applications
- IETF RFC 8785 — JSON Canonicalization Scheme
- IETF RFC 9110 — HTTP Semantics
- Google SRE Workbook — Canarying Releases
- NIST SP 800-142 — Practical Combinatorial Testing
- AWS SaaS Lens — Well-Architected Framework
References
- 1.OpenFeature — Specificationopenfeature.dev
- 2.OpenFeature — Evaluation Contextopenfeature.dev
- 3.Martin Fowler — Feature Togglesmartinfowler.com
- 4.The Twelve-Factor App — Config12factor.net
- 5.JSON Schema — Draft 2020-12json-schema.org
- 6.Open Policy Agent — Policy Languageopenpolicyagent.org
- 7.
- 8.
- 9.OWASP — Top 10 for Large Language Model Applicationsgenai.owasp.org
- 10.IETF RFC 8785 — JSON Canonicalization Schemerfc-editor.org
- 11.IETF RFC 9110 — HTTP Semanticsrfc-editor.org
- 12.Google SRE Workbook — Canarying Releasessre.google
- 13.
- 14.AWS SaaS Lens — Well-Architected Frameworkdocs.aws.amazon.com
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython