A security review of an internal "AI assistant" pilot finds three things nobody planned for. Support agents have been pasting full customer tickets, including names, addresses and order histories, into a hosted chat model. The same tickets are being embedded by a third-party API to power search. And the application's own debug logs, which engineers ship to a hosted observability vendor, contain every prompt and every completion verbatim. No one did anything malicious. Each step was a reasonable shortcut, and together they sent a copy of the company's most sensitive text to three outside parties.
The natural reaction is "we will run the model ourselves." That is a sound instinct, but it is only the start of the work. Running open-weight weights on your own GPUs removes one egress path, the call to a model provider, and leaves a dozen others: the package manager that fetches weights at startup, the inference server's usage reporting, the log pipeline, the vector database, the browser tool an agent can call, and the humans who copy output into email. This article walks through what "zero data egress" actually requires, how to build it, what it costs in capacity and effort, and when you should not attempt it.
1. What "data egress" means for an LLM system
Before choosing hardware, write down every place data can leave. An LLM application is not one box. It is a chain, and each link can copy your data somewhere else. A useful threat model lists the data classes first and the channels second.
The data classes are broader than "the prompt." They include the system prompt (often containing business rules you consider confidential), retrieved documents injected into context, user input, model output, tool-call arguments and results, embeddings (which can often be partially inverted back to text and should be treated as sensitive as the source), conversation history, and fine-tuning datasets.
The channels are where the surprises live:
- Model API calls. The obvious one. Prompts and completions go to the provider, subject to its retention and training terms, which you must read rather than assume.
- Embedding and rerank APIs. Easy to forget because they feel like "just search," but they receive your whole document corpus.
- Telemetry. Some inference servers, SDKs and developer tools report anonymous usage statistics by default. Usually opt-out is a single environment variable, but you have to know to look.
- Logs and traces. Application logs, APM spans and error trackers frequently capture request bodies. This is the most common real-world leak.
- Weight and package downloads. A server that resolves a model from a public hub at startup both depends on the internet and tells the hub what you run.
- Agent tools. Web fetch, code execution with network access, and email or chat connectors are egress channels you handed to a model.
- Backups and support bundles. A crash dump sent to a vendor can contain GPU memory contents, which include prompts.
"Zero egress" is therefore a property you enforce at the network layer and verify by test, not a property you obtain by purchasing a product. The rest of the article follows that logic: shrink the surface, deny by default, and prove the denial.
2. Deployment models, and what each one actually protects
There is a spectrum between "call a hosted API" and "air-gapped cluster in our own datacenter," and the middle options are often the right answer. The table compares qualitative properties only, because the right choice depends on your contracts, regulators and team.
| Option | Where prompts are processed | What you control | Main residual risk | Operational burden |
|---|---|---|---|---|
| Hosted API under standard terms | Provider infrastructure | Contract and data-handling terms only | Retention, subprocessors, jurisdiction | Lowest |
| Hosted API with zero-retention or regional terms | Provider infrastructure, restricted region | Contract, region, sometimes encryption keys | Provider staff or incident access, abuse monitoring exceptions | Low |
| Open weights in your cloud account (private network) | Your VPC, your GPUs | Network, identity, logging, weights | Cloud operator trust, misconfigured egress | Medium |
| Open weights on-premises with outbound allowed | Your datacenter | Everything above plus hardware | Update and telemetry channels you forgot to close | High |
| Air-gapped on-premises | Your datacenter, no route out | Everything, including every artifact that enters | Supply-chain content you carry in, slow updates | Highest |
Two points deserve emphasis. First, the jump in protection between rows is smaller than the jump in cost, so choose the weakest row that satisfies your actual obligation. A hosted API with a signed zero-retention agreement is acceptable to many regulated teams; a few cannot accept any third-party processing at all. Second, self-hosting changes who is accountable, not whether the data is safe. A misconfigured on-premises cluster with a permissive firewall is worse than a well-run hosted service.
3. Building the serving path
The components
A minimal self-hosted stack has four parts. An inference server loads the weights and exposes a completion endpoint; common open choices include vLLM, llama.cpp's server, Hugging Face Text Generation Inference and SGLang. A gateway sits in front, authenticates callers, applies rate limits and quotas, and is the single place that writes audit records. An internal model registry holds the approved weight files. Application services, retrieval stores and agents sit behind the gateway and never talk to the inference server directly.
Putting the gateway in front matters for security more than for convenience. It lets you swap the model without touching clients, it gives you one choke point for redaction and logging policy, and it means the inference server can live on a network segment that accepts connections from exactly one source.
Deny egress by default
The enforcement lives in the network. On Kubernetes, begin with a default-deny policy for the namespace that holds inference workloads, then allow only the paths you can justify. The manifest below denies all outbound traffic from the inference pods except DNS to the cluster resolver and connections to the internal registry. Note that NetworkPolicy semantics depend on your CNI plugin enforcing them, so test it rather than trusting it.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: inference-egress-allowlist
namespace: llm-serving
spec:
podSelector:
matchLabels:
app: inference
policyTypes:
- Egress
egress:
# Cluster DNS only
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
# Internal model registry (weights are pulled from here, never from the internet)
- to:
- ipBlock:
cidr: 10.20.30.0/28
ports:
- protocol: TCP
port: 443
---
# Container environment: fail loudly instead of reaching out
# HF_HUB_OFFLINE=1 do not contact the public model hub
# TRANSFORMERS_OFFLINE=1 same, for the transformers library
# DO_NOT_TRACK=1 honored by several tools as an opt-out signal
# VLLM_NO_USAGE_STATS=1 opt out of vLLM usage reporting (check your version's docs)
The environment variables are a second layer, not the defense. They stop well-behaved software from trying; the network policy stops software that tries anyway. Check each tool's current documentation for its exact opt-out setting, because these names change between releases.
Prove the denial
Treat "no egress" as a test that runs in continuous integration and again on a schedule in production. From inside an inference pod, attempt connections to a public IP, a public hostname, the cloud metadata endpoint and an external DNS resolver. Every one should fail. Also run the full request path with a packet capture on the node and confirm that the only destinations are the ones in your allowlist. Many teams discover a stray call this way: a tokenizer that fetches a vocabulary file, a health check that pings a vendor, a library that checks for updates.
4. Supply chain: weights are code
Model files are an untrusted input that your GPUs will execute against. The risks are concrete and well documented in the open-source community.
- Serialization format. Python pickle-based checkpoints can execute arbitrary code when loaded. The safetensors format stores raw tensors and was designed to avoid this. Prefer safetensors, and treat any pickle checkpoint as untrusted code. GGUF is a tensor container used by llama.cpp; it does not execute code by design, but the loader is still software that parses attacker-controlled bytes, so keep it patched.
- Custom code in the repository. Some model repositories ship Python modules that a loader runs when you enable "trust remote code." Do not enable that flag against a public repository. If a model needs custom code, read it, vendor it, and pin it.
- Provenance and integrity. Record the source, revision and SHA-256 of every weight file at the time a human approved it. The serving environment should refuse any file whose hash is not on the approved list.
- Behavioral risk. Weights from an unknown publisher may have been tuned to misbehave on specific triggers. Evaluate on your own test set before promotion, and prefer publishers with an established record.
- Licence. "Open weights" does not mean open source. Licences differ on commercial use, user-count thresholds, naming and acceptable-use restrictions. Have counsel read the specific licence for each model you ship.
The workflow that follows is an import pipeline. A connected, quarantined machine downloads the artifact, verifies the publisher's checksum, scans and loads it in a sandbox, runs your evaluation set, and then copies the approved file to the internal registry. For an air-gapped site, the registry is populated by physical media or a one-way transfer with the same checks on the receiving side. The inference cluster itself never initiates a download.
5. Identity, logging and the data you create yourself
Once egress is closed, the largest remaining risk is internal: who can read the prompts you now store. Treat prompts and completions as the sensitive records they are.
Logging policy
Decide explicitly what gets logged at the gateway. A common safe default is to log metadata (caller identity, model, token counts, latency, status, a request ID) and not the content. When content logging is necessary for debugging or evaluation, write it to a separate store with its own access controls and a short retention period, and redact known sensitive patterns before it is written. Make sure the metadata path and the content path cannot be accidentally merged by a log shipper.
Access control and tenant isolation
Authenticate every caller to the gateway with workload identity, not a shared API key pasted into configuration files. If several teams or customers share the cluster, isolate their data: separate retrieval indexes, separate caches, and care with features that share state across requests. Prompt prefix caching, for example, is a performance feature that reuses computed attention state across requests with an identical prefix; it must be scoped per tenant so one tenant's prompt can never be a cache hit for another, and timing differences cannot reveal that a prefix was seen before.
Agents widen the surface
If the model can call tools, then prompt injection, where text in a retrieved document or web page tries to instruct the model, becomes an exfiltration route: the injected text asks the agent to send secrets to an attacker-controlled URL. Closing the network at the pod level helps, but only if the agent's tool executor is also confined. Give each tool the least privilege it needs, route all fetches through an allowlisting proxy, require approval for actions that write or send, and keep untrusted content out of the same context as secrets whenever possible.
6. Capacity: what the hardware actually has to hold
Self-hosting fails most often on a planning error rather than a security error: the model does not fit, or fits with no room for concurrent users. Two memory consumers matter, and you can estimate both with arithmetic before buying anything.
Weights
Weight memory is roughly the parameter count times the bytes per parameter. A model with 8 billion parameters stored in 16-bit floating point needs about 16 GB for weights alone. With 8-bit quantization it needs roughly half that, and with 4-bit quantization roughly a quarter, plus some overhead for scales and higher-precision layers. A 70-billion-parameter model needs about 140 GB at 16 bits, which means several accelerators sharing the model through tensor parallelism, or about 35 GB plus overhead at 4 bits.
KV cache
During generation, the server keeps keys and values for every token of every active sequence so it does not recompute them. The per-token cost is 2 (keys and values) times the number of layers, times the number of key-value heads, times the head dimension, times bytes per element. Take an illustrative 8B-class model with grouped-query attention: 32 layers, 8 KV heads, head dimension 128, 16-bit cache. That is 2 × 32 × 8 × 128 × 2 bytes, which is 131,072 bytes, or 128 KiB per token. A single 8,192-token conversation therefore holds about 1 GiB of cache, and 32 concurrent conversations of that length hold about 32 GiB, more than the weights themselves.
The planning lesson is that concurrency and context length, not parameter count alone, determine how many GPUs you need. Cutting the maximum context, quantizing the cache, or choosing a model with fewer KV heads each trade quality or capability for capacity. Your real numbers come from measuring your own prompts, because prompt length distributions vary enormously between a chat assistant and a document-summarization pipeline.
Serving shape
Modern inference servers use continuous batching, which admits new requests into a running batch at every step, and paged cache management to waste less memory on fragmentation. Both raise throughput substantially compared with naive serving, but they raise the importance of a proper load test with realistic prompt and output lengths. Measure time to first token, tokens per second per user, and behavior under overload. Decide in advance whether the gateway queues, sheds or rejects excess load, because an unbounded queue turns a traffic spike into a timeout storm.
7. A worked example: ticket summarization with no egress
Return to the support scenario. The goal is to summarize customer tickets for agents without any ticket text leaving the company network.
- Classify the data. Tickets contain names, contact details and payment references. The commitment to customers is that these never go to third parties. That justifies self-hosting; a redaction-only approach would still leave order histories in prompts.
- Pick a model by task, not by headline. Summarization of short documents rarely needs the largest model. Start with a mid-size open model, evaluate it against a few hundred hand-labeled tickets, and only move up if quality is insufficient.
- Size memory. Take a mid-size model in 8-bit, estimate weights, add KV cache for your expected concurrent agents times ticket length, and add headroom. Run the load test described above.
- Close the network. Deploy with the default-deny policy, an internal registry, offline flags, and a gateway that logs metadata only.
- Replace the other leaks. Switch embeddings to a self-hosted embedding model, point the vector store at internal storage, and redirect application logs away from the hosted observability vendor, or strip the content fields before shipping.
- Run the egress test. From inside every component, attempt external connections and confirm they fail. Capture traffic during a full ticket flow and confirm only allowlisted destinations appear.
- Write the runbook. Document how to import a new model version, how to rotate credentials, how to respond if a prompt leak is suspected, and who owns each of those.
Notice that the model choice is one step of seven. Most of the work is plumbing and verification, which is why a team that budgets only for GPUs underestimates the project.
8. When not to self-host
Self-hosting is the wrong decision more often than its advocates admit. Skip it, or postpone it, when any of the following is true.
- The data is not actually sensitive, or a contractual zero-retention hosted option already meets your obligation.
- You need frontier-level capability on hard reasoning or coding tasks and the best open weights available to you do not meet your evaluation bar. A weaker model that is private is not useful if the output is wrong.
- Volume is low or bursty. Idle GPUs cost money, and a small team will spend more on engineering time than on a hosted bill.
- You have no one to operate it. Patching serving software, rotating credentials, monitoring GPU health and re-importing models are ongoing duties.
- Your threat model is dominated by insiders or endpoint compromise, which self-hosting does not address.
A reasonable hybrid is a router at the gateway that sends sensitive classes of request to the local model and non-sensitive ones to a hosted model. The routing decision itself must be deterministic and auditable, for example a classifier plus rules, because a misroute is the same as a leak.
9. Decision checklist, common mistakes and what to do Monday
Checklist
- Which data classes and which legal or contractual obligations apply?
- Is every channel in section 1 either closed or consciously accepted?
- Is egress denied by network policy, and is there an automated test proving it?
- Are weights in a safetensors or equivalent non-executing format, hashed, and pulled only from the internal registry?
- Does the gateway log metadata by default, with content logging separate, redacted and short-lived?
- Are caches and indexes isolated per tenant?
- Has capacity been sized from measured prompt lengths and concurrency, with a load test?
- Does an evaluation set gate every model change?
Common mistakes
- Self-hosting the model while still sending embeddings, logs or traces to a third party.
- Relying on environment variables for "offline" instead of a network control.
- Enabling remote-code loading to get a model working quickly and never revisiting it.
- Giving an agent unrestricted outbound web access inside an otherwise sealed network.
- Sizing the cluster by parameter count and discovering at launch that the KV cache does not fit.
- Treating the first deployment as finished, with no process for importing patched weights or serving software.
What to do Monday
- List every system that touches a prompt, an embedding or a completion, and mark which are outside your network.
- Turn on a default-deny egress policy in a staging copy of your current deployment and see what breaks. That list is your real dependency map.
- Grep your logging configuration for request and response bodies.
- Pick one low-risk workload, run it on an open model behind a gateway, and measure quality against your current provider on the same test set.
Questions teams ask
Does self-hosting guarantee compliance? No. Compliance depends on controls, evidence and process. Self-hosting gives you the ability to implement them; it does not implement them for you.
Are open models as good as hosted frontier models? It depends on the task and changes quickly. Evaluate on your own data and re-evaluate when new releases appear, rather than relying on public leaderboards.
Can we fine-tune on private data? Yes, and the same egress rules apply to training jobs, datasets and checkpoints. Fine-tuned weights can memorize training text, so treat them as being as sensitive as the data they were trained on.
Is a private cloud account good enough? Often, if your obligation allows trusting the cloud operator. It removes the model provider from the path while keeping elastic capacity, at the cost of relying on the network controls described above.