Skip to content

About

A Sovereign RAG app with self-hosted LLM & tenant isolation on Azure

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

13 Commits

Folders and files

Repository files navigation

Sovereign Multi-Tenant RAG Platform

A self-hosted retrieval-augmented generation platform where multiple regulated tenants share one GPU but are provably isolated at the data plane, the control plane, and the network.

Two tenants, each with their own legal corpus, ask the same question and get different correct answers with different citations:

Tenant Corpus "What are my breach notification obligations?"
tenant-a UAE Federal Decree-Law 45/2021 (PDPL) cites PDPL Art. 9
tenant-b DIFC Data Protection Law No. 5 of 2020 cites DIFC Art. 41

A retrieval leak is therefore visible: the tenant would be told the obligations of a legal regime that does not apply to them.

Video walkthrough (Intro): youtu.be/3JQY13Bs4b0


Why this is the hard part

Government and regulated organisations want their own LLM stack: weights on their own hardware, no data crossing the boundary, answers grounded in their own corpus. The economics only work if several entities share the GPU, because a dedicated accelerator per organisation is unaffordable.

That produces the actual engineering problem: shared compute, non-shared data.

Most RAG systems don't address it. One vector collection behind one endpoint is fine until the second tenant arrives, at which point "the retriever returned the wrong document" stops being a quality bug and becomes a data-protection incident, under exactly the laws the corpus contains.

So isolation here is not a single WHERE tenant_id = ?. It is enforced independently at three layers, and the evaluation suite fails the build if any of them leaks.


Architecture

Sovereign multi-tenant RAG on AKS

Description. Boxes are coloured by ownership: grey is outside the sovereign boundary, blue is Azure-managed, green is the AKS data plane, white are namespaces you own. Arrows are coloured by whose request it is: teal is tenant-a, purple is tenant-b, black is shared by both, red is a call that must fail. Numbers 1 to 8 follow tenant-a's question end to end. Tenant-b's path is deliberately unnumbered because it is identical apart from the collection.

Three things the picture is there to make obvious:

  • Teal and purple arrive at the same TEI, Qdrant and vLLM nodes and still never mix. That is the whole thesis: shared compute, non-shared data.
  • The only stretch genuinely shared inbound is the load balancer and the nginx controller. Separation begins at the Host header, not before it.
  • The three isolation layers fail in three different places. Network is dropped pod-to-pod inside the data plane. RBAC is refused by the API server, which is why that denial routes through the control-plane box rather than pod-to-Secret. The data-plane filter happens inside the retriever, so it is written on edge 6 rather than drawn as a box.

Line style carries meaning too: solid is the request path, dashed is an identity being presented (an API key, a ServiceAccount token), dotted is standing background that is true all the time and part of no single request.

All platform services are ClusterIP, never exposed externally.

Layer Isolation mechanism How it's proven
Data Qdrant metadata filter on tenant_id, applied inside the retriever rather than at the request boundary Eval asserts every retrieved chunk's tenant_id equals the caller's, across all queries
Control Namespace per tenant; ServiceAccount + Role scoped to its own Secret/ConfigMap only kubectl auth can-i get secrets -n tenant-b --as=…:tenant-a:rag-sa → no
Network Calico NetworkPolicy: default-deny, egress to rag-platform and DNS only kubectl exec from tenant-a to tenant-b's Service → timeout

Stack

Component Choice Why
Cluster AKS, 3 node pools (system / apps / gpu) GPU node is the scarce resource; taint keeps everything else off it
Inference vLLM, Qwen2.5-7B-Instruct-AWQ see Model selection below
Embeddings TEI, BAAI/bge-m3, on CPU see Why embeddings run on CPU below
Vector store Qdrant, one collection per tenant Filtered-search correctness; see Vector store below. The named-vector alternative would put both tenants in one collection, a worse blast radius
Audit In-process ring buffer (app/main.py:59) Records question_sha256, retrieved article IDs, refusal status and latency on every call, including rejected ones
Ingress ingress-nginx + cert-manager, self-signed CA Proves the Issuer → Certificate → Secret path without owning DNS

Design decisions

Model selection: constraint first, not benchmark

The T4 is Turing (SM 7.5): 16 GB, no bf16, no Marlin kernels, no FP8. That narrows the field to a 7B at 4-bit AWQ before quality is even discussed.

