# How to Deploy Hugging Face Models in Production

> Source: <https://dev.to/mango7777/how-to-deploy-hugging-face-models-in-production-412a>
> Published: 2026-11-27 17:30:00+00:00

**Recommendation:** Use vLLM or TGI for any LLM text generation instead of wrapping generate() in FastAPI; continuous batching and PagedAttention delivered roughly 100x throughput on Llama-3-8B over a single A10G.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

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.

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.

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:

`model.generate()` per request: ~5 tokens/sec/req, batch 1
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).

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](https://mangodeveloper.com/articles/cisco-openai-shirudo-ebpf-shields-patch-without-reboot)-compatible endpoint in 5-10 minutes.

```
BashCopy
```

pip install huggingface_hub

from huggingface_hub import HfApi

api = HfApi(token="hf_xxx")

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](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.

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

docker pull ghcr.io/huggingface/text-generation-inference:latest

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](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"])

Or use the OpenAI-compatible endpoint at `/v1/chat/completions`:

```
PythonCopy
```

client = OpenAI(base_url="[http://localhost:8080/v1](http://localhost:8080/v1)", api_key="dummy")

resp = client.chat.completions.create(

 model="tgi",

 messages=[{"role": "user", "content": "Explain PagedAttention."}],

)

vLLM is the [open-source](https://mangodeveloper.com/category/dev) 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

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

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
```

client = OpenAI(base_url="[http://localhost:8000/v1](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)

Use TGI when:

Use vLLM when:

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.

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

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()}

```
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"]

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()`).

Before you pick a GPU, do the math. A 7B model in bfloat16 needs:

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.

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) │

 └─────────────┘

Key principles:

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](https://mangodeveloper.com/category/devops) 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:

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.

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

Cache hit rates of 20-40% are typical for support/chat workloads. That's a 25-65% cost reduction for free.

The metrics that matter:

Grafana dashboard with vLLM's built-in Prometheus metrics + DCGM exporter covers most of this.

**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.

**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](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.

Rough monthly cost for serving Llama-3-8B at moderate traffic (50 req/sec avg, 500 tokens per request):

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.

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](https://mangodeveloper.com/articles/deploy-huggingface-models).
