Deploying Open-Source LLM APIs: From GPU Memory to Load Testing
A practical guide to taking an open-source large language model from a working process to a stable API service. It covers capacity goals, weight and KV cache memory estimates, startup parameters, mixed-GPU scheduling, RAG ingestion, gateway rate limits and metering, security controls, load testing, and staged rollout with rollback.
1. Define the service goal before you choose a stack
Getting a model to start is only the first step. If business systems will call it over the long term, answer a few questions first: peak concurrency, target time to first token and end-to-end latency, the longest context per request, and whether the data includes personal information or internal sensitive content. Those answers drive GPU count, where the service runs, and audit requirements.
| Dimension | Questions to confirm | Effect on the decision |
|---|---|---|
| Workload | Daily call volume, peak concurrency, and whether traffic clusters in certain hours | GPU count and whether an elastic pool is needed |
| Latency targets | Time to first token and end-to-end P95 latency | Model size and batching parameters |
| Context length | Maximum tokens for input plus output | KV cache memory directly |
| Data classification | Personal information, confidential data, or internal data | Whether a public cloud is acceptable, and what audit is required |
| Operations | People who can operate GPUs and respond to failures | Self-hosted, managed, or an appliance |
Whether on-premises deployment pays off depends on utilization. When GPUs stay busy, cost per call can be lower than pay-as-you-go public API pricing. With light or short-lived use, the opposite can be true. Include hardware depreciation, power, data center and bandwidth, operations labor, and model upgrade cost, and compare that total with real invoices. Comparing single-GPU list price alone is usually misleading.
2. Memory estimates and deployment checks
2.1 Weight memory
A rough estimate is: weight memory ≈ parameter count × bytes per parameter. BF16 is 2 bytes per parameter, FP8 is 1 byte, and INT4-class quantization is about 0.5 bytes, often a bit higher because of group scaling. For a 671B-parameter MoE model:
| Weight precision | Bytes per parameter | Estimated weight memory | Notes |
|---|---|---|---|
| BF16 | 2 | About 1.3 TB | Needs a multi-node cluster |
| FP8 | 1 | About 670 GB | Confirm the inference stack supports the format |
| INT4-class quantization | About 0.5 | About 350 GB | Varies with the quant scheme and group size |
These figures are order-of-magnitude estimates. They exclude KV cache and runtime overhead. Before deployment, check the official model card and framework documentation.
2.2 KV cache memory
KV cache grows with concurrency and context length and is often the part high-concurrency deployments miss. For standard multi-head or grouped-query attention:
KV cache memory ≈ concurrent requests × average context length × layers × 2 × KV heads × head_dim × bytes per element
The factor of 2 is the separate K and V caches. Example: 60 layers, 8 KV heads, head_dim 128, BF16. Each token is about 2 × 60 × 8 × 128 × 2 = 245,760 bytes, roughly 240 KB. With 16 requests in flight and 32,768 tokens of context each, KV cache is about 16 × 32,768 × 245,760 ≈ 1.29 × 10^11 bytes, or about 120 GiB.
This is only a worked example. Use the model’s official config for real values. Compressed attention such as MLA uses a different conversion; follow the official description. Total memory must cover weights, KV cache, activations, and framework overhead, plus headroom for fragmentation.
2.3 Startup parameters and risks
Record the environment before you deploy: exact inference framework version, CUDA and driver versions, GPU model and memory per card, interconnect, weight source and checksum, and quantization format.
The command below is an example. Replace every placeholder for the real environment and validate it in a test environment first.
# Example only. Replace and validate every argument for your environment.# Take quantization settings from this model's official docs, not from another model.python -m vllm.entrypoints.openai.api_server \--model /data/models/<your-model-dir> \--tensor-parallel-size <GPU count> \--max-model-len <set from the workload> \--max-num-seqs <set from load tests> \--gpu-memory-utilization 0.85 \--host 127.0.0.1 \--port 8000
| Parameter | Role | Starting point | Risk |
|---|---|---|---|
| —tensor-parallel-size | GPUs used for tensor parallelism | Number of GPUs in one high-speed interconnect domain, and a divisor of the attention head count | Cross-node parallelism adds network latency and can cut throughput sharply |
| —gpu-memory-utilization | Fraction of each GPU that vLLM may use | Start at 0.85 and raise only after stable load tests | 0.90 can OOM under high concurrency or long context; leave room for activations and fragmentation |
| —max-model-len | Maximum context length | Set to what the workload needs, not the model maximum | Larger values consume more KV cache and reduce concurrency |
| —max-num-seqs | Cap on sequences processed together | Set from load-test results | Too high exhausts memory; too low queues requests |
| —quantization | Quantization method | Follow the model’s official documentation | A mismatch with the weights can fail to load or degrade accuracy |
| —host / —port | Bind address and port | Bind to an internal address and reach it through the gateway | Exposing the port on the public internet raises abuse risk |
Suggested staged checks: load the same weights and checksum in a test environment; compare outputs on a fixed question set; send 5% of production traffic and watch at least one full business cycle before expanding.
3. Scheduling mixed GPU generations
Data centers often mix GPU generations. Scheduling rules:
- Split pools by model and memory class: large models, small models and embeddings, and rerankers.
- Keep every GPU for one model instance inside the same high-speed interconnect domain.
- Do not put cards with different memory sizes in one tensor-parallel group. The group is limited by the smallest card.
- If several models share a card, load-test interference. Average utilization is not enough.
| Metric | Meaning | Alert guidance |
|---|---|---|
| GPU utilization | How busy the compute units are | Sustained low utilization may justify scale-in; judge it against the workload |
| Memory watermark | Used memory over total memory | Investigate if it stays above 90% |
| Queue time | How long a request waits before inference | Alert when it exceeds half the latency target |
| Time to first token | Time from request arrival to the first output token | Set from the SLO |
| Instance health | Health-check result | Remove the instance from routing after consecutive failures |
Failover: drop instances that fail health checks in a row; return 503 or 429 when queue time expires; if you fall back to a smaller model, the application must tell the caller. Do not swap models silently.
4. RAG data ingestion
RAG quality and safety both depend on how data is ingested:
- Collect: list sources, an owner for each, and how often it changes.
- Clean and redact: drop headers, footers, and duplicates. Redact fields such as national ID numbers and phone numbers before indexing.
- Chunk: split on semantic paragraphs. Start with 300 to 600 tokens and 10% to 15% overlap between neighbors.
- Embed and store: keep vectors with the source text. Metadata should record source, update time, classification, and which roles may read it.
- Retrieve: filter candidates by the user’s permissions first, then run vector search. Start with top_k of 5 to 10.
- Rerank and assemble: a reranker is optional. Pass retrieved text as data in the prompt and cite the source.
| Parameter | Starting value | Notes |
|---|---|---|
| Chunk size | 300 to 600 tokens | Too large dilutes key facts; too small drops context |
| Overlap | 10% to 15% | Reduces breaks at chunk boundaries |
| top_k | 5 to 10 | Higher values lengthen the prompt and raise cost and latency |
| Similarity threshold | Set from a validation set | Drop hits below the threshold |
| Incremental refresh | Match how fast the source changes | Sets how current the knowledge is |
Permission filters must run at retrieval time, not only after generation. Otherwise unauthorized text can already be in the prompt. Retrieved documents are untrusted input and may contain instructions meant to change model behavior. Keep the system prompt and document text separate.
Acceptance checks: Recall@k and citation accuracy on a labeled question set; zero results on unauthorized-access tests; after a knowledge update, new content is retrievable within the agreed time.
5. Gateway limits, metering, and request caps
The gateway handles authentication, rate limits, routing, metering, and audit. Set limits from inference-pool capacity. The numbers below are starting points and should be revised after load tests.
| Parameter | Scope | Starting value | Notes |
|---|---|---|---|
| RPM | Per API key | Set from the workload, for example 60 | Requests per minute |
| TPM | Per API key | Set from the workload | Input plus output tokens per minute; tracks compute better than RPM |
| Concurrency cap | Per tenant | From pool capacity | Requests in flight at once |
| max_tokens cap | Per request | For example 2048 | Stops one request from filling GPU memory |
| Request timeout | Global | Based on P99, with margin | Release inference resources when the timeout fires |
| Input length cap | Global | Match —max-model-len | Reject requests over the cap |
Rate limiting is usually a token bucket. Over-limit requests return HTTP 429 with a Retry-After header.
Meter from the usage field returned by the inference service: prompt_tokens and completion_tokens. Write metering records asynchronously with caller, model, time, both token counts, and request ID. Streaming responses may omit usage; enable the option that returns it, or count tokens at the gateway. Reconcile metering with inference logs daily and alert when the gap exceeds the agreed ratio. Confirm the pricing rules before you bill externally. Do not write API keys to logs.
6. Security and compliance
- Authentication: a separate API key per caller, with rotation and revocation. Keep admin APIs separate from inference APIs.
- Transport: HTTPS on every external entry, TLS 1.2 or newer. Encrypt internal links as well when you can.
- Network: only the gateway may reach the inference service. Tighten security groups by port and source address.
- Logs: record caller, time, model, token counts, and status code. Whether prompts and raw outputs are stored, for how long, and how they are redacted depends on data classification.
- Prompt injection: treat user input and retrieved documents as data. Do not execute instructions inside them. Allow-list tool calls.
- Output: filter output that includes personal or confidential data, and sample it for human review on a schedule.
- Compliance: apply the privacy, cybersecurity, and generative-AI rules of each jurisdiction where the service is offered. For services in mainland China, that includes the Cybersecurity Law, the Data Security Law, and the Personal Information Protection Law, plus whether the interim measures for generative AI services apply and whether filing or a security assessment is required. Legal or compliance staff should confirm the launch scope.
7. Load-test checklist
Cover these cases:
| Scenario | How to design it | What to watch |
|---|---|---|
| Short Q&A | About 200 input tokens and 200 output tokens | Throughput and time to first token |
| Long context | Input near —max-model-len | OOM and memory watermark |
| Mixed load | Short and long requests in the production mix | Queue time and fairness across request types |
| Spike | Raise concurrency in steps | Where rate-limit hits and error rate bend |
| Soak | At least 2 hours | Memory fragmentation growth and latency drift |
Raise load one step at a time, hold each step for at least 10 minutes, and record every metric. After you find the knee, use concurrency near that knee as the ceiling and leave margin for the production starting point.
Before go-live, check each item and keep a test record or an owner sign-off:
- P95 time to first token is within the SLO.
- P95 end-to-end latency is within the SLO.
- Error rate is at or below the agreed threshold.
- No OOM during the full load test.
- Peak memory watermark stays under the cap, with margin.
- Rate limits return 429 and a Retry-After header.
- Metering reconciles with inference logs inside the agreed error band.
- A rollback drill has passed.
8. Staged rollout and rollback
Roll out in stages: 5% of traffic for at least one business cycle, then 20%, then 50%, then 100%, and only after metrics are stable. At each stage, recheck the items above.
| Trigger | Example threshold | Action |
|---|---|---|
| Error rate rises | Above the agreed threshold for 5 minutes straight | Gateway routes back to the previous version |
| P95 latency misses the SLO | Over the SLO for 10 minutes straight | Lower the concurrency cap first; roll back if that does not help |
| OOM | Any single instance OOMs | Remove that instance and revert its config |
| Bad outputs | A fixed question set regresses clearly | Switch back to the previous model version |
Rollback rules: keep the previous instances running until the new stage is stable; version both model config and gateway routes; do not delete logs or metering data during rollback; do not hand-edit production parameters during an incident, and record every change. Drill the rollback path so on-call staff can follow it.