Within that constraint, RAG needs three behaviours more than it needs raw reasoning: instruction-following (stay inside the retrieved context), reliable refusal (say "not in these documents"), and clean structured output (citation markers, tool-call JSON). It also needs to be ungated, so there is no Hugging Face token dependency in the deploy path.

Qwen2.5-7B-Instruct-AWQ satisfies all four. Llama-3.1-8B is gated; Mistral-7B is weaker at instruction-following; Hermes-2-Pro is a better pure tool-caller but weaker at general RAG. On an H100 the calculus changes entirely: FP8 becomes available and a 32B or an FP8 70B is back on the table.

--model=Qwen/Qwen2.5-7B-Instruct-AWQ
--quantization=awq          # NOT awq_marlin. Marlin requires SM 8.0+, T4 is 7.5
--dtype=float16             # Turing has no bf16
--gpu-memory-utilization=0.90
--max-model-len=8192
--enable-auto-tool-choice
--tool-call-parser hermes   # the Qwen2.5 tool-call parser

Memory: ~5.6 GiB of weights leaves ~7 GiB of KV cache at util 0.90, comfortable on 16 GB.

The LLM never writes an article number

Retrieved chunks are numbered [1]…[k] in the prompt. The model may cite markers only. The service maps marker → chunk metadata → PDPL Art. 9.

This makes hallucinated citations structurally impossible rather than statistically unlikely, and turns citation accuracy from an LLM-judge problem into a schema check. It is the single most important design call in the system.

Vector store: three of the four candidates are eliminated by constraints

Candidate Verdict
Pinecone Eliminated by the thesis. Managed SaaS means the corpus leaves the boundary, and indexing data-protection law on someone else's infrastructure contradicts the premise. Not a tradeoff; a contradiction.
FAISS Wrong category. A library, not a database: no server, no auth, no concurrent writers, metadata filtering not first-class. The index would live inside rag-service, so ingest becomes redeploy. Or you write a server around it and have rebuilt a worse Qdrant.
OpenSearch Viable, priced out. Better hybrid BM25+vector, which suits a corpus users cite by exact string. But JVM heap alone wants 2 to 4 GiB against Qdrant's ~1 GiB budget, in a pool where TEI already takes 3 GiB. Forces a bigger VM against a 6/10 regional vCPU quota.
pgvector The strongest objection, because a Postgres for observability would cost zero extra pods. Rejected because it makes the observability database the tenant data store: the tracing system filling its disk would take retrieval down, and a compromised tracing pod would sit inside the corpus.

Why Qdrant wins on the one axis that matters here: filtered-search correctness.

The tenant filter is a security boundary, not a preference. Stores that implement filtering as post-filtering, meaning retrieve global top-k then discard non-matching rows, fail silently under a tenant filter: if this tenant's chunks miss the global top-k, the retriever returns fewer than k results, or none, and degrades exactly as the corpus grows. Qdrant applies payload filters during HNSW traversal, so a tenant-scoped search returns the true top-k within that tenant.

That is what would make a recall@5 ≥ 0.90 gate real: it would be measured under the filter, and post-filtering would make the number a lie.

Secondary: Rust single binary, no JVM, ~1 GiB; collections are a native isolation unit, so one-per-tenant is idiomatic rather than a convention the app enforces.

What would change the answer: hybrid keyword search dominating quality → OpenSearch. The sovereignty requirement dropped → Pinecone, cheaper to operate. Millions of vectors per tenant → collection-per-tenant stops scaling; move to single-collection with payload partitioning.

Why embeddings run on CPU

Both models fit on the T4 on paper. They run separately because two pods cannot share one nvidia.com/gpu: 1 without time-slicing, and time-slicing gives scheduling isolation with zero memory isolation. One OOM would take down inference and embedding together.

Embedding is a one-time batch cost at ingest, not on the serving hot path, so CPU is the correct place for it. The GPU stays dedicated to the latency-sensitive workload.

Tenant identity is resolved server-side

The tenant is derived from the API key alone. A client-supplied X-Tenant header never influences collection selection: it is rejected with 403 and written to the audit log. This is the difference between a tenant boundary and a tenant suggestion.

Audit records hash the question

Storing data-subject queries verbatim inside a data-protection system is a self-own. The audit row keeps question_sha256, the retrieved article IDs, guardrail decisions, refusal status and latency: enough to reconstruct what the system did without retaining what was asked.


