ISO/IEC 27001:2022 cost control architecture for enterprise LLM deployment — Reference Architecture
Implementation parameter matrix
Every value below is a parameter you can hold a vendor or an internal team to. Adjectives are not acceptance criteria.
| Deployment vector | Shared tier with tiered routing and a pre-flight budget governor |
|---|---|
| Security standard | ISO/IEC 27001:2022 |
| Applicable regimes | SOC 2 Type II, ISO/IEC 27001:2022, GDPR |
| Latency SLA | p95 ≤ 900ms — interactive surfaces need sub-second; batch jobs do not |
| Integration protocol | REST over HTTPS — the widest compatibility and the easiest audit story |
| Idempotency control | an Idempotency-Key header, honoured for 24h |
| Throughput envelope | ~2k rps per gateway node before connection churn dominates |
| Middleware requirement | policy decision point in front of the model gateway |
| Data classes in scope | PII, commercial-in-confidence data |
| Retention obligation | per the data class retention schedule, enforced automatically |
| Data residency | contracted processing region, asserted on every response |
| Contractual instrument | DPA plus a disclosed subprocessor list |
| Systems of record | SAP, Salesforce, Workday |
| Primary failure mode | a retried POST creating a duplicate record |
The control that resolves this is a Pre-Flight Budget Governor, evaluated before the request reaches a model provider rather than audited afterwards. In regulated enterprise the binding constraint is ISO/IEC 27001:2022, and the question it actually asks is is this risk on the register with a named owner and a treatment. The shape below holds p95 ≤ 900ms over REST over HTTPS, and ships with a standard-library implementation that runs as written.
The architecture friction point
LLM spend is discovered in a monthly invoice and defended with a dashboard, so it is reported rather than controlled. Finance asks for a per-team cap and engineering cannot implement one, because nothing in the request path knows a budget exists.
What ISO/IEC 27001:2022 specifically requires
ISO 27001 is a management-system standard: the auditor checks that risks are identified, owned, treated and reviewed on a cycle. A perfect technical control that is absent from the risk register is a nonconformity.
The artifact that satisfies it is risk register entries with owners, treatments and review dates. The way teams most often fail it: a technically sound control that no Statement of Applicability references, so it cannot be evidenced.
Reference implementation — Two-phase token budget with per-tenant chargeback
Standard-library Python, no external dependencies, runs as written. Executed by the publish gate: if it raises, this page does not ship. Wire it behind REST over HTTPS; the failure mode it guards against is a retried POST creating a duplicate record. The output you hand the assessor is the Statement of Applicability extract.
"""Pre-flight token budget enforcement with per-tenant chargeback.
Why this shape: LLM spend is discovered monthly in an invoice and defended with
a dashboard, which means it is never actually controlled. The control has to run
BEFORE the call, on an estimate, with a hard ceiling per tenant and per period —
otherwise the first thing finance asks for is a cap you cannot implement.
"""
import math
import time
from dataclasses import dataclass, field
# USD per 1k tokens. Keep rates in config, not code: they change, and a stale
# rate silently misprices every chargeback downstream of it.
RATES = {
"frontier": {"in": 0.0030, "out": 0.0150},
"mid": {"in": 0.0008, "out": 0.0040},
"small": {"in": 0.0001, "out": 0.0004},
}
def estimate_tokens(text: str, chars_per_token: float = 3.8) -> int:
"""Deliberately a conservative OVER-estimate.
Under-estimating defeats the purpose: the request gets admitted, the real
usage exceeds the budget, and the ceiling is decorative."""
return max(1, math.ceil(len(text or "") / chars_per_token))
def price(tier: str, tokens_in: int, tokens_out: int) -> float:
r = RATES[tier]
return (tokens_in / 1000.0) * r["in"] + (tokens_out / 1000.0) * r["out"]
class BudgetExceeded(Exception):
def __init__(self, tenant, projected, ceiling):
self.tenant, self.projected, self.ceiling = tenant, projected, ceiling
super().__init__(f"{tenant}: ${projected:.4f} would exceed "
f"${ceiling:.2f} for the period")
@dataclass
class Budget:
ceiling_usd: float
period_seconds: float = 86400.0
spent_usd: float = 0.0
started: float = field(default_factory=time.time)
committed: dict = field(default_factory=dict) # request_id -> reserved USD
def _roll(self, now):
if now - self.started >= self.period_seconds:
self.started, self.spent_usd = now, 0.0
self.committed.clear()
def reserve(self, request_id: str, projected_usd: float, now=None) -> float:
"""Two-phase: reserve the estimate, settle the actual.
Without a reservation, N concurrent requests each see the same low
`spent` and all get admitted — the classic race that blows a cap."""
now = time.time() if now is None else now
self._roll(now)
outstanding = sum(self.committed.values())
if self.spent_usd + outstanding + projected_usd > self.ceiling_usd:
raise BudgetExceeded("tenant",
self.spent_usd + outstanding + projected_usd,
self.ceiling_usd)
self.committed[request_id] = projected_usd
return projected_usd
def settle(self, request_id: str, actual_usd: float):
self.committed.pop(request_id, None)
self.spent_usd += actual_usd
def release(self, request_id: str):
self.committed.pop(request_id, None)
class Governor:
def __init__(self):
self.budgets: dict = {}
self.ledger: list = []
def set_budget(self, tenant: str, ceiling_usd: float, period_seconds=86400.0):
self.budgets[tenant] = Budget(ceiling_usd, period_seconds)
def admit(self, tenant: str, request_id: str, prompt: str,
tier: str = "mid", max_output_tokens: int = 1024) -> dict:
b = self.budgets.get(tenant)
if b is None:
raise KeyError(f"{tenant} has no budget: fail closed, never open")
t_in = estimate_tokens(prompt)
projected = price(tier, t_in, max_output_tokens)
b.reserve(request_id, projected)
return {"tenant": tenant, "request_id": request_id, "tier": tier,
"tokens_in_est": t_in, "projected_usd": round(projected, 6)}
def record(self, tenant: str, request_id: str, tier: str,
tokens_in: int, tokens_out: int) -> dict:
actual = price(tier, tokens_in, tokens_out)
self.budgets[tenant].settle(request_id, actual)
row = {"tenant": tenant, "request_id": request_id, "tier": tier,
"tokens_in": tokens_in, "tokens_out": tokens_out,
"actual_usd": round(actual, 6), "ts": time.time()}
self.ledger.append(row) # this is the chargeback record
return row
if __name__ == "__main__":
g = Governor()
g.set_budget("bank-eu", ceiling_usd=0.05)
adm = g.admit("bank-eu", "req-1", "Reconcile these 400 journal lines." * 20)
print("admitted:", adm)
print("settled :", g.record("bank-eu", "req-1", "mid", adm["tokens_in_est"], 310))
try:
for i in range(40):
g.admit("bank-eu", f"burst-{i}", "x" * 4000, tier="frontier")
except BudgetExceeded as e:
print("ceiling held:", e)
The ISO/IEC 27001:2022 control, as code
Statement of Applicability with operating evidence. This is the artifact an assessor asks for under ISO/IEC 27001:2022 specifically — it is not the same control as the one above, and a system that implements one does not thereby implement the other. It executes under the same publish gate.
"""Annex A control to evidence mapping behind a Statement of Applicability.
ISO/IEC 27001:2022 turns on the SoA: every Annex A control is either applicable
with a justification and evidence, or excluded with a justification. The audit
failure is an applicable control whose evidence is a policy document rather
than a record that the control operated.
"""
ANNEX_A_2022 = {
"A.5.23": "Information security for use of cloud services",
"A.8.2": "Privileged access rights",
"A.8.10": "Information deletion",
"A.8.12": "Data leakage prevention",
"A.8.15": "Logging",
"A.8.16": "Monitoring activities",
"A.8.24": "Use of cryptography",
"A.8.28": "Secure coding",
}
EVIDENCE_KINDS = {"record", "configuration", "test_result"}
NON_EVIDENCE = {"policy", "intent", "roadmap"}
class StatementOfApplicability:
def __init__(self, scope: str):
self.scope = scope
self.entries: dict[str, dict] = {}
def apply(self, control: str, justification: str,
evidence_ref: str, evidence_kind: str) -> None:
if control not in ANNEX_A_2022:
raise KeyError(f"{control} is not an Annex A:2022 control")
if evidence_kind in NON_EVIDENCE:
raise ValueError(
f"{control}: {evidence_kind!r} describes intent, not operation")
if evidence_kind not in EVIDENCE_KINDS:
raise ValueError(f"{control}: unknown evidence kind {evidence_kind!r}")
self.entries[control] = {"applicable": True, "justification": justification,
"evidence_ref": evidence_ref,
"evidence_kind": evidence_kind}
def exclude(self, control: str, justification: str) -> None:
if control not in ANNEX_A_2022:
raise KeyError(f"{control} is not an Annex A:2022 control")
if len(justification.split()) < 5:
raise ValueError(f"{control}: exclusion needs a real justification")
self.entries[control] = {"applicable": False, "justification": justification}
def unaddressed(self) -> list[str]:
return sorted(set(ANNEX_A_2022) - set(self.entries))
def certifiable(self) -> dict:
gaps = self.unaddressed()
applied = [c for c, e in self.entries.items() if e["applicable"]]
return {"scope": self.scope, "applied": sorted(applied),
"excluded": sorted(c for c, e in self.entries.items()
if not e["applicable"]),
"unaddressed": gaps, "certifiable": not gaps}
if __name__ == "__main__":
soa = StatementOfApplicability("LLM platform, production tenant")
soa.apply("A.5.23", "Model inference is a cloud service",
"cfg://gateway/allowed-providers.yaml", "configuration")
soa.apply("A.8.2", "Operators hold privileged access to prompts",
"rec://iam/quarterly-access-review-2026Q3", "record")
soa.apply("A.8.10", "Retention is enforced on prompt logs",
"test://retention/expiry-suite-2026-10", "test_result")
soa.apply("A.8.12", "Egress to model providers can leak data",
"cfg://dlp/egress-classifier.yaml", "configuration")
soa.apply("A.8.15", "All inference events are logged",
"rec://audit/chain-head-2026-10-16", "record")
soa.apply("A.8.16", "Anomalous usage is monitored",
"rec://siem/llm-usage-alerts", "record")
soa.apply("A.8.24", "TLS and at-rest encryption",
"test://crypto/tls-config-scan", "test_result")
soa.exclude("A.8.28", "No application code is developed within this scope "
"boundary; the platform is configured, not coded")
report = soa.certifiable()
assert report["certifiable"], report
assert len(report["applied"]) == 7 and len(report["excluded"]) == 1, report
try:
soa.apply("A.8.15", "we have a logging policy",
"doc://policies/logging.pdf", "policy")
raise AssertionError("accepted a policy document as operating evidence")
except ValueError:
pass
partial = StatementOfApplicability("partial")
partial.apply("A.8.15", "logging", "rec://x", "record")
assert not partial.certifiable()["certifiable"]
assert len(partial.certifiable()["unaddressed"]) == 7
print("ISO/IEC 27001:2022 SoA evidence mapping: OK")
print(f" applied {len(report['applied'])}, excluded {len(report['excluded'])}, "
f"unaddressed {len(report['unaddressed'])}")
The request path
Pre-Flight Budget Governor — the request path, with the decision points that must exist before the first model call:
flowchart LR
REQ[Request] --> EST[Conservative token estimate]
EST --> PR[Price at tier rate]
PR --> RES{Reserve against budget<br/>spent + outstanding + projected}
RES -->|over ceiling| REJ[429 BudgetExceeded]
RES -->|no budget| FC[Refuse - fail closed]
RES -->|ok| TR[Tier router<br/>cheapest tier meeting quality bar]
TR --> M[Model call]
M --> ST[Settle actual usage]
ST --> LED[(Chargeback ledger)]
LED --> FIN[Finance reconciliation]Implementation components
- Conservative estimator — Deliberately over-estimates; under-estimating makes the ceiling decorative.
- Two-phase budget — Reserve the estimate, settle the actual — closes the concurrency race.
- Rate table in config — Prices change; a stale rate in code silently misprices every chargeback.
- Tier router — Routes to the cheapest tier that meets the quality bar for the task.
- Chargeback ledger — Per-tenant, per-request actuals — the artifact finance reconciles against.
- Fail-closed default — A tenant with no budget is refused, never admitted.
Risk register with acceptance criteria
Each row carries an acceptance parameter rather than an adjective, because "low latency" cannot be signed off. Retention here is bound by per the data class retention schedule, enforced automatically.
| Category | Risk | Control | Acceptance parameter |
|---|---|---|---|
| ISO/IEC 27001:2022 | Controls exist technically but are absent from the SoA and register | Generate register entries from the deployed control set so the register cannot drift from the system | 100% of deployed controls map to an SoA entry with an owner and a review date |
| Cost control | Concurrent requests race past the ceiling | Two-phase reserve/settle; admission counts outstanding reservations | 40 concurrent oversized requests cannot exceed the ceiling (tested) |
| Cost control | Token estimate under-shoots, so the cap never binds | Deliberately conservative chars-per-token plus max_output_tokens in the projection | Estimate >= actual on 95%+ of requests; drift reviewed weekly |
| Cost control | Stale price table misprices chargeback | Rates in versioned config with an effective date; alert when a rate is older than 90 days | Chargeback reconciles to the provider invoice within 2% |
| Cost control | A tenant with no configured budget runs unbounded | Fail closed on a missing budget — refuse rather than admit | 0 requests served for tenants without a budget |
| Latency SLA | Cheapest-tier routing degrades answer quality below the bar | Per-task quality gate with an eval set; escalate tiers on failure, never silently | Tier escalation rate tracked; quality gate pass rate above target |
| Data privacy | Chargeback ledger accumulates prompt text as 'usage context' | Ledger stores counts and ids only — never prompt or completion bodies | Schema test asserts no free-text payload column in the ledger |
| Operational | Period rollover loses outstanding reservations | Roll the window and clear reservations atomically; settle in-flight against the new period | No negative or double-counted spend across a rollover (tested) |
What the auditor will ask
- Where is this control in the risk register and the Statement of Applicability, who owns it, and when was it last reviewed?
Register entries are generated from the deployed control set, so every control has an SoA reference, a named owner and a review date that cannot silently lapse. - What refuses a request that would exceed this team's monthly cap, and where in the path does it run?
The budget governor, at admission — before the model call. It prices a conservative token estimate against the tenant's remaining ceiling and refuses the request if the projection would exceed it. - If 50 requests arrive at once against a nearly-exhausted budget, how many are admitted?
Only those that fit. Admission counts outstanding reservations as well as settled spend, which closes the race where concurrent requests all read the same low figure and are all admitted. - How does your chargeback figure reconcile to the provider invoice, and what is the variance?
The chargeback ledger records per-request actuals priced from a versioned rate table with an effective date; reconcile it monthly and track the variance against the provider invoice. - What happens to a tenant with no budget configured?
It is refused. A missing budget fails closed — admitting an unbudgeted tenant is how the cap becomes decorative. - Which rate table priced last month's chargeback, and when was it last updated?
The rate table in versioned config, with its effective date recorded. A rate older than 90 days raises an alert, because a stale rate silently misprices every chargeback downstream.
Related reference architectures
- Part of enterprise llm cost control.
- The same control appears in GDPR cost control architecture for enterprise LLM deployment.
- The same control appears in EU AI Act cost control architecture for enterprise LLM deployment.
- SOX cost control architecture for enterprise LLM deployment applies the same mechanism under a different obligation.
- A different failure mode of the same component: P95 cost control architecture for enterprise LLM deployment.
- If this is the blocker in front of you: enterprise AI infrastructure review.
Enterprise infrastructure review
If you are carrying this blocker, the useful next step is not a demo. It is a review of your actual request path against the control points above:
- Which of the 6 components exist in your estate today, and which are assumed
- Your current numbers against the 7 acceptance parameters, starting with p95 ≤ 900ms
- Which ISO/IEC 27001:2022 control questions you cannot yet answer, and what closes each gap