There's a moment every ML engineer hits the first time they try to put a Hugging Face model behind a real API. You grab transformers, you wrap it in FastAPI, you pipeline("text-generation", model=...), you curl it once, it works, you push to prod, and at peak traffic your GPU OOMs and the latency goes to 30 seconds. That's the moment you learn that serving a model is not the same as running a model.
This article is the deployment playbook. We'll go through the four real options (Inference Endpoints, TGI, vLLM, and bare Transformers), when to pick each, and the production plumbing around them. I'll skip the marketing and focus on the stuff that bites you at 3am.
The four real options
You have four ways to serve a Hugging Face model in production. Each has a clear use case.
| Option | Best for | Throughput | Cost | Operational burden |
|---|---|---|---|---|
| HF Inference Endpoints | Prototyping, low-traffic prod | Medium-high | $0.06-3/hr/GPU | Very low |
| TGI (Text Generation Inference) | Production LLM serving | High | Compute + your infra | Medium |
| vLLM | Max throughput LLM serving | Highest | Compute + your infra | Medium |
Bare transformers + FastAPI |
Embeddings, small models, custom pipelines | Low | Compute + your infra | High |
The rule of thumb: if it's an LLM doing text generation, use vLLM or TGI. If it's embeddings or a small classification model, bare transformers behind FastAPI is fine. If you don't want to operate infra, Inference Endpoints.
Never serve an LLM by wrapping AutoModelForCausalLM in FastAPI and calling model.generate() per request. You will get 1/20th the throughput of vLLM and OOM under load. The reason is batching: vanilla generate() processes one request at a time, while vLLM and TGI do continuous batching, which is the single biggest LLM serving optimization of the last three years.
Continuous batching: why it matters
Naive batching waits to collect N requests, processes them together, returns all results, then starts the next batch. If one request takes 10x longer (long output), the other 9 wait. Throughput collapses.
Continuous batching (also called iteration-level batching or in-flight batching) inserts new requests into the batch at every token step. A short request finishes, frees its slot, a new request slides in. GPU utilization stays near 100% even when request lengths vary wildly.
The performance difference is not subtle. For Llama-3-8B on a single A10G:
- Naive
model.generate()per request: ~5 tokens/sec/req, batch 1 - vLLM continuous batching: ~2000 tokens/sec aggregate throughput at batch 32+
That's not a typo. vLLM is roughly 100x the throughput for the same model on the same GPU under load. The win comes from continuous batching + PagedAttention (which handles the KV cache like virtual memory, eliminating fragmentation).
Option 1: HF Inference Endpoints (managed)
If you don't want to operate GPUs, this is the path. You click through a UI, pick a model, pick a GPU, and you get an OpenAI-compatible endpoint in 5-10 minutes.
BashCopy
Via huggingface_hub
pip install huggingface_hub
Create an endpoint programmatically
from huggingface_hub import HfApi
api = HfApi(token="hf_xxx")
Or use the CLI
huggingface-cli inference-endpoints create \
--name "llama-3-8b-prod" \
--namespace "your-org" \
--repository "meta-llama/Llama-3.1-8B-Instruct" \
--accelerator "gpu" \
--instance-size "x1" \
--instance-type "nvidia-a10g" \
--region "us-east-1" \
--type "protected"
Call it like OpenAI:
PythonCopy
python
from openai import OpenAI
client = OpenAI(
base_url="https://xxx.us-east-1.aws.endpoints.huggingface.cloud/v1",
api_key="hf_xxx"
)
response = client.chat.completions.create(
model="tgi",
messages=[{"role": "user", "content": "Explain PagedAttention in one sentence."}],
max_tokens=100,
)
markdown
When to use: prototypes, internal tools, low-traffic prod (<10 req/sec), or when you don't have a platform team.
When not to use: high-traffic prod where the per-token markup adds up, regulated environments needing on-prem, or when you need custom inference logic.
Pricing is the cloud GPU rate plus a markup, billed per second. An A10G endpoint runs roughly $1.20-1.50/hr. Compare to a self-managed A10G on AWS at ~$1.00/hr-the markup is the operational simplicity tax.
Option 2: TGI (Text Generation Inference)
TGI is Hugging Face's production LLM server. It's what powers Inference Endpoints internally, and you can run the same Docker image yourself.
BashCopy
shell
Pull the image
docker pull ghcr.io/huggingface/text-generation-inference:latest
Launch a Llama-3-8B server on a single GPU
docker run --gpus all --shm-size 1g \
-p 8080:80 \
-v /data/models:/data \
ghcr.io/huggingface/text-generation-inference:latest \
--model-id meta-llama/Llama-3.1-8B-Instruct \
--max-batch-prefill-tokens 4096 \
--max-total-tokens 8192 \
--quantize awq \
--num-shard 1
plaintext
Key flags you'll actually tune:
-
--max-total-tokens: max sequence length per request. Higher = more memory. -
--max-batch-prefill-tokens: how many tokens to process during prefill per batch. Higher = better throughput, more memory. -
--quantize:awq,gptq,bitsandbytes,eetq, or unset. AWQ is the current sweet spot for 7B-70B models. -
--num-shard: tensor parallel degree. Set to the number of GPUs for multi-GPU serving. -
--max-concurrent-requests: backpressure. Set this or you'll OOM under load.
Call it:
PythonCopy
python
import requests
resp = requests.post("http://localhost:8080/generate", json={
"inputs": "Explain PagedAttention.",
"parameters": {
"max_new_tokens": 200,
"temperature": 0.7,
"top_p": 0.9,
"do_sample": True,
}
})
print(resp.json()["generated_text"])
plaintext
Or use the OpenAI-compatible endpoint at /v1/chat/completions:
PythonCopy
python
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8080/v1", api_key="dummy")
resp = client.chat.completions.create(
model="tgi",
messages=[{"role": "user", "content": "Explain PagedAttention."}],
)
markdown
Option 3: vLLM
vLLM is the open-source throughput king. Same use case as TGI, generally 1.2-2x faster on the same hardware, larger community, faster-moving. The trade-off is less polish on the deployment story and occasional instability on the latest models.
BashCopy
shell
pip install vllm
Launch a server
vllm serve meta-llama/Llama-3.1-8B-Instruct \
--port 8000 \
--tensor-parallel-size 1 \
--max-model-len 8192 \
--gpu-memory-utilization 0.9 \
--quantization awq \
--enable-chunked-prefill
plaintext
Useful flags:
-
--gpu-memory-utilization: fraction of GPU memory vLLM claims. 0.9 leaves room for the rest of your stack. 1.0 = OOM risk. -
--max-model-len: context window. Higher uses more KV cache. -
--enable-chunked-prefill: process prefill in chunks so short requests don't get blocked behind long prefills. Big throughput win for mixed workloads. -
--tensor-parallel-size: split model across N GPUs. -
--swap-space: CPU memory for KV cache spillover. Use sparingly; it's slow.
PythonCopy
python
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
resp = client.chat.completions.create(
model="meta-llama/Llama-3.1-8B-Instruct",
messages=[{"role": "user", "content": "Explain PagedAttention."}],
stream=True,
)
for chunk in resp:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
markdown
TGI vs vLLM: how to choose
Use TGI when:
- You want Hugging Face ecosystem tightness (model hub integration, dtype detection, chat templates).
- You need AWQ/GPTQ with stable support.
- Your team prefers fewer releases and less breakage.
Use vLLM when:
- Max throughput is the priority.
- You want the latest models supported first.
- You're comfortable with breaking changes between minor versions.
In practice, both are good. Pick one based on operational fit, not benchmarks. The 20% throughput difference won't matter if your team can't operate the thing.
Option 4: Bare transformers + FastAPI (for embeddings and small models)
For embeddings, classification, or small seq2seq models, you don't need TGI/vLLM. A simple FastAPI server with the model loaded once at startup works fine.
PythonCopy
python
server.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from contextlib import asynccontextmanager
from sentence_transformers import SentenceTransformer
import torch, os
MODEL_NAME = os.getenv("MODEL_NAME", "BAAI/bge-large-en-v1.5")
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
state = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
state["model"] = SentenceTransformer(MODEL_NAME, device=DEVICE)
yield
state.clear()
app = FastAPI(lifespan=lifespan)
class EmbedRequest(BaseModel):
texts: list[str]
@app.post("/embed")
def embed(req: EmbedRequest):
if not req.texts:
raise HTTPException(400, "texts must be non-empty")
model = state["model"]
with torch.inference_mode():
emb = model.encode(req.texts, normalize_embeddings=True, batch_size=32)
return {"embeddings": emb.tolist()}
plaintext
DockerfileCopy
docker
FROM python:3.11-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY server.py .
ENV MODEL_NAME=BAAI/bge-large-en-v1.5
EXPOSE 8000
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
markdown
Run with --workers 1 because the model is in GPU memory; multiple workers would each load a copy. For throughput, batch within a single worker (the batch_size=32 in encode()).
GPU memory math (the part nobody teaches you)
Before you pick a GPU, do the math. A 7B model in bfloat16 needs:
- Weights: 7B × 2 bytes = ~14 GB
- KV cache: depends on context. For 8K context, batch 32, roughly 4-8 GB.
- Activation buffers and overhead: 1-2 GB.
So a 7B in bf16 fits on a 24GB GPU (A10G, 3090, 4090) with room for moderate batching. A 70B in bf16 needs 140GB for weights alone-you need 2×80GB (A100 80GB) with tensor parallelism, or you quantize.
Quantization options:
| Format | Bits | Size (7B) | Quality loss | Speed |
|---|---|---|---|---|
| fp32 | 32 | 28 GB | none | baseline |
| bf16/fp16 | 16 | 14 GB | none | baseline |
| 8-bit (int8) | 8 | 7 GB | ~1% | faster |
| AWQ 4-bit | 4 | 4 GB | ~2-3% | faster |
| GPTQ 4-bit | 4 | 4 GB | ~2-3% | comparable |
| bitsandbytes 4-bit | 4 | 5 GB | ~3-5% | slower |
AWQ is the current production sweet spot for LLMs. GPTQ is comparable. bitsandbytes is easiest to set up but slowest. For embeddings, stay in fp16 or bf16-quantizing embedding models tends to wreck retrieval quality.
Deployment architecture
A real production setup looks like this:
CodeCopy
plaintext
┌─────────────┐
│ Cloudflare │
│ / nginx │
└──────┬──────┘
│
┌──────▼──────┐
│ API gateway│
│ (rate limit,│
│ auth, logs)│
└──────┬──────┘
│
┌────────────┼────────────┐
│ │ │
┌──────▼───┐ ┌──────▼───┐ ┌──────▼───┐
│ vLLM pod │ │ vLLM pod │ │ vLLM pod │
│ (GPU 1) │ │ (GPU 2) │ │ (GPU 3) │
└──────────┘ └──────────┘ └──────────┘
│ │ │
└────────────┼────────────┘
│
┌──────▼──────┐
│ Redis │
│ (cache, kv) │
└─────────────┘
markdown
Key principles:
- Stateless pods: each vLLM pod loads the model from a shared volume. Horizontal scaling = more pods.
- Sticky sessions not required: vLLM is stateless across requests. Round-robin is fine.
- Shared model storage: NFS, EFS, or a PVC. Don't pull from HF Hub on every pod startup-use a cached copy.
- Queue + backpressure: put a queue (Redis Streams, SQS) between the API gateway and the pods. Reject requests when the queue is full rather than letting them OOM the pods.
Autoscaling
CPU-based autoscaling doesn't work for LLMs. A pod at 0 req/sec and a pod at 50 req/sec both show 5% CPU because the GPU is doing the work. You need GPU-aware metrics.
Prometheus + DCGM exporter gives you:
-
DCGM_FI_DEV_GPU_UTIL(0-100%) DCGM_FI_DEV_MEM_COPY_UTIL-
DCGM_FI_DEV_FB_USED(frame buffer memory used)
Scale on DCGM_FI_DEV_GPU_UTIL > 80 for scale-up, < 30 for scale-down. Set a longer stabilization window (5-10 min) because pods take 2-5 minutes to load a model.
For KEDA (Kubernetes Event-Driven Autoscaling) on a custom metric like queue depth:
YAMLCopy
yaml
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: vllm-scaler
spec:
scaleTargetRef:
name: vllm-deployment
minReplicaCount: 2
maxReplicaCount: 10
cooldownPeriod: 300
triggers:
- type: redis metadata: address: redis.default.svc:6379 listName: inference_queue listLength: "10"
markdown
Cold starts are the killer here. A new pod takes 2-5 minutes to pull the model into GPU memory. Keep minReplicaCount at your baseline traffic level. Never scale to zero in production unless you can afford 5-minute startup latency.
Caching
Semantic caching (cache similar prompts, not just identical ones) is the biggest cost lever for LLM serving. Tools like RedisVL, GPTCache, or a simple embedding-similarity cache work.
PythonCopy
python
import redis, numpy as np
from sentence_transformers import SentenceTransformer
r = redis.Redis(host="redis", port=6379)
embedder = SentenceTransformer("BAAI/bge-small-en-v1.5")
def cached_generate(prompt: str, generate_fn, threshold: float = 0.95):
q_emb = embedder.encode([prompt], normalize_embeddings=True)[0]
# Search cache
results = r.execute_command(
"FT.SEARCH", "cache_idx",
f"*=>[KNN 1 @emb $query_vec]",
"PARAMS", 2, "query_vec", q_emb.tobytes(),
"RETURN", 1, "__emb_score",
"DIALECT", 2
)
if results and results[0] > 0:
score = results[2][1]
if float(score) >= threshold:
cached = r.get(f"response:{results[2][3]}")
if cached:
return cached.decode()
# Cache miss
response = generate_fn(prompt)
r.setex(f"prompt:{hash(prompt)}", 3600, response)
# ... index embedding
return response
markdown
Cache hit rates of 20-40% are typical for support/chat workloads. That's a 25-65% cost reduction for free.
Monitoring
The metrics that matter:
- Latency p50/p95/p99: separate first-token latency (TTFT) from total latency. Users tolerate 200ms TTFT, not 2000ms.
- Tokens/sec per request: regression signal.
- GPU utilization: should be >60% under load, <30% at idle.
- GPU memory utilization: alert at >90%.
- Queue depth: alert at >100.
- Error rate by error type: OOM, timeout, model-not-loaded.
- Cache hit rate: regression here = cost regression.
Grafana dashboard with vLLM's built-in Prometheus metrics + DCGM exporter covers most of this.
Common mistakes
Serving LLMs with bare transformers.generate(): 100x slower than vLLM. Stop doing this in production.
Setting --gpu-memory-utilization 1.0: OOMs on the first long request. Leave 5-10% headroom.
Pulling models from HF Hub at pod startup: 2-3 minute startup tax, fails if HF is down. Cache models on a shared volume.
No backpressure: clients pile up, pods OOM, you get a thundering herd. Set --max-concurrent-requests and return 429 above it.
Ignoring first-token latency: users perceive streaming responses as 3x faster than buffered ones, even at the same total time. Always stream.
Forgetting to set CUDA_VISIBLE_DEVICES on multi-GPU boxes: vLLM grabs GPU 0 by default and ignores the others. Use --tensor-parallel-size N or set the env var.
Mixing quantization formats: load an AWQ model with --quantization gptq and you get garbage output. Match the format.
No model warmup: the first request after startup takes 30+ seconds because CUDA kernels compile. Hit the endpoint with a dummy request in your readiness probe.
Troubleshooting real production issues
Symptom: First request after deploy takes 30 seconds.
Cause: CUDA kernel compilation + lazy initialization.
Fix: warm up in the Docker entrypoint or readiness probe:
PythonCopy
python
import requests
def warmup():
try:
requests.post("http://localhost:8000/v1/chat/completions",
json={"model": "x", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 1},
timeout=60)
except Exception:
pass
Symptom: p99 latency spikes to 30s every few hours.
Cause: Long prefill requests blocking the batch.
Fix: enable --enable-chunked-prefill (vLLM) or --max-batch-prefill-tokens (TGI) and cap --max-input-length.
Symptom: OOM errors under load despite low utilization.
Cause: KV cache exhausted from long-context requests.
Fix: lower --max-model-len, set --max-num-seqs explicitly, add backpressure.
Symptom: Throughput halves after a deploy.
Cause: Quantization disabled by config drift, or a different dtype loaded.
Fix: check startup logs for quantization and dtype lines. Pin everything in config, not CLI flags.
Cost considerations
Rough monthly cost for serving Llama-3-8B at moderate traffic (50 req/sec avg, 500 tokens per request):
- AWS p3.2xlarge (V100 16GB): $0.50/hr ≈ $365/mo. Doesn't fit a 7B in bf16.
- AWS g5.xlarge (A10G 24GB): $1.00/hr ≈ $730/mo. Fits 7B in bf16 or 4-bit. 2-3 pods for HA.
- AWS g5.12xlarge (4×A10G): $7.09/hr ≈ $5,150/mo. For 70B in 4-bit with TP=4.
- RunPod/Lambda Labs: roughly half the AWS price, less reliable.
- HF Inference Endpoints: ~1.3× AWS compute cost.
A 70B in 4-bit on 2×A100 80GB self-managed runs ~$5,500/mo on AWS, or ~$3,500/mo on Lambda Labs. The Inference Endpoint equivalent is ~$4,500-5,000/mo. The operational savings may justify the markup if you don't have a platform team.
Real-world use cases
- Customer support bot: vLLM on 2× A10G pods, AWQ-quantized Llama-3-8B, 4 replicas behind an nginx queue. ~$2,000/mo, handles 200 req/sec peak.
- Internal RAG: TGI on 1× A100 80GB, Mixtral 8x7B in 4-bit. ~$3,000/mo, 50 internal users.
- Embeddings service: bare transformers + FastAPI, bge-large-en, 1× L4 GPU. ~$300/mo, 1000 req/sec.
- Code completion: vLLM on 2× A100 80GB, DeepSeek-Coder 33B in AWQ. ~$5,500/mo, IDE plugin for 200 developers.
Conclusion
If you take one thing from this article: don't serve LLMs with bare transformers. Pick vLLM or TGI, learn its flags, and instrument it properly. The model is 20% of the work; the serving infrastructure is 80%, and it's where your production fires will be.
Originally published on Mango Developer.
Top comments (0)