Evaluation

Deterministic metrics only, no LLM judge, so results are reproducible and the gate is meaningful.

eval/run_eval.py runs 8 questions and computes two metrics, deliberately asymmetric:

Metric Role Result on the cluster
leakage_rate GATE, exits 1 on any boundary crossing, no error budget 0
gold_article_hit_rate reported, never gated 6/6

Only leakage gates, because leakage is the platform's claim. Answer quality is not, so holding the build hostage to a retrieval score would be gating the wrong thing.

Leakage is checked two independent ways, because the risk is one mechanism failing silently. They catch different things:

  1. Chunk ownership. Every retrieved chunk's tenant_id equals the caller's. The authoritative check. Catches a retrieval breach.
  2. Forbidden terms. None of the other law's vocabulary (Commissioner, DIFC / Bureau, Executive Regulations) appears in the answer. Catches the case where retrieval was clean but the model leaked from pretrained knowledge, which check 1 cannot see because no chunk crossed.

Check 2 skips terms already present in the question. A trap question deliberately uses the other law's vocabulary, so a correct refusal quotes those terms back, and flagging that would score the ideal behaviour as a leak. Only vocabulary the model introduced itself counts as evidence. This was found by the first real-model run, which flagged trap-executive-regs-asked-by-b as a false positive.

The question set includes cross-tenant traps, asking tenant A a question only DIFC answers. The correct behaviour is refusal, not a DIFC answer. These are never trimmed from the set.

gold_article_hit_rate went from 1/6 with HashEmbedder to 6/6 with real bge-m3, and 1/6 is chance. The metric only became meaningful on the cluster, which is exactly why it was reported and never gated.


Known limitation

Qdrant OSS has a single instance-wide API key; per-collection authorization is not first-class. The tenant boundary is therefore enforced by the application and NetworkPolicy, not by the vector store. A compromised tenant-A pod could reach tenant-B's collection.

Closing it properly means Qdrant JWT collection-scoped tokens, or one Qdrant instance per tenant once the tenant count justifies the cost. It is documented rather than hidden because knowing where your boundary isn't is part of owning it.


Repository layout

