GDPR cost control architecture for enterprise LLM deployment — Reference Architecture

Reference architecture · published 2026-10-16 · regulated enterprise · GDPR · layout walkthrough · implementation executed in CI before publish

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 GDPR, and the question it actually asks is what is the lawful basis, and can you actually erase. The shape below holds p95 ≤ 900ms over durable queue (SQS / Kafka) with an outbox, and ships with a standard-library implementation that runs as written.

The control gap

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 GDPR specifically requires

GDPR asks two things an audit log does not answer: under what lawful basis was this processed, and can you erase it on request. Erasure is the harder one — a prompt embedded into a vector index and a fine-tune has propagated beyond the row you deleted.

The artifact that satisfies it is a lineage graph from source record to every derived artifact. The way teams most often fail it: an erasure request that cannot be honoured because the data survives in embeddings, caches and eval sets.

Why this blocks a rollout rather than slowing it: A ceiling enforced after the call is an alert, not a control. Enforcement has to happen before the request on a conservative estimate, with reservations — otherwise concurrent requests all read the same low spend figure and the cap is raced past. In regulated enterprise the cost of getting it wrong is concrete — a failed Type II observation window restarts the clock.

Modular implementation framework

  1. Conservative estimator — Deliberately over-estimates; under-estimating makes the ceiling decorative.
  2. Two-phase budget — Reserve the estimate, settle the actual — closes the concurrency race.
  3. Rate table in config — Prices change; a stale rate in code silently misprices every chargeback.
  4. Tier router — Routes to the cheapest tier that meets the quality bar for the task.
  5. Chargeback ledger — Per-tenant, per-request actuals — the artifact finance reconciles against.
  6. Fail-closed default — A tenant with no budget is refused, never admitted.

The 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 durable queue (SQS / Kafka) with an outbox; the failure mode it guards against is a consumer crash between side effect and acknowledgement. The output you hand the assessor is the data-subject lineage and erasure report.

"""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 GDPR control, as code

Article 17 erasure propagated into derived artifacts. This is the artifact an assessor asks for under GDPR 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.

"""Article 17 erasure that propagates into derived artifacts.

The erasure request everyone implements is a DELETE on the source row. The one
that fails an audit is the derived copy: embeddings in a vector index, a cached
retrieval chunk, a fine-tuning corpus, a prompt log. Article 17(2) expects
controllers to take reasonable steps to inform processors of the erasure, and a
vector built from personal data is still personal data.

So erasure is modelled as a lineage walk with a receipt per derived artifact,
and the request is not complete until every downstream store confirms.
"""
from datetime import datetime, timezone


class Store:
    def __init__(self, name: str, kind: str):
        self.name, self.kind = name, kind
        self.rows: dict[str, dict] = {}
        self.erased: list[str] = []

    def put(self, key: str, subject_id: str, payload: str) -> None:
        self.rows[key] = {"subject_id": subject_id, "payload": payload}

    def erase_subject(self, subject_id: str) -> int:
        doomed = [k for k, v in self.rows.items() if v["subject_id"] == subject_id]
        for k in doomed:
            del self.rows[k]
            self.erased.append(k)
        return len(doomed)

    def holds(self, subject_id: str) -> int:
        return sum(1 for v in self.rows.values() if v["subject_id"] == subject_id)


class ErasureOrchestrator:
    """Lineage-aware erasure. A store that is not registered cannot be erased,
    so registration is the control — an unregistered derived store is exactly
    how personal data survives a 'completed' erasure."""

    def __init__(self):
        self.stores: list[Store] = []
        self.lineage: dict[str, list[str]] = {}

    def register(self, store: Store, derived_from: str | None = None) -> Store:
        self.stores.append(store)
        if derived_from:
            self.lineage.setdefault(derived_from, []).append(store.name)
        return store

    def execute(self, subject_id: str) -> dict:
        receipts = []
        for store in self.stores:
            held = store.holds(subject_id)
            removed = store.erase_subject(subject_id)
            receipts.append({"store": store.name, "kind": store.kind,
                             "held": held, "erased": removed})
        residual = {s.name: s.holds(subject_id) for s in self.stores
                    if s.holds(subject_id)}
        return {
            "subject_id": subject_id,
            "completed_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
            "receipts": receipts,
            "residual": residual,
            "complete": not residual,
            "derived_stores_covered": sorted(
                s.name for s in self.stores if s.kind != "source"),
        }


if __name__ == "__main__":
    orch = ErasureOrchestrator()
    src = orch.register(Store("crm_postgres", "source"))
    vec = orch.register(Store("vector_index", "embedding"), derived_from="crm_postgres")
    cache = orch.register(Store("retrieval_cache", "cache"), derived_from="vector_index")
    logs = orch.register(Store("prompt_log", "log"), derived_from="crm_postgres")

    src.put("c-1", "subject-77", "Jana Soor, contract renewal notes")
    vec.put("v-1", "subject-77", "[0.11, -0.4, ...]")
    cache.put("k-1", "subject-77", "chunk: contract renewal notes")
    logs.put("l-1", "subject-77", "prompt containing the same notes")
    src.put("c-2", "subject-90", "unrelated subject")

    result = orch.execute("subject-77")
    assert result["complete"], result["residual"]
    assert len(result["derived_stores_covered"]) == 3, result
    assert sum(r["erased"] for r in result["receipts"]) == 4, result
    assert src.holds("subject-90") == 1, "erasure must not over-reach"

    # An unregistered derived store is the failure this design exists to expose.
    orphan = Store("analytics_extract", "warehouse")
    orphan.put("a-1", "subject-77", "same personal data, different copy")
    assert orphan.holds("subject-77") == 1
    assert orphan.name not in {s.name for s in orch.stores}

    print("GDPR Article 17 lineage erasure: OK")
    print(f"  stores erased {len(result['receipts'])}, complete={result['complete']}")
    print(f"  UNREGISTERED store still holding data: {orphan.name} "
          f"({orphan.holds('subject-77')} row) — registration is the control")

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]
Request path. Rendered as a diagram where scripting is available; the Mermaid source above is the authoritative definition either way.

Enterprise implementation parameters

Every value below is a parameter you can hold a vendor or an internal team to. Adjectives are not acceptance criteria.

Implementation parameters for this deployment shape
Deployment vectorShared tier with tiered routing and a pre-flight budget governor
Security standardGDPR
Applicable regimesSOC 2 Type II, ISO/IEC 27001:2022, GDPR
Latency SLAp95 ≤ 900ms — interactive surfaces need sub-second; batch jobs do not
Integration protocoldurable queue (SQS / Kafka) with an outbox — writes must survive a downstream outage
Idempotency controlthe outbox row is the idempotency record
Throughput envelopedecoupled; the queue absorbs the burst the model tier cannot
Middleware requirementpolicy decision point in front of the model gateway
Data classes in scopePII, commercial-in-confidence data
Retention obligationper the data class retention schedule, enforced automatically
Data residencycontracted processing region, asserted on every response
Contractual instrumentDPA plus a disclosed subprocessor list
Systems of recordSAP, Salesforce, Workday
Primary failure modea consumer crash between side effect and acknowledgement

Controls and acceptance parameters

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.

CategoryRiskControlAcceptance parameter
GDPRErasure request cannot reach data derived into embeddings or cachesTag every derived artifact with the source record id; make erasure a graph traversal, not a row deleteErasure completes across all derived stores within 30 days, evidenced by a lineage report per request
Cost controlConcurrent requests race past the ceilingTwo-phase reserve/settle; admission counts outstanding reservations40 concurrent oversized requests cannot exceed the ceiling (tested)
Cost controlToken estimate under-shoots, so the cap never bindsDeliberately conservative chars-per-token plus max_output_tokens in the projectionEstimate >= actual on 95%+ of requests; drift reviewed weekly
Cost controlStale price table misprices chargebackRates in versioned config with an effective date; alert when a rate is older than 90 daysChargeback reconciles to the provider invoice within 2%
Cost controlA tenant with no configured budget runs unboundedFail closed on a missing budget — refuse rather than admit0 requests served for tenants without a budget
Latency SLACheapest-tier routing degrades answer quality below the barPer-task quality gate with an eval set; escalate tiers on failure, never silentlyTier escalation rate tracked; quality gate pass rate above target
Data privacyChargeback ledger accumulates prompt text as 'usage context'Ledger stores counts and ids only — never prompt or completion bodiesSchema test asserts no free-text payload column in the ledger
OperationalPeriod rollover loses outstanding reservationsRoll the window and clear reservations atomically; settle in-flight against the new periodNo negative or double-counted spend across a rollover (tested)

What the auditor will ask

See also

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 GDPR control questions you cannot yet answer, and what closes each gap
Request an architecture review