To build your own LLM API, serve an open model with vLLM on a GPU, bound to localhost, then put a small gateway in front that checks per-user API keys, rate-limits and logs token usage. Add TLS with Caddy or a tunnel. Clients use the standard OpenAI SDK with your base URL and key.
- Model server
- vLLM: OpenAI-compatible /v1/chat/completions, /v1/completions, /v1/models
- Built-in auth
- vLLM --api-key accepts a static key; per-user keys need a gateway
- Client change
- Set base_url (or OPENAI_BASE_URL) and the API key; no other code changes
- Monitoring
- vLLM exposes Prometheus metrics at /metrics and a /health check
- Example capacity
- Qwen3 32B AWQ on one L40S: roughly 300 tokens/s total under load (assumption)
- Always-on cost on an H100
- 730 hours × hourly price; business hours only is about 30% of that
An OpenAI-compatible API in front of an open model gives you the developer experience of a hosted API: the same SDKs, streaming and tool calling. You also keep the things a hosted API cannot give you: your choice of model, prompts that stay on your own GPU, and a cost that does not grow with every token. This guide builds that API step by step. It covers vLLM as the engine, a small gateway for per-user keys, rate limits and usage logs, TLS, monitoring and scaling.
The code is complete and copy-pasteable. It assumes Ubuntu with NVIDIA drivers, Python 3.10+, and recent releases of vLLM, FastAPI and httpx. For how serving works underneath, read the complete guide to LLM inference.
What does a production LLM API need?
Six components, most of them small: a model server, a gateway, TLS, process supervision, monitoring and usage accounting. vLLM handles the hard part; the rest is ordinary web plumbing.
client (OpenAI SDK)
│ HTTPS, Bearer key
▼
TLS proxy (Caddy) or tunnel ──► gateway :9000 (keys, rate limits, usage log)
│ HTTP, localhost only
▼
vLLM :8000 (model on the GPU)| Component | Job | What we use here |
|---|---|---|
| Model server | Batching, KV cache, OpenAI-compatible routes | vLLM |
| Gateway | Per-client keys, rate limits, usage logging | ~80 lines of FastAPI |
| TLS | Encrypt traffic, give a stable hostname | Caddy, or a Cloudflare tunnel |
| Supervision | Restart on crash or reboot | systemd, or tmux |
| Monitoring | Queue depth, KV cache use, errors | vLLM /metrics and /health |
| Accounting | Tokens per client | SQLite table written by the gateway |
Option 1: How do you get an LLM API without building one?
If you just need the endpoint, Wandering Giants Compute serves it for you. Pick a GPU and API mode, choose a one-click model (Llama 3.3 70B FP8, Qwen3, DeepSeek R1 Distill Qwen 32B, gpt-oss and others) and launch. You get an OpenAI-compatible base URL served by vLLM and your own key. The values below are placeholders for the ones in your dashboard.
export WG_BASE_URL="https://YOUR-ENDPOINT/v1"
export WG_API_KEY="your-key"
curl -s "$WG_BASE_URL/models" -H "Authorization: Bearer $WG_API_KEY"Existing code that uses the OpenAI SDK changes one line, the base URL. The Python SDK also reads it from the environment:
export OPENAI_BASE_URL="$WG_BASE_URL"
export OPENAI_API_KEY="$WG_API_KEY"
python your_existing_app.py # no code changes if it uses OpenAI() with defaults// Node.js (openai package)
import OpenAI from "openai";
const client = new OpenAI({ baseURL: process.env.WG_BASE_URL, apiKey: process.env.WG_API_KEY });Remember to change the model name to the ID returned by /models. If you need several client keys, rate limits or usage per customer, put the gateway from Step 3 in front of this endpoint by setting UPSTREAM to it.
Option 2: How do you build the API yourself?
With root access to a GPU machine, the build is five steps: pick the model, run vLLM as a service, add the gateway, add TLS, then monitor. Allow about an hour, most of it waiting for downloads.
Step 1: Pick a model and GPU
Size the GPU for the weights plus KV cache for your expected concurrency. The GPU memory guide for LLMs has the formulas.
| API for... | Model | GPU | Why |
|---|---|---|---|
| Classification, extraction, routing | Qwen/Qwen3-8B (FP8 on load) | RTX 4090 | Cheap, fast, high throughput |
| General assistant and agents | Qwen/Qwen3-32B-AWQ | L40S | Strong quality, tool calling, lots of KV room |
| Highest quality open chat | RedHatAI/Llama-3.3-70B-Instruct-FP8-dynamic | H200 or RTX PRO 6000 | 70B with room for many users |
| Reasoning | deepseek-ai/DeepSeek-R1-Distill-Qwen-32B (FP8 on load) | H100 | Separate reasoning output via parser |
The rest of this guide uses Qwen3 32B AWQ on an L40S. Swap the model ID for any other; the Qwen tutorial covers its flags in detail.
Step 2: Run vLLM as a service on localhost
Install vLLM in a virtual environment:
ssh root@<your-gpu-address>
python3 -m venv ~/vllm-env && source ~/vllm-env/bin/activate
pip install -U pip && pip install -U vllmCreate /etc/systemd/system/vllm.service. vLLM listens only on 127.0.0.1, so nothing reaches it except through the gateway:
[Unit]
Description=vLLM OpenAI-compatible server
After=network-online.target
[Service]
Environment=HF_HOME=/root/.cache/huggingface
ExecStart=/root/vllm-env/bin/vllm serve Qwen/Qwen3-32B-AWQ \
--served-model-name qwen3-32b \
--host 127.0.0.1 --port 8000 \
--max-model-len 32768 \
--gpu-memory-utilization 0.92 \
--reasoning-parser qwen3 \
--enable-auto-tool-choice --tool-call-parser hermes
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.targetsystemctl daemon-reload
systemctl enable --now vllm
journalctl -u vllm -f # wait for "Application startup complete"
curl -s localhost:8000/v1/modelsIf the machine has no systemd, which is common on container-based GPU rentals, run the same vllm serve command inside tmux new -s vllm instead. For gated models such as Llama, add Environment=HF_TOKEN=... to the unit file.
Step 3: Add a gateway with per-client keys, rate limits and usage logs
vLLM's --api-key supports one shared key. A gateway gives every client its own key, which you can revoke, plus a per-minute rate limit and a token count per client. Install the dependencies and create a key file:
pip install fastapi uvicorn httpx
mkdir -p ~/gateway && cd ~/gateway
echo "alice:$(openssl rand -hex 24)" >> keys.txt
echo "billing-app:$(openssl rand -hex 24)" >> keys.txt
chmod 600 keys.txt && cat keys.txtSave this as ~/gateway/gateway.py:
import json, os, sqlite3, time
from collections import defaultdict, deque
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from starlette.background import BackgroundTask
UPSTREAM = os.environ.get("UPSTREAM", "http://127.0.0.1:8000")
UPSTREAM_KEY = os.environ.get("UPSTREAM_KEY", "") # set if the upstream needs a key
RATE_PER_MIN = int(os.environ.get("RATE_PER_MIN", "60"))
KEYS = {} # api key -> client name
with open(os.environ.get("KEYS_FILE", "keys.txt")) as f:
for line in f:
if line.strip() and not line.startswith("#"):
name, key = line.strip().split(":", 1)
KEYS[key] = name
db = sqlite3.connect("usage.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS usage (ts REAL, client TEXT, path TEXT, prompt INT, completion INT)")
hits = defaultdict(deque)
client = httpx.AsyncClient(base_url=UPSTREAM, timeout=httpx.Timeout(None))
app = FastAPI()
def authorise(request: Request) -> str:
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
name = KEYS.get(token)
if not name:
raise HTTPException(status_code=401, detail="invalid API key")
now, window = time.time(), hits[name]
while window and now - window[0] > 60:
window.popleft()
if len(window) >= RATE_PER_MIN:
raise HTTPException(status_code=429, detail="rate limit exceeded")
window.append(now)
return name
def record(name: str, path: str, usage) -> None:
if usage:
db.execute("INSERT INTO usage VALUES (?,?,?,?,?)",
(time.time(), name, path, usage.get("prompt_tokens", 0), usage.get("completion_tokens", 0)))
db.commit()
@app.get("/health")
async def health():
r = await client.get("/health")
return JSONResponse({"upstream_status": r.status_code})
@app.api_route("/v1/{path:path}", methods=["GET", "POST"])
async def proxy(path: str, request: Request):
name = authorise(request)
body = await request.body()
payload = json.loads(body) if body else None
streaming = bool(payload and payload.get("stream"))
if streaming: # ask for a final usage chunk
payload.setdefault("stream_options", {})["include_usage"] = True
body = json.dumps(payload).encode()
headers = {"content-type": "application/json"}
if UPSTREAM_KEY:
headers["authorization"] = f"Bearer {UPSTREAM_KEY}"
req = client.build_request(request.method, f"/v1/{path}", content=body, headers=headers)
upstream = await client.send(req, stream=True)
if not streaming:
data = await upstream.aread()
await upstream.aclose()
try:
record(name, path, json.loads(data).get("usage"))
except (ValueError, AttributeError):
pass
return Response(content=data, status_code=upstream.status_code,
media_type=upstream.headers.get("content-type"))
async def relay():
async for line in upstream.aiter_lines():
if line.startswith("data: {") and '"usage"' in line:
try:
record(name, path, json.loads(line[6:]).get("usage"))
except ValueError:
pass
yield line + "\n"
return StreamingResponse(relay(), status_code=upstream.status_code,
media_type="text/event-stream",
background=BackgroundTask(upstream.aclose))Run it with a single worker, because the rate-limit counters live in memory:
cd ~/gateway
uvicorn gateway:app --host 0.0.0.0 --port 9000 --workers 1The gateway logs token counts, not prompt content, so usage reports never contain your users' data. To proxy a hosted endpoint instead of local vLLM, set UPSTREAM=https://YOUR-ENDPOINT (no /v1) and UPSTREAM_KEY=$WG_API_KEY. FastAPI's own docs are at fastapi.tiangolo.com.
Step 4: Put TLS in front
Never send API keys over plain HTTP across the internet. There are two easy routes, depending on whether your machine accepts inbound connections on ports 80 and 443.
With a public IP and a DNS name pointing at the machine, Caddy obtains and renews a certificate automatically. Install it following Caddy's install guide, then:
caddy reverse-proxy --from api.yourdomain.com --to localhost:9000Without open inbound ports, an outbound tunnel works. Cloudflare's cloudflared makes a quick tunnel for testing in one command:
curl -L -o cloudflared.deb \
https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
dpkg -i cloudflared.deb
cloudflared tunnel --url http://localhost:9000 # prints a https://....trycloudflare.com URLQuick tunnels get a random hostname and are meant for testing. For production, create a named tunnel on your own domain, as described in the cloudflared repository. If only you need access, skip both and use an SSH tunnel: ssh -L 9000:localhost:9000 root@<your-gpu-address>.
Step 5: Call your API
export MY_API="https://api.yourdomain.com/v1"
export MY_KEY="the-key-from-keys.txt"
curl -s "$MY_API/chat/completions" \
-H "Authorization: Bearer $MY_KEY" -H "Content-Type: application/json" \
-d '{"model": "qwen3-32b",
"messages": [{"role": "user", "content": "Draft a polite payment reminder."}],
"chat_template_kwargs": {"enable_thinking": false}}'import os
from openai import OpenAI
client = OpenAI(base_url=os.environ["MY_API"], api_key=os.environ["MY_KEY"])
stream = client.chat.completions.create(
model="qwen3-32b",
messages=[{"role": "user", "content": "List five checks for a pull request."}],
stream=True,
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
for chunk in stream:
if chunk.choices:
print(chunk.choices[0].delta.content or "", end="", flush=True)A wrong key returns 401, and more than RATE_PER_MIN requests in a minute return 429. Both are standard errors the OpenAI SDKs already handle and retry.
Step 6: Monitor capacity and usage
vLLM publishes Prometheus metrics. The ones that tell you whether you need more GPU are requests running, requests waiting and KV cache usage:
curl -s localhost:8000/metrics | grep -E "num_requests_(running|waiting)|cache_usage_perc"If requests are regularly waiting and KV cache use sits near 100%, you are at capacity. Add memory or another replica, or lower --max-model-len. Token usage per client comes from the gateway's database:
sqlite3 ~/gateway/usage.db \
"SELECT client, COUNT(*) AS requests, SUM(prompt) AS prompt_tokens, SUM(completion) AS completion_tokens
FROM usage WHERE ts > strftime('%s','now','-1 day') GROUP BY client;"To find capacity before users do, run vllm bench serve against the gateway at increasing concurrency. The tokens per second guide explains how to read the results.
Step 7: Scale beyond one GPU
Scale out with replicas before scaling up a single model, as long as the model fits on one card. Run another vLLM on a second GPU (CUDA_VISIBLE_DEVICES=1 vllm serve ... --port 8001) or another machine, and have the gateway pick an upstream per request. Use tensor parallelism only when the model does not fit on one card. Copies avoid inter-GPU traffic and usually serve more users per pound.
What does a self-hosted LLM API cost?
A dedicated GPU costs its hourly price for every hour it runs, so the two numbers to decide are hours per month and how much traffic you can push through it. The table uses our prices and an assumed throughput under load for each setup.
| Setup | Our price | 24/7 (730 h) | Business hours (220 h) | Assumed tok/s under load | Max output tokens per month, 24/7 |
|---|---|---|---|---|---|
| Qwen3 8B FP8, RTX 4090 | $1.59/hr | $1,161 | $349.80 | 1,200 | ~3.2 billion |
| Qwen3 32B AWQ, L40S | $1.89/hr | $1,380 | $415.80 | 300 | ~790 million |
| Llama 3.3 70B FP8, H100 | $4.99/hr | $3,643 | $1,098 | 250 | ~660 million |
| Llama 3.3 70B FP8, H200 | $9.09/hr | $6,636 | $2,000 | 900 | ~2.4 billion |
Monthly figures are the live hourly price × 730 or × 220 hours. Business hours means 10 hours a day for 22 days. Throughput is an assumption for chat-like traffic, not a measurement, and real utilisation is always below the maximum. Between sessions a paused machine pays only for its disk, about 3¢ an hour per 50 GB, so stopping overnight keeps the downloaded weights without paying for the GPU.
The comparison that matters is your expected monthly tokens against a hosted API's per-token price. If you would use a small fraction of the monthly capacity, a hosted API is probably cheaper. If you would fill it, or if prompts must stay private, self-hosting wins. Best GPU clouds for LLM inference compares where to rent.
Security checklist for a self-hosted LLM API
Run through these before you give anyone a key:
- vLLM bound to
127.0.0.1. Only the gateway or proxy is reachable from outside. - TLS on every external connection.
- One key per client, stored outside code, revocable by deleting a line and restarting the gateway.
- Rate limits set below what one GPU can serve, so one client cannot starve the rest.
- Usage logs that hold metadata, not prompt content, unless you have a reason and a retention policy.
- No
--trust-remote-codeon models from unknown publishers. - A plan for model updates: pin the model revision, and test before swapping.
For agent workloads that call the API in loops, see how to build a private AI agent platform. For an engine other than vLLM, the vLLM vs Ollama vs TGI comparison covers the options. Every vLLM flag here is documented in the vLLM docs.
When renting from Wandering Giants Compute fits
Wandering Giants Compute covers both routes in this guide. API mode is Option 1: an OpenAI-compatible endpoint served by vLLM with your own key, ready in minutes, for any of our one-click models from Qwen3 8B on an RTX 4090 at $1.59/hr to Qwen3 235B-A22B FP8 on a B300 at $18.09/hr. Root is Option 2: the whole machine, to run this exact stack with your own model, gateway and domain. Prompts go to your machine, not a shared AI API, and we don't read them or train on them. Billing is by the minute from prepaid credit, and the machine stops if credit runs out.
What we don't provide is autoscaling or scale-to-zero. If your traffic is very spiky and you want to pay nothing between bursts, a serverless GPU platform fits better. See the AI SaaS infrastructure guide for how teams combine the two.
Frequently asked questions
Can I make an OpenAI-compatible API for an open-source model?
Yes. vLLM, SGLang, TGI and Ollama all expose OpenAI-compatible endpoints. With vLLM, run vllm serve with your model and any OpenAI SDK can call it by changing the base URL and key. Tool calling, streaming and JSON output work for models that support them.
How do I add API keys to vLLM?
vLLM's --api-key flag, or the VLLM_API_KEY environment variable, requires one static bearer token on /v1 routes. For separate keys per user or app, rate limits and usage tracking, put a gateway in front: a small FastAPI proxy like the one in this guide, or an off-the-shelf proxy such as LiteLLM.
How many users can a self-hosted LLM API handle?
It depends on model size, GPU memory and request lengths. A 70B FP8 model on one 80 GB H100 suits a handful of concurrent conversations; the same model on a 141 GB H200 serves dozens. Benchmark with vllm bench serve at your real prompt and output lengths to find the concurrency where latency crosses your target.
Is a self-hosted LLM API cheaper than OpenAI or Anthropic?
Only when you keep the GPU busy, or when you need privacy or a specific model. A GPU costs the same per hour at any load, so at low traffic a pay-per-token API is usually cheaper. At steady high traffic, a well-batched open model can cost less per token.
How do I secure a self-hosted LLM API?
Bind the model server to localhost, expose only the gateway, require per-client keys over TLS, rate-limit, keep keys out of code and logs, and avoid trust-remote-code on unknown models. Log usage metadata rather than prompt content if prompts are sensitive.
Do I need Kubernetes to run an LLM API?
No. One machine with a systemd service or a tmux session for vLLM, a gateway and a reverse proxy serves a lot of traffic. Kubernetes helps when you run many replicas across many machines and need automated scheduling and rollouts.
Rent the GPU for this, by the minute.
Get an OpenAI-compatible endpoint for Llama, Qwen or DeepSeek with your own key in minutes, or take root and build the full API stack yourself.
Prepaid credit, billed by the minute, stops itself when credit runs out. Prices in £, $, €, ¥, CA$, A$, CHF and S$; UK prices include VAT.
Keep reading
- Complete guideWhat Is LLM Inference? A Complete Technical Guide
- Head to headvLLM vs Ollama vs TGI: Which LLM Serving Framework Should You Use?
- TutorialHow to Run Qwen Models on a Cloud GPU
- ComparisonBest GPU Infrastructure for AI SaaS Startups
- TutorialHow to Build a Private AI Agent Infrastructure Platform
- ComparisonBest GPU Cloud Providers for LLM Inference
About this article. Written by the Wandering Giants Compute team, the people who run Wandering Giants Compute. Hardware figures are the manufacturers’ published specifications. Speeds and costs marked as estimates are worked out from those specifications and our current prices, with the method shown; they are not measured benchmarks. Wandering Giants prices are taken live from our price list each time this page is built.
Last reviewed 25 November 2026.