terraform/     AKS (3 pools), GPU Operator, resource group
k8s/           Namespaces, RBAC, Secrets, NetworkPolicies, Ingress, workloads
app/           FastAPI RAG service: /ingest, /query, /healthz, /audit
corpus/        Normalised legal texts (## Article N)
eval/          questions.yaml + run_eval.py
scripts/       ingest.py, demo.sh, verify-eval-isolation.sh
docs/          IMPLEMENTATION-PLAN.md, instance_math.md, diagrams/ (architecture as code)

Status: built, verified on real hardware, torn down

Complete as scoped. The platform ran end to end on AKS with a real T4, real bge-m3 embeddings and a real Qwen2.5-7B-AWQ, passed every isolation proof, and was then destroyed. The cluster no longer exists; nothing is billing.

Component State
Terraform (AKS 3 pools, GPU Operator, Calico, ACR) ✅ applied
Image built linux/amd64, pushed to ACR ✅ pods ran v3
Corpus normalisation (PDPL 31 articles, DIFC 65) ✅
Data plane (Qdrant, TEI, vLLM) ✅ all Running
RAG service (/ingest, /query, /healthz, /audit) ✅
Ingest against the cluster ✅ 31 + 65 points, real bge-m3, 1024 dims
RBAC / Secrets / NetworkPolicy ✅ applied and enforced
ingress-nginx + cert-manager, HTTPS per tenant ✅
scripts/demo.sh ✅ all 8 blocks pass
scripts/verify-eval-isolation.sh ✅ 7/7 pass
eval/run_eval.py against real models ✅ leakage 0, hit rate 6/6
Infrastructure 🗑️ destroyed: resource group, PVCs, ACR, LoadBalancer

The isolation proofs that passed

=== 1. control plane: tenant-a cannot read tenant-b's secrets     PASS
=== 2. control plane: get=yes list=no                             PASS
=== 3. network: cross-tenant traffic dropped                      PASS
=== 4. data plane: each tenant retrieved only its own corpus      PASS
=== 5. data plane: spoofed X-Tenant rejected with 403             PASS
                   rejection written to the audit log             PASS
=== 6. evaluation gate: leakage_rate = 0                          PASS

The demo, which is the platform's whole claim, measured

Same question, two tenants, two legal regimes:

Tenant A Tenant B
Corpus UAE Federal Decree-Law 45/2021 DIFC DP Law No. 5 of 2020
Article cited 9 41
Regulator named Bureau Commissioner
Chunks returned all tenant-a all tenant-b
Gold article rank 1 1

End-to-end query: 200 in 5.6s, grounded answer, correct citation.

Plus: a cross-tenant trap (tenant A asked a DIFC-phrased question) answered from PDPL only, laws cited: {'UAE PDPL'}; a spoofed X-Tenant → 403 with an audit row showing retrieved_article_ids: [], refused before any search ran, question stored only as question_sha256; RBAC → no/yes/no; network → URLError reaching rag.tenant-b while qdrant, tei and vllm stayed reachable and the query still returned PDPL Art. 9.

Roadmap

The next items, each with its reasoning, threshold and ordering, are in docs/ENHANCEMENTS.md. The highest-value one needs no cloud credentials at all: the stub providers turn the isolation boundary into a ~40s merge gate in CI.

What it cost, and the lesson

~$40 against a $10 budget, 4× over. Almost none of it bought progress: TEI crash-looped ~11h before anyone looked, and vLLM sat idle-but-broken for 37h while passing a /health probe that ran no inference. The productive work took about two hours.

The transferable lesson is the health check: a readiness probe that exercises no inference proves nothing about a model server. The meter ran on a dead engine for a day and a half. Operationally, the rule that came out of it is if a pod is not Ready in 15 minutes, scale the GPU pool to zero and debug the manifest offline, because you do not pay to stare at a CrashLoopBackOff.


Running it

cd terraform && terraform init && terraform apply

az aks get-credentials -g rg-sovereign-rag -n sovereign-rag --overwrite-existing
kubectl get nodes -o wide            # gpu node Ready, containerd 1.7.x

kubectl apply -f k8s/            # namespaces, qdrant, tei, vllm, tenants, policies

# ingest both corpora. Idempotent, run through each tenant's own endpoint
uv run python scripts/ingest.py corpus/processed/uae-pdpl.md --law "UAE PDPL"    --key key-a
uv run python scripts/ingest.py corpus/processed/data-protection-law.md \
                                                --law "DIFC DP Law" --key key-b

bash scripts/demo.sh                      # 8 blocks: the two-tenant story end to end
bash scripts/verify-eval-isolation.sh     # the 7 isolation proofs
uv run python eval/run_eval.py            # leakage_rate must be 0

Locally, with no cluster and no GPU

With no TEI_URL/VLLM_URL, app/main.py falls back to HashEmbedder + FixtureGenerator. The tenant filter runs identically, so the authoritative leakage check is fully meaningful locally. Only ranking and answer text are not.

docker start qdrant 2>/dev/null || docker run -d --name qdrant -p 6333:6333 qdrant/qdrant
uv run uvicorn app.main:app --port 8000
Signal Local (stubs) Cluster (real models)
leakage_rate chunk-level check ✅ meaningful ✅
forbidden-terms check ❌ inert ✅
gold_article_hit_rate ❌ chance (1/6) ✅ (6/6)

Teardown

Already run, so this infrastructure no longer exists. Kept here because the cost shape is the reusable part.

The GPU node is ~60% of the burn. Scale it to zero between sessions; destroy everything when done.

az aks nodepool scale -g rg-sovereign-rag --cluster-name sovereign-rag --name gpu --node-count 0
cd terraform && terraform destroy

Then confirm, because a forgotten LoadBalancer or managed disk keeps billing after the cluster is gone:

az aks list -o table                    # expect empty
az group list -o table | grep sovereign # expect nothing

Two traps worth knowing:

  • kubectl delete statefulset does not remove volumeClaimTemplates PVCs. Only destroying the resource group does.
  • The LoadBalancer and its public IP outlive kubectl delete on the Service if the deletion half-fails, and neither shows up in kubectl get.

Cost: ~$1.07/hr warm, ~$0.42/hr with the GPU pool at zero. Against a $10 budget that is ten hours of wall-clock time including model downloads. See the cost retrospective in docs/P10-STATUS.md for how this project spent $40 of it, and the two rules that came out of that.

About

A Sovereign RAG app with self-hosted LLM & tenant isolation on Azure

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages