AI Engineering · Build lab 14 of 14
Deploy an LLM app with Docker, and serve your own model with vLLM
Package the streaming chat API for production: settings from environment variables, health checks, timeouts and rate limiting, a small non-root Docker image built with uv, and docker compose with Ollama. Then serve a model with vLLM and switch the app to it by changing only settings.
⏱ 75 minIntermediate💸 Free locally (a GPU machine for vLLM is optional)10 steps
Python 3.12uvFastAPIuvicornopenai SDKDocker + docker composeOllamallama3.2:3bvLLM (optional, NVIDIA GPU)pytest
Overview video
What you will build
A chat service you can deploy: the streaming chat API from lab 2, rebuilt as a small production service. It reads every setting from environment variables, has /health and /ready endpoints for the platform that runs it, stops answers that take too long, and limits how many requests each client may send.
You package it as a Docker image (two stages, built with uv, running as a normal user, no secrets inside), run it next to Ollama with docker compose, and then serve a model yourself with vLLM, the open-source server built for many users at once. Switching the app from Ollama to vLLM changes three settings and no code. You finish with an honest comparison of Ollama, vLLM and a hosted API, and a checklist for deploying to any container platform.
Everything is tested without a model: a fake streamer, a fake clock for the rate limiter, and a fake OpenAI-compatible server inside the tests.
Before you start
- Lab 2: Streaming chat. This lab rebuilds its API here, so you do not need that project, but the ideas (Server-Sent Events, async generators,
Depends) are explained there in more depth. - FastAPI and pytest basics: FastAPI and Testing with pytest.
- Docker basics help: what an image and a container are. Every Docker command here is explained.
- About 5 GB of free disk space (the model, the Ollama image and your image).
Setup
S1Install uv (the Python project tool)
Skip this if you did lab 1. uv installs Python for you, creates the virtual environment and manages packages. The Docker image in step 6 uses it too.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" everything's installed!
S2Check uv works
The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own. On Windows, open a new terminal after installing.
uv --version uv 0.x.y
S3Install Ollama (runs models on your machine)
Download it from ollama.com/download and open it once. It runs a server on port 11434 that speaks the same chat API as the hosted providers. Steps 1 to 5 use it directly; step 7 also runs Ollama inside Docker.
ollama --version ollama version is 0.x.y
S4Pull a small model (llama3.2:3b, about 2 GB)
If you did lab 1 you already have it: ollama list shows it.
ollama pull llama3.2:3b pulling manifest ... success
S5Install Docker (with docker compose)
macOS and Windows: install Docker Desktop from docker.com and open it once; it includes docker compose. Linux: install Docker Engine and the compose plugin by following the instructions for your distribution on docs.docker.com, then add yourself to the docker group (sudo usermod -aG docker $USER, then log out and in) so you do not need sudo for every command. Both commands below must print a version.
docker --version
docker compose version Docker version x.y.z, build abc1234 Docker Compose version vx.y.z
S6Optional: a Linux machine with an NVIDIA GPU (for vLLM)
Only steps 8 and 9 need it, and you can read them without one. vLLM needs a Linux machine with an NVIDIA GPU (compute capability 7.0 or newer: T4, L4, A10, A100, H100, RTX 20xx or newer) and its driver. A rented cloud GPU machine is fine. It does not run on a Mac (step 8 explains why). On the GPU machine, nvidia-smi shows the GPU and its memory:
nvidia-smi +-----------------------------------------------------------------------------+ | NVIDIA-SMI 5xx.xx Driver Version: 5xx.xx CUDA Version: 12.x | | 0 NVIDIA L4 ... | 0MiB / 23034MiB | +-----------------------------------------------------------------------------+
Create the project
A fresh project on Python 3.12, the same version the Docker image will use.
uv init creates the project folder and pyproject.toml (like package.json or pom.xml). --python 3.12 pins the Python version in a .python-version file, so your laptop and the Docker image in step 6 run the same Python. uv downloads 3.12 if you do not have it.
The packages: fastapi (the web framework, think Spring Web), uvicorn (the server that runs it, think the embedded Tomcat), openai (the SDK, which talks to Ollama, vLLM and hosted APIs alike) and python-dotenv (reads .env). For tests: pytest and httpx2, the HTTP client the openai SDK is built on; the tests use its fake transport. uv add also writes uv.lock, the exact version of every package. Commit it: the Docker build in step 6 installs exactly what it says.
uv also creates a main.py you will not need: delete it. Then add the two small files below.
.venv/
__pycache__/
.pytest_cache/
.env - Never commit
.env: in production it holds a real key.line 4
{"messages": [{"role": "user", "content": "Say hello and name one sorting algorithm."}]} - A chat request body, used by
curl -d @hi.jsonin later steps. The@tells curl to read the body from this file, which avoids quoting trouble in every shell.line 1
uv init --python 3.12 chat-service
cd chat-service
rm main.py
uv add fastapi uvicorn openai python-dotenv
uv add --dev pytest httpx2uv init --python 3.12 chat-service
cd chat-service
rm main.py
uv add fastapi uvicorn openai python-dotenv
uv add --dev pytest httpx2uv init --python 3.12 chat-service
cd chat-service
Remove-Item main.py
uv add fastapi uvicorn openai python-dotenv
uv add --dev pytest httpx2 Initialized project `chat-service` at `.../chat-service` Using CPython 3.12.13 Creating virtual environment at: .venv Resolved 23 packages in 187ms Installed 21 packages in 34ms + fastapi==0.165.0 + openai==3.60.0 + python-dotenv==1.2.4 + uvicorn==0.55.0 ... Resolved 29 packages in 14ms Installed 5 packages in 5ms + pytest==9.2.0 ...
Stuck on this step?
uv: command not found- Run
export PATH="$HOME/.local/bin:$PATH"(macOS and Linux), or open a new terminal so the installer's PATH change applies. rm: main.py: No such file or directory- Your uv version did not create one. Nothing to delete; carry on.
Every setting from environment variables
One `Settings` object built from the environment, checked at startup, with the key hidden from logs.
The same image must run on your laptop, in CI and in production, so nothing that differs between them may live in the code: the model server's URL, the model, the key and the limits all come from environment variables. On your laptop, .env provides them (through load_dotenv(), as in lab 1). In a container there is no .env at all: docker compose or the platform sets real environment variables. The code is the same either way.
Two habits make this safe. Check values when the app starts: RATE_BURST=lots should stop the app with a clear message, not crash on the first request at 3 a.m. Never print secrets: field(repr=False) leaves the key out of the text Python prints for the object (its repr, like toString() in Java), so logging the settings cannot leak it.
# Local development: the app on your laptop, the model in the Ollama app.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b
# Limits (seconds and counts). The defaults in config.py are the same.
LLM_TIMEOUT=30
ANSWER_TIMEOUT=120
MAX_TOKENS=512
RATE_PER_MINUTE=20
RATE_BURST=5 - On your laptop the model server is the Ollama app. Inside docker compose it will be
http://ollama:11434/v1(step 7), and with vLLM a different URL again (step 9). Only this file or the environment changes.line 2 - Seconds to wait for the model server: to connect, and for each next piece of a streamed answer.line 7
- Seconds for one whole answer, however steadily it streams. Step 3 enforces it.line 8
- The rate limit (step 4): 20 requests a minute per client, at most 5 at once.line 10
import os
from dataclasses import dataclass, field
from dotenv import load_dotenv
load_dotenv() # reads .env if there is one; in a container there is none, and real env vars win anyway
@dataclass(frozen=True)
class Settings:
base_url: str
api_key: str = field(repr=False) # never printed, never logged
model: str
llm_timeout: float # seconds: connecting, and waiting for each next chunk
answer_timeout: float # seconds: one whole answer, start to finish
max_tokens: int # longest answer the model may write
rate_per_minute: int # requests per client per minute
rate_burst: int # requests a client may send at once
def _number(name: str, default: str, cast):
raw = os.environ.get(name, default)
try:
value = cast(raw)
except ValueError:
raise ValueError(f"{name} must be a number, got {raw!r}") from None
if value <= 0:
raise ValueError(f"{name} must be greater than 0, got {raw!r}")
return value
def settings() -> Settings:
return Settings(
base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key=os.environ.get("LLM_API_KEY", "ollama"),
model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
llm_timeout=_number("LLM_TIMEOUT", "30", float),
answer_timeout=_number("ANSWER_TIMEOUT", "120", float),
max_tokens=_number("MAX_TOKENS", "512", int),
rate_per_minute=_number("RATE_PER_MINUTE", "20", int),
rate_burst=_number("RATE_BURST", "5", int),
) - If there is no
.envfile, this does nothing and raises no error. That is exactly what happens in the container.line 6 - A read-only data class, like a Java record. Nothing can change the settings after startup.line 9
field(repr=False): the key is a normal field, butprint(settings())and log lines leave it out.line 12- Reads a number from the environment.
castis the type to convert to, passed as a function:intorfloat(in Python a type can be called like a function:int("5")is5).line 21 from Nonehides the originalint()error, so the message shows only the setting's name and the bad value.{raw!r}prints the value in quotes, so an empty or space-padded value is visible.line 26- Zero or negative limits make no sense (and a rate of zero would divide by zero later). Refuse them too.line 27
- Builds the settings from the environment. The second argument of each
getis the default for when the variable is not set.line 32
uv run python -c "from config import settings; print(settings())"
RATE_BURST=lots uv run python -c "from config import settings; settings()"uv run python -c "from config import settings; print(settings())"
RATE_BURST=lots uv run python -c "from config import settings; settings()"uv run python -c "from config import settings; print(settings())"
$env:RATE_BURST="lots"; uv run python -c "from config import settings; settings()"; Remove-Item Env:RATE_BURST Settings(base_url='http://localhost:11434/v1', model='llama3.2:3b', llm_timeout=30.0, answer_timeout=120.0, max_tokens=512, rate_per_minute=20, rate_burst=5) Traceback (most recent call last): ... ValueError: RATE_BURST must be a number, got 'lots'
Stuck on this step?
- The first line shows other values than mine in
.env - A real environment variable with the same name is set in your shell, and real variables win over
.env. Check withecho $LLM_MODEL(PowerShell:$env:LLM_MODEL).
The streaming API, with health checks and timeouts
Lab 2's `/chat` endpoint plus `/health`, `/ready`, a deadline for every answer, and clear error events.
llm.py holds the model call: one function that streams the answer as an async generator (async def with yield; the caller reads it with async for, like a Flux in Reactor or an async iterator in JavaScript). The client and model are passed in as arguments, so tests can pass fakes.
server.py is the API. Compared with lab 2 it adds what a platform and an operator need:
/health(liveness) answers "the process is up" and never calls the model. If it fails, the platform restarts the container./ready(readiness) checks that the model server answers and has your model. If it fails, the platform stops sending traffic but does not restart anything: restarting your app cannot fix a missing model.- Two timeouts.
LLM_TIMEOUT(in the client) limits each wait for the model server.ANSWER_TIMEOUTlimits the whole answer, because a model that keeps sending a token every few seconds never trips the first one. max_tokenscaps the answer length, so one request cannot generate (and bill) for minutes.
Start it in one terminal and leave it running:
uv run uvicorn server:app
Then use a second terminal in the same folder for the commands below. curl -sN prints the stream as it arrives (-N) and hides curl's progress meter (-s).
Try the deadline too: stop the server (Ctrl+C), start it with ANSWER_TIMEOUT=2 uv run uvicorn server:app (PowerShell: $env:ANSWER_TIMEOUT="2"; uv run uvicorn server:app, then Remove-Item Env:ANSWER_TIMEOUT when done) and send a long question. You get a few tokens, then {"type": "error", "message": "The answer took too long, so it was stopped."}.
from collections.abc import AsyncIterator
from openai import AsyncOpenAI
from config import Settings
def make_client(s: Settings) -> AsyncOpenAI:
"""One client for the whole app: it keeps a pool of connections to the model server."""
return AsyncOpenAI(base_url=s.base_url, api_key=s.api_key, timeout=s.llm_timeout, max_retries=1)
async def stream_reply(client: AsyncOpenAI, model: str, messages: list[dict], max_tokens: int) -> AsyncIterator[str]:
"""Send the conversation, yield the answer piece by piece."""
stream = await client.chat.completions.create(
model=model,
messages=messages,
max_tokens=max_tokens,
temperature=0.7,
stream=True,
)
async with stream:
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content - Built once and shared (
get_clientinserver.py). The client keeps connections to the model server open between requests, which saves time on every call.line 8 timeoutcomes fromLLM_TIMEOUT. One retry for temporary errors (connection failures, 429, 5xx): a user is waiting, so retry little and fail fast.line 10AsyncIterator[str]is the return type: something you read withasync for, getting strings.line 13- The longest answer the model may write. Ollama, vLLM and most hosted APIs accept
max_tokens; some hosted APIs prefer the newer namemax_completion_tokens.line 18 - Closes the connection to the model server when the loop ends, fails or is cancelled, so the model stops generating when nobody is listening.line 22
- Each chunk carries a small piece of text in
delta.content. Some chunks (like the last one) carry none: skip them.line 24
import asyncio
import json
import logging
from contextlib import asynccontextmanager
from functools import lru_cache
from typing import Literal
import openai
from fastapi import Depends, FastAPI
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from config import Settings, settings
from llm import make_client, stream_reply
SYSTEM = "You are a friendly, concise assistant for software developers."
log = logging.getLogger("uvicorn.error")
@lru_cache
def get_settings() -> Settings:
return settings()
@lru_cache
def get_client() -> openai.AsyncOpenAI:
return make_client(get_settings())
@asynccontextmanager
async def lifespan(app: FastAPI):
s = get_settings() # bad settings stop the app here, at startup, not on the first request
log.info("Model %s at %s", s.model, s.base_url)
yield
await get_client().close()
app = FastAPI(title="Chat service", lifespan=lifespan)
class Message(BaseModel):
role: Literal["user", "assistant"]
content: str = Field(max_length=8000)
class ChatRequest(BaseModel):
messages: list[Message] = Field(min_length=1, max_length=50)
def sse(data: dict) -> str:
return f"data: {json.dumps(data)}\n\n"
def get_streamer(s: Settings = Depends(get_settings), client: openai.AsyncOpenAI = Depends(get_client)):
"""Which function streams the reply. Tests replace it with a fake."""
return lambda messages: stream_reply(client, s.model, messages, s.max_tokens)
def friendly(err: Exception) -> str:
if isinstance(err, TimeoutError):
return "The answer took too long, so it was stopped."
if isinstance(err, openai.APITimeoutError): # before APIConnectionError: it is a subclass
return "The model server did not respond in time."
if isinstance(err, openai.APIConnectionError):
return "Cannot reach the model server."
if isinstance(err, openai.NotFoundError):
return "The configured model does not exist on the model server."
return "The model failed while answering."
@app.get("/health")
def health():
"""Liveness: the process is up and serving requests. Never calls the model."""
return {"status": "ok"}
@app.get("/ready")
async def ready(client: openai.AsyncOpenAI = Depends(get_client), s: Settings = Depends(get_settings)):
"""Readiness: the model server answers and has our model."""
try:
models = await client.with_options(timeout=3, max_retries=0).models.list()
except openai.APIError as err:
log.warning("Not ready: %r", err)
return JSONResponse({"status": "model server unreachable"}, status_code=503)
if s.model not in [m.id for m in models.data]:
return JSONResponse({"status": f"model {s.model} not found"}, status_code=503)
return {"status": "ready"}
@app.post("/chat")
async def chat(req: ChatRequest, streamer=Depends(get_streamer), s: Settings = Depends(get_settings)):
messages = [{"role": "system", "content": SYSTEM}] + [m.model_dump() for m in req.messages]
async def events():
sent = 0
tokens = streamer(messages)
deadline = asyncio.get_running_loop().time() + s.answer_timeout
try:
while True:
try:
async with asyncio.timeout_at(deadline):
token = await anext(tokens)
except StopAsyncIteration:
break
yield sse({"type": "token", "text": token})
sent += 1
yield sse({"type": "done"})
except asyncio.CancelledError:
log.info("Client disconnected after %d tokens: stopped the model", sent)
raise
except Exception as err:
log.warning("Stream failed after %d tokens: %r", sent, err)
yield sse({"type": "error", "message": friendly(err)})
finally:
await tokens.aclose()
return StreamingResponse(events(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) - uvicorn prints this logger (despite the name, it is uvicorn's general log), so your lines appear next to its request lines.line 17
@lru_cacheremembers the result of the first call, so every later call returns the same object: a singleton, like a Spring@Bean. FastAPI's own docs recommend this for settings.line 21- One shared client for the whole app, also cached.line 26
- Code that runs once at startup (before
yield) and once at shutdown (after it), like@PostConstructand@PreDestroy.line 31 - Reading the settings here means a bad value stops the app at startup, with the message from
config.py, before it accepts any traffic.line 32 - Log where the app sends requests. The URL and model help every debugging session; the key never appears (and could not: it is not in the settings' text).line 33
- At most 50 messages of at most 8,000 characters each: a body over the limits gets a 422 response before any model call.line 47
- A dependency: FastAPI calls it for each request and passes the result to the endpoint. It gets the settings and client from their own dependencies. Tests replace the whole thing with a fake through
app.dependency_overrides, much like@MockBeanin a Spring test.line 54 lambda messages: ...is a one-line anonymous function, likemessages -> ...in Java. Calling it starts a stream for those messages.line 56TimeoutErroris Python's built-in timeout exception, raised by the answer deadline below. It is not related to the SDK'sAPITimeoutError.line 60- Order matters:
APITimeoutErroris a subclass ofAPIConnectionError, so check it first or it can never match.line 62 - A plain
defis fine here: it does no waiting. FastAPI runs plain functions in a thread pool andasync defones on the event loop.line 72 GET /v1/models: Ollama, vLLM and hosted APIs all list their models there.with_optionsmakes a copy of the client with a short timeout and no retries, because a readiness check must answer quickly.line 81APIErroris the parent of every SDK error, so this catches connection errors and error statuses alike. 503 means "not ready, try later".line 82- The server answers but your model is not there, for example not pulled yet in a fresh Ollama container (step 7).line 85
- The moment the answer must be finished: now plus
ANSWER_TIMEOUTseconds, on the event loop's clock.line 97 asyncio.timeout_atraisesTimeoutErrorif the code inside is still waiting at the deadline. It wraps only the wait for the next token, never theyield: a timeout around ayieldwould fire while the server is busy sending, outside this generator, and break the response.line 101anext()is the async version ofnext(): wait for the next token. When the stream has no more, it raisesStopAsyncIterationand the loop ends.line 102- The client went away and the server is cancelling this task. Log it, then re-raise: swallowing a cancellation leaves the task running.line 108
- Anything else, including the deadline's
TimeoutError. The real error goes to the log (%rshows its type); the client gets a safe message as an event, because the200 OKwas sent long ago.line 111 finallyalways runs.aclose()closes the model stream if it is still open, so an abandoned answer never keeps the model busy.line 115
curl -s -w "\n" localhost:8000/health
curl -s -w "\n" localhost:8000/ready
curl -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.jsoncurl -s -w "\n" localhost:8000/health
curl -s -w "\n" localhost:8000/ready
curl -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.jsoncurl.exe -s -w "\n" localhost:8000/health
curl.exe -s -w "\n" localhost:8000/ready
curl.exe -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d "@hi.json" {"status":"ok"}
{"status":"ready"}
data: {"type": "token", "text": "Hello"}
data: {"type": "token", "text": "!"}
data: {"type": "token", "text": " I"}
data: {"type": "token", "text": "'m"}
data: {"type": "token", "text": " here"}
...
data: {"type": "token", "text": "?"}
data: {"type": "done"} Stuck on this step?
/readysays{"status":"model server unreachable"}- Ollama is not running. Open the Ollama app (or run
ollama serve). The uvicorn terminal shows the real error on itsWARNING: Not ready:line. /readysays{"status":"model llama3.2:3b not found"}- The model is not pulled, or
LLM_MODELis spelled differently from whatollama listshows. Runollama pull llama3.2:3b. -w "\n": what is that?- curl prints the body without a newline at the end, so the next output would continue on the same line.
-wadds text after the response; curl turns\ninto a newline itself, in every shell. [Errno 48] Address already in use(or 98 on Linux)- Something else is on port 8000, maybe the server from lab 2. Stop it, or run this one on another port with
--port 8001and use that port in the curl commands.
Rate limiting per client
Each client may send a few requests at once and a steady number per minute; the rest get `429 Too Many Requests` with `Retry-After`.
Every chat request costs real compute (or real money on a hosted API). Without a limit, one buggy script in a loop can take your whole capacity. The classic fix is a token bucket per client: the bucket holds up to RATE_BURST tokens, each request spends one, and tokens refill at RATE_PER_MINUTE. So a person can send a few messages quickly, but a loop is slowed to the steady rate.
The limiter is plain Python in its own file, with the clock passed in so tests can control time (step 5). server.py gets a rate_limit dependency on /chat only: health checks must never be rate limited.
A refused request gets status 429 and a Retry-After header with the seconds to wait. Well-behaved clients (and the openai SDK itself, when it calls a hosted API) read that header and wait.
Stop the server and start it with a small limit, so you can hit it by hand: one request a minute, three at once.
RATE_PER_MINUTE=1 RATE_BURST=3 uv run uvicorn server:app
In PowerShell: $env:RATE_PER_MINUTE="1"; $env:RATE_BURST="3"; uv run uvicorn server:app. Then send five requests from the second terminal, and look at the headers of a sixth:
import time
from collections.abc import Callable
class RateLimiter:
"""A token bucket per client: up to `burst` requests at once, refilled at `per_minute`."""
def __init__(self, per_minute: int, burst: int, clock: Callable[[], float] = time.monotonic):
self.rate = per_minute / 60 # tokens added per second
self.burst = burst
self.clock = clock
self.buckets: dict[str, tuple[float, float]] = {} # key -> (tokens left, time of last check)
def check(self, key: str) -> float:
"""Spend one token for `key`. Returns 0 if allowed, otherwise the seconds to wait."""
now = self.clock()
tokens, last = self.buckets.get(key, (self.burst, now))
tokens = min(self.burst, tokens + (now - last) * self.rate)
if tokens >= 1:
self.buckets[key] = (tokens - 1, now)
return 0.0
self.buckets[key] = (tokens, now)
return (1 - tokens) / self.rate clockis any function that returns the time in seconds. The default,time.monotonic, only ever moves forward, even if the computer's clock is changed (likeSystem.nanoTime()in Java). Tests pass a fake clock.line 8- One entry per client: how many tokens are left, and when we last looked. A
tupleis a fixed pair of values.line 12 - A new client starts with a full bucket.
get(key, default)returns the default when the key is missing.line 17 - Refill: the time since the last check, times the rate.
minstops the bucket from filling beyondburst, so an hour of quiet does not allow a burst of 1,000.line 18 - Refused: the seconds until one whole token is back. That number becomes the
Retry-Afterheader.line 23
import asyncio
import json
import logging
import math
from contextlib import asynccontextmanager
from functools import lru_cache
from typing import Literal
import openai
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
from config import Settings, settings
from llm import make_client, stream_reply
from ratelimit import RateLimiter
SYSTEM = "You are a friendly, concise assistant for software developers."
log = logging.getLogger("uvicorn.error")
@lru_cache
def get_settings() -> Settings:
return settings()
@lru_cache
def get_client() -> openai.AsyncOpenAI:
return make_client(get_settings())
@lru_cache
def get_limiter() -> RateLimiter:
s = get_settings()
return RateLimiter(s.rate_per_minute, s.rate_burst)
@asynccontextmanager
async def lifespan(app: FastAPI):
s = get_settings() # bad settings stop the app here, at startup, not on the first request
log.info("Model %s at %s", s.model, s.base_url)
yield
await get_client().close()
app = FastAPI(title="Chat service", lifespan=lifespan)
class Message(BaseModel):
role: Literal["user", "assistant"]
content: str = Field(max_length=8000)
class ChatRequest(BaseModel):
messages: list[Message] = Field(min_length=1, max_length=50)
def sse(data: dict) -> str:
return f"data: {json.dumps(data)}\n\n"
def get_streamer(s: Settings = Depends(get_settings), client: openai.AsyncOpenAI = Depends(get_client)):
"""Which function streams the reply. Tests replace it with a fake."""
return lambda messages: stream_reply(client, s.model, messages, s.max_tokens)
async def rate_limit(request: Request, limiter: RateLimiter = Depends(get_limiter)):
key = request.client.host if request.client else "unknown"
wait = limiter.check(key)
if wait > 0:
raise HTTPException(429, "Too many requests. Slow down.", headers={"Retry-After": str(math.ceil(wait))})
def friendly(err: Exception) -> str:
if isinstance(err, TimeoutError):
return "The answer took too long, so it was stopped."
if isinstance(err, openai.APITimeoutError): # before APIConnectionError: it is a subclass
return "The model server did not respond in time."
if isinstance(err, openai.APIConnectionError):
return "Cannot reach the model server."
if isinstance(err, openai.NotFoundError):
return "The configured model does not exist on the model server."
return "The model failed while answering."
@app.get("/health")
def health():
"""Liveness: the process is up and serving requests. Never calls the model."""
return {"status": "ok"}
@app.get("/ready")
async def ready(client: openai.AsyncOpenAI = Depends(get_client), s: Settings = Depends(get_settings)):
"""Readiness: the model server answers and has our model."""
try:
models = await client.with_options(timeout=3, max_retries=0).models.list()
except openai.APIError as err:
log.warning("Not ready: %r", err)
return JSONResponse({"status": "model server unreachable"}, status_code=503)
if s.model not in [m.id for m in models.data]:
return JSONResponse({"status": f"model {s.model} not found"}, status_code=503)
return {"status": "ready"}
@app.post("/chat", dependencies=[Depends(rate_limit)])
async def chat(req: ChatRequest, streamer=Depends(get_streamer), s: Settings = Depends(get_settings)):
messages = [{"role": "system", "content": SYSTEM}] + [m.model_dump() for m in req.messages]
async def events():
sent = 0
tokens = streamer(messages)
deadline = asyncio.get_running_loop().time() + s.answer_timeout
try:
while True:
try:
async with asyncio.timeout_at(deadline):
token = await anext(tokens)
except StopAsyncIteration:
break
yield sse({"type": "token", "text": token})
sent += 1
yield sse({"type": "done"})
except asyncio.CancelledError:
log.info("Client disconnected after %d tokens: stopped the model", sent)
raise
except Exception as err:
log.warning("Stream failed after %d tokens: %r", sent, err)
yield sse({"type": "error", "message": friendly(err)})
finally:
await tokens.aclose()
return StreamingResponse(events(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}) - One limiter for the whole process, built from the settings. Tests replace it with their own.line 33
async defon purpose: FastAPI runsasyncdependencies on the event loop, one at a time, so two requests never change the buckets at the same moment. A plaindefwould run in a thread pool, and two threads could both spend the last token.line 67- The client's IP address is the key. Behind a load balancer every request seems to come from the balancer: step 10 shows the uvicorn setting that fixes it. With user accounts, use the user id or API key instead.line 68
- Raising
HTTPExceptionin a dependency stops the request before the endpoint runs: no model call.math.ceilrounds up, so clients never retry a fraction of a second too early.line 71 dependencies=[...]runsrate_limitbefore the endpoint without passing its result in. Only/chathas it.line 105
for i in 1 2 3 4 5; do curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.json; done
curl -s -D - -o /dev/null -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.jsonfor i in 1 2 3 4 5; do curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.json; done
curl -s -D - -o /dev/null -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.json1..5 | ForEach-Object { curl.exe -s -o NUL -w "%{http_code}\n" -X POST localhost:8000/chat -H "Content-Type: application/json" -d "@hi.json" }
curl.exe -s -D - -o NUL -X POST localhost:8000/chat -H "Content-Type: application/json" -d "@hi.json" 200 200 200 429 429 HTTP/1.1 429 Too Many Requests date: Sun, 29 Nov 2026 06:41:52 GMT server: uvicorn retry-after: 59 content-length: 42 content-type: application/json
Stuck on this step?
- All five are
200 - The server was started without the small limits, or the variables were set in a different terminal. Stop it and start it again with
RATE_PER_MINUTE=1 RATE_BURST=3on the same line as the command. - What do
-o /dev/null,-wand-D -do? -o /dev/nullthrows the body away (NULon Windows),-w "%{http_code}\n"prints only the status code, and-D -prints the response headers to the terminal.
Test it without a model
Ten fast tests: the limiter with a fake clock, the model call against a fake OpenAI-compatible server, and the endpoints with fake streamers.
Three test files, three kinds of fake. Each one replaces exactly one thing the code depends on, and nothing else:
test_ratelimit.py: a fake clock. Time only moves when the test says so, so "wait one second" takes no time and always gives the same result.test_llm.py: a fake model server.httpx2.MockTransportsends the SDK's HTTP requests to a Python function instead of the network. The function checks the request and answers with a real Server-Sent Events stream in the OpenAI format. So the real SDK parses a real stream, andstream_replyis tested for real.test_server.py: fake dependencies.app.dependency_overridesswaps the streamer, the limiter, the settings or the client for one test. FastAPI'sTestClientcalls the app in memory (no server, no port).
The test for the deadline uses a streamer that sends one token, then sleeps for ten seconds, with answer_timeout set to 0.2 seconds. It proves the client gets the partial answer and then the timeout message, in a fraction of a second. You could never make a real model do that on cue.
from ratelimit import RateLimiter
class FakeClock:
def __init__(self):
self.now = 1000.0
def __call__(self):
return self.now
def test_burst_then_wait():
clock = FakeClock()
limiter = RateLimiter(per_minute=60, burst=3, clock=clock) # one new token per second
assert [limiter.check("a") for _ in range(3)] == [0.0, 0.0, 0.0]
assert limiter.check("a") == 1.0 # empty: wait one second
clock.now += 1
assert limiter.check("a") == 0.0 # refilled one token
def test_clients_have_separate_buckets():
limiter = RateLimiter(per_minute=60, burst=1, clock=FakeClock())
assert limiter.check("a") == 0.0
assert limiter.check("a") > 0
assert limiter.check("b") == 0.0
def test_bucket_never_holds_more_than_burst():
clock = FakeClock()
limiter = RateLimiter(per_minute=60, burst=2, clock=clock)
limiter.check("a")
clock.now += 3600 # an hour of quiet
assert [limiter.check("a") for _ in range(3)] == [0.0, 0.0, 1.0] __call__makes an object callable like a function:clock()returnsclock.now. So it can stand in fortime.monotonic.line 8- 60 per minute is one token per second, which makes the numbers easy to check by hand.line 14
- A list comprehension: call
checkthree times and collect the results._is the usual name for a loop variable you do not use.line 15 - An hour passes instantly. The bucket refills only up to
burst, so the third request is refused.line 32
import asyncio
import json
import httpx2
from openai import AsyncOpenAI
from llm import stream_reply
def chunk(text: str) -> str:
body = {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": "m",
"choices": [{"index": 0, "delta": {"content": text}, "finish_reason": None}]}
return f"data: {json.dumps(body)}\n\n"
def fake_model_server(request: httpx2.Request) -> httpx2.Response:
"""Answers like an OpenAI-compatible server (Ollama, vLLM, a hosted API) with a stream."""
sent = json.loads(request.content)
assert request.url.path == "/v1/chat/completions"
assert sent["stream"] is True and sent["max_tokens"] == 64
body = chunk("Hel") + chunk("lo") + "data: [DONE]\n\n"
return httpx2.Response(200, text=body, headers={"content-type": "text/event-stream"})
async def collect(client: AsyncOpenAI) -> list[str]:
messages = [{"role": "user", "content": "hi"}]
return [token async for token in stream_reply(client, "m", messages, max_tokens=64)]
def test_stream_reply_reads_an_openai_compatible_stream():
http = httpx2.AsyncClient(transport=httpx2.MockTransport(fake_model_server))
client = AsyncOpenAI(base_url="http://fake/v1", api_key="test", http_client=http)
assert asyncio.run(collect(client)) == ["Hel", "lo"] - One streamed piece in the exact OpenAI format: a
data:line with achat.completion.chunkobject, then a blank line.line 10 - A fake server is just a function from request to response.line 16
- It also checks what the code sent: streaming on, and the
max_tokenslimit passed through.line 20 - OpenAI-compatible streams end with
data: [DONE]. The SDK stops reading there.line 21 - An async list comprehension:
async forinside the brackets collects every token into a list.line 27 - An HTTP client whose "network" is the function above. The SDK accepts it through
http_client=.line 31 asyncio.runruns an async function from normal code and returns its result, so the test itself stays a plain function.line 33
import asyncio
import json
from dataclasses import replace
import httpx2
from fastapi.testclient import TestClient
from openai import AsyncOpenAI
from config import settings
from ratelimit import RateLimiter
from server import app, get_client, get_limiter, get_settings, get_streamer
client = TestClient(app)
HI = {"messages": [{"role": "user", "content": "hi"}]}
def read_events(response):
return [json.loads(line[len("data: "):]) for line in response.iter_lines() if line.startswith("data: ")]
def use_fake(fake):
app.dependency_overrides[get_streamer] = lambda: fake
def setup_function():
app.dependency_overrides[get_limiter] = lambda: RateLimiter(per_minute=60, burst=100)
def teardown_function():
app.dependency_overrides.clear()
async def three_tokens(messages):
for token in ["Hel", "lo", " there"]:
yield token
def test_health_never_needs_the_model():
assert client.get("/health").json() == {"status": "ok"}
def test_streams_tokens_then_done():
use_fake(three_tokens)
with client.stream("POST", "/chat", json=HI) as r:
assert r.status_code == 200
events = read_events(r)
assert [e.get("text") for e in events] == ["Hel", "lo", " there", None]
assert events[-1] == {"type": "done"}
def test_slow_answer_is_cut_off():
async def slow(messages):
yield "Thinking"
await asyncio.sleep(10)
yield "never sent"
use_fake(slow)
app.dependency_overrides[get_settings] = lambda: replace(settings(), answer_timeout=0.2)
with client.stream("POST", "/chat", json=HI) as r:
events = read_events(r)
assert events == [
{"type": "token", "text": "Thinking"},
{"type": "error", "message": "The answer took too long, so it was stopped."},
]
def test_rate_limit_returns_429_with_retry_after():
limiter = RateLimiter(per_minute=6, burst=2, clock=lambda: 0.0) # time stands still
app.dependency_overrides[get_limiter] = lambda: limiter
use_fake(three_tokens)
codes = [client.post("/chat", json=HI).status_code for _ in range(3)]
assert codes == [200, 200, 429]
r = client.post("/chat", json=HI)
assert r.headers["retry-after"] == "10"
assert r.json() == {"detail": "Too many requests. Slow down."}
def fake_client(handler) -> AsyncOpenAI:
"""A real SDK client whose HTTP calls go to `handler` instead of the network."""
http = httpx2.AsyncClient(transport=httpx2.MockTransport(handler))
return AsyncOpenAI(base_url="http://fake/v1", api_key="test", http_client=http)
def test_ready_needs_the_model_on_the_server():
def models(request):
return httpx2.Response(200, json={"object": "list", "data": [{"id": "other-model", "object": "model"}]})
app.dependency_overrides[get_client] = lambda: fake_client(models)
app.dependency_overrides[get_settings] = lambda: replace(settings(), model="my-model")
r = client.get("/ready")
assert r.status_code == 503
assert r.json() == {"status": "model my-model not found"}
def test_ready_reports_an_unreachable_model_server():
def down(request):
raise httpx2.ConnectError("connection refused")
app.dependency_overrides[get_client] = lambda: fake_client(down)
r = client.get("/ready")
assert r.status_code == 503
assert r.json() == {"status": "model server unreachable"} - Calls the app in-process, like Spring's
MockMvcor supertest in Node.line 13 - pytest runs a function with this name before every test in the file: each test starts with a generous limiter, so the rate limit never gets in the way of other tests.line 25
- And this one after every test, so one test's fakes never leak into the next.line 29
- A fake streamer: the same shape as the real one (takes the messages, yields strings), with fixed output.line 33
dataclasses.replacecopies the frozen settings with one field changed. Only this test gets the short deadline.line 58- A clock that never moves: no tokens ever refill, so the result does not depend on how fast the machine runs the test.line 68
- Six a minute is one every 10 seconds, so a client with an empty bucket must wait exactly 10.line 74
- A real SDK client with a fake network, the same trick as
test_llm.py. Used for the/readytests.line 78 - What the SDK sees when nothing listens on the port: the test needs no stopped server, just this exception.line 97
uv run pytest -q .......... [100%] 10 passed in 0.86s
Stuck on this step?
ModuleNotFoundError: No module named 'httpx2'- Add it as a dev dependency:
uv add --dev httpx2. ModuleNotFoundError: No module named 'server'- Run pytest from the project folder with
uv run pytest, so the tests can importserver.py.
A small, safe Docker image
A two-stage Dockerfile with uv: the dependencies from `uv.lock`, your code, a non-root user, and no secrets.
An image is a frozen file system plus the command to start: everything your app needs, the same on every machine. The multi-stage pattern below is the one uv's own Docker guide recommends. Stage 1 has uv and installs the packages into /app/.venv. Stage 2 starts from a clean Python image and copies in only /app: no uv, no download cache, no build leftovers. Only stage 2 becomes your image.
The order of the lines is a speed trick. Docker caches each step and reuses it while its inputs are unchanged. The dependencies are installed from pyproject.toml and uv.lock before your code is copied in, so changing server.py reuses the cached dependency layer and rebuilds in seconds.
.dockerignore is .gitignore for the build: files it lists are never sent to Docker. Two lines matter most. .env holds keys, and anything copied into an image can be read by anyone who has the image. .venv/ is your laptop's virtual environment, built for your operating system: copied in, it would replace the Linux one from stage 1.
Build it, then run it. In a container, localhost is the container itself, so the app cannot reach the Ollama app at localhost:11434. On macOS and Windows, Docker Desktop provides the name host.docker.internal for your computer. On Linux, --network host puts the container on your computer's network, so localhost works as before (and -p is not needed).
# syntax=docker/dockerfile:1
# ---------- stage 1: build. Has uv; installs the dependencies into /app/.venv ----------
FROM python:3.12-slim-bookworm AS builder
COPY --from=ghcr.io/astral-sh/uv:0.11.32 /uv /uvx /bin/
ENV UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy \
UV_PYTHON_DOWNLOADS=0
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --locked --no-install-project --no-dev
COPY . /app
# ---------- stage 2: run. Only Python, the .venv and your code; no uv, no build cache ----------
FROM python:3.12-slim-bookworm
RUN groupadd --system --gid 999 app \
&& useradd --system --gid 999 --uid 999 --no-create-home app
COPY --from=builder --chown=app:app /app /app
ENV PATH="/app/.venv/bin:$PATH" \
PYTHONUNBUFFERED=1
WORKDIR /app
USER app
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"]
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000", "--timeout-graceful-shutdown", "30"] - Use the current Dockerfile syntax. Needed for the
--mountoptions below.line 1 - The official slim Python 3.12 image on Debian 12 ("bookworm"), named
builderso stage 2 can copy from it. Both stages use the same image, so Python sits at the same path in both, which the.venvrelies on.line 4 - Copies the
uvprogram out of uv's official image, pinned to an exact version so every build uses the same uv.line 5 - Compile
.pyfiles to bytecode during the build, so the container starts faster.line 7 - Copy files out of uv's cache instead of linking them: the cache is a separate mount and links across it do not work.line 8
- Use the image's Python; never download another one.line 9
- A cache that survives between builds (but is never part of the image), so packages are not downloaded again every time.line 12
- Bind mounts make
uv.lockandpyproject.tomlvisible to this one command without copying them into a layer.line 13 --lockedfails ifuv.lockdoes not matchpyproject.toml, so the image always has exactly the tested versions.--no-devleaves out pytest and httpx2.--no-install-projectinstalls only the dependencies; this project is a plain folder of modules with nothing to install itself.line 15- Now your code, minus everything in
.dockerignore.line 17 - A user and group called
appwith no login and no home folder. If someone breaks into the app, they are not root inside the container.line 22 - Copy
/app(the.venvand the code) from stage 1, owned by the new user.line 25 - Puts the
.venvprograms (python,uvicorn) first on the PATH: the same as activating the virtual environment.line 27 - Print log lines immediately instead of holding them in a buffer, so
docker logsshows them as they happen.line 28 - Every command from here, including the app itself, runs as
app, not root.line 31 - Documents the port. It does not open anything:
-p(orports:in compose) does.line 32 - Docker calls
/healthevery 30 seconds and marks the container unhealthy after 3 failures. The slim image has no curl, so a one-line Python script does the request.line 34 - The list form starts uvicorn directly (no shell in between), so it receives Docker's stop signal.
--host 0.0.0.0listens on every network interface: the default, 127.0.0.1, is unreachable from outside the container. On stop, uvicorn finishes open streams for up to 30 seconds.line 37
.venv/
__pycache__/
.pytest_cache/
.git/
.env
test_*.py - Your laptop's environment, possibly for macOS or Windows. The image builds its own.line 1
- Keys stay out of the image. Settings arrive as environment variables when the container starts.line 5
- Tests run before the build (in CI), not inside the production image.line 6
docker build -t chat-service:0.1.0 .
docker run --rm -p 8000:8000 -e LLM_BASE_URL=http://host.docker.internal:11434/v1 chat-service:0.1.0docker build -t chat-service:0.1.0 .
docker run --rm --network host chat-service:0.1.0docker build -t chat-service:0.1.0 .
docker run --rm -p 8000:8000 -e LLM_BASE_URL=http://host.docker.internal:11434/v1 chat-service:0.1.0 [+] Building 15.4s (17/17) FINISHED docker:desktop-linux => FROM ghcr.io/astral-sh/uv:0.11.32@sha256:df4cae8f3a96... => [builder 1/5] FROM docker.io/library/python:3.12-slim-bookworm@sha256:44cf1793efa7... => [stage-1 2/4] RUN groupadd --system --gid 999 app && useradd --system --gid 999 ... => [builder 4/5] RUN --mount=type=cache,target=/root/.cache/uv ... => [builder 5/5] COPY . /app => [stage-1 3/4] COPY --from=builder --chown=app:app /app /app => naming to docker.io/library/chat-service:0.1.0 INFO: Started server process [1] INFO: Waiting for application startup. INFO: Model llama3.2:3b at http://host.docker.internal:11434/v1 INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
uv run uvicorn first (port 8000), then try step 3's curl commands against the container: same answers. Ctrl+C stops the container, and --rm deletes it. docker image ls chat-service shows the size: about 200 MB, mostly the slim Python base; your packages add about 50 MB.Stuck on this step?
failed to compute cache key: "/uv.lock": not found- There is no
uv.lockyet (for example, you downloaded the project instead of runninguv add). Runuv lockonce, and commit the file. The lockfile at uv.lock needs to be updated- You changed
pyproject.tomlby hand. Runuv lock(or useuv add, which updates both), then build again. /readyfrom the container says the model server is unreachableLLM_BASE_URLpoints atlocalhostinside the container. Use the-e LLM_BASE_URL=http://host.docker.internal:11434/v1form on macOS and Windows, and--network hoston Linux. On Linux, Ollama must be running on the same machine.permission denied while trying to connect to the Docker daemon socket- Linux: your user is not in the
dockergroup yet. Runsudo usermod -aG docker $USER, log out and in again. Cannot connect to the Docker daemon- Docker is not running. Open Docker Desktop (macOS, Windows) or run
sudo systemctl start docker(Linux).
The app and Ollama together with docker compose
One file describes both containers, their settings, the network between them and the startup order.
docker compose starts several containers from one file, compose.yaml, and gives them a private network where each one is reachable by its service name. So the app finds Ollama at http://ollama:11434, and that URL is the only setting that changes.
Ollama's port is not published to your computer: only the app can reach it, which is what you want on a server. Downloaded models live in a named volume, ollama-models, so they survive restarts and rebuilds.
depends_on with condition: service_healthy waits until Ollama's health check passes before starting the app. A fresh Ollama container has no models, so pull one into it once (it lands in the volume). Until then, /ready says the model is not found, which is exactly the case it was built for.
GPUs. On a Linux machine with an NVIDIA GPU, install the NVIDIA Container Toolkit and remove the # from the deploy: lines: Ollama then runs the model on the GPU. On a Mac, Docker cannot use the Apple GPU: containers run in a Linux virtual machine, so Ollama in compose runs on the CPU and is several times slower than the Ollama app. For daily work on a Mac, run only the app in Docker (step 6) next to the Ollama app; use compose to test the whole stack, and on Linux servers.
Stop step 6's container first (Ctrl+C), since it uses port 8000. Then:
services:
app:
build: .
image: chat-service:0.1.0
ports:
- "8000:8000"
environment:
LLM_BASE_URL: http://ollama:11434/v1
LLM_API_KEY: ollama
LLM_MODEL: llama3.2:3b
ANSWER_TIMEOUT: "120"
RATE_PER_MINUTE: "20"
RATE_BURST: "5"
depends_on:
ollama:
condition: service_healthy
restart: unless-stopped
stop_grace_period: 40s
ollama:
image: ollama/ollama:latest
volumes:
- ollama-models:/root/.ollama
healthcheck:
test: ["CMD", "ollama", "list"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
# NVIDIA GPU on Linux (needs the NVIDIA Container Toolkit): remove the # below.
# deploy:
# resources:
# reservations:
# devices:
# - driver: nvidia
# count: all
# capabilities: [gpu]
volumes:
ollama-models: - Build the image from the
Dockerfilein this folder, and tag it with the name below.line 3 computer:container. Only the app is published.line 6ollamais the service name below: compose's network resolves it to that container.line 8- Quoted, so YAML keeps them as text, which is what environment variables always are.
config.pyturns them into numbers and checks them at startup.line 11 - Start the app only after Ollama's health check passes.line 16
- Restart a container that crashes, or after the machine reboots, unless you stopped it yourself.line 17
- On
docker compose down, wait up to 40 seconds before killing the app, longer than uvicorn's 30-second graceful shutdown. Docker's default is 10 seconds, which would cut long answers off.line 18 - Ollama's official image.
latestis fine for learning; in production pin a version tag (listed on the image's Docker Hub page) so an update never surprises you.line 21 - Where Ollama keeps models inside the container, stored in a named volume.line 23
ollama listasks the Ollama server for its models, so it fails until the server is up.line 25- The standard compose way to give a container NVIDIA GPUs. Linux only, with the NVIDIA Container Toolkit installed.line 31
docker compose up -d --build
docker compose exec ollama ollama pull llama3.2:3b
curl -s -w "\n" localhost:8000/ready
curl -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.jsondocker compose up -d --build
docker compose exec ollama ollama pull llama3.2:3b
curl -s -w "\n" localhost:8000/ready
curl -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.jsondocker compose up -d --build
docker compose exec ollama ollama pull llama3.2:3b
curl.exe -s -w "\n" localhost:8000/ready
curl.exe -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d "@hi.json" [+] Running 4/4
✔ Network chat-service_default Created
✔ Volume "chat-service_ollama-models" Created
✔ Container chat-service-ollama-1 Healthy
✔ Container chat-service-app-1 Started
pulling manifest
...
success
{"status":"ready"}
data: {"type": "token", "text": "Hello"}
...
data: {"type": "done"} -d runs the containers in the background. docker compose ps shows them and their health, docker compose logs -f app follows the app's log (Ctrl+C stops following, not the app), and docker compose down stops and removes the containers but keeps the volume with the model.Stuck on this step?
Bind for 0.0.0.0:8000 failed: port is already allocated- Something still uses port 8000: the container from step 6 or
uv run uvicorn. Stop it, then rundocker compose up -dagain. - The first answer takes a long time
- Ollama loads the model into memory on the first request. In compose on a Mac it also runs on the CPU (see above). Later answers are faster.
could not select device driver "nvidia" with capabilities: [[gpu]]- You enabled the
deploy:lines on a machine without an NVIDIA GPU or without the NVIDIA Container Toolkit. Put the#back, or install the toolkit.
Serve a model yourself with vLLM
Run vLLM's OpenAI-compatible server on a GPU machine, and know what it needs and why it is fast.
Ollama is built for one person on one machine. vLLM is built to serve many users at once from GPUs. Two ideas make it fast:
- Continuous batching. A GPU does nearly the same work for 30 sequences in one step as for one. vLLM adds new requests to the running batch at every step, and removes finished ones, instead of waiting for a whole batch to finish. Each user sees roughly the same speed; the server produces many times more tokens per second in total.
- PagedAttention. The model keeps memory for every request it is answering (the "KV cache": what it has computed about the text so far). vLLM stores it in small pages, like an operating system does with RAM, so little memory is wasted and more requests fit at once.
What it needs. Linux and an NVIDIA GPU with compute capability 7.0 or newer (AMD, Intel and TPU builds exist too). GPU memory decides what fits: the weights take about 2 bytes per parameter in 16-bit precision, so the 1.5-billion-parameter model below needs about 3 GB, and an 8B model about 16 GB, plus room for the KV cache. vLLM claims 90% of the GPU's memory at startup by default (--gpu-memory-utilization 0.9), so do not share the GPU with other programs. --max-model-len caps the context length, which caps the KV cache each request can need.
Not on a Mac. vLLM's releases are built for Linux with CUDA (NVIDIA's GPU platform), which Macs do not have. There is an experimental CPU-only build for Apple silicon, compiled from source, but it is far too slow to be worth it. On a Mac, keep Ollama for local work and use a rented Linux GPU machine for this step.
The model: Qwen2.5-1.5B-Instruct, small, good at chat, and open on Hugging Face without signing anything. (Meta's Llama models on Hugging Face are "gated": accept the license on the model page, create a token, and set HF_TOKEN before starting vLLM.) vLLM downloads the weights to ~/.cache/huggingface on first start.
On the GPU machine, in a new folder (vLLM's install guide uses uv too; --torch-backend=auto picks the PyTorch build that matches your GPU driver):
uv venv --python 3.12 --seed
source .venv/bin/activate
uv pip install vllm --torch-backend=auto
vllm serve Qwen/Qwen2.5-1.5B-Instruct --port 8001 --api-key local-secret --max-model-len 8192 INFO ... vLLM API server version 0.x.y INFO ... Starting to load model Qwen/Qwen2.5-1.5B-Instruct... INFO ... Loading weights took 2.10 seconds INFO ... Maximum concurrency for 8,192 tokens per request: 92.50x INFO ... Starting vLLM API server 0 on http://0.0.0.0:8001 INFO: Application startup complete.
Stuck on this step?
CUDA out of memoryat startup- The model plus its KV cache does not fit. Lower
--max-model-len(for example4096), pick a smaller model, or checknvidia-smifor other programs using the GPU. Bfloat16 is only supported on GPUs with compute capability of at least 8.0- Older GPUs such as the T4 cannot use bfloat16. Add
--dtype halfto the command. - Startup takes minutes
- The first start downloads the weights and compiles GPU kernels. Later starts reuse
~/.cache/huggingfaceand are much faster. - Prefer Docker on the GPU machine?
- With the NVIDIA Container Toolkit installed:
docker run --gpus all --ipc=host -p 8001:8000 -v ~/.cache/huggingface:/root/.cache/huggingface vllm/vllm-openai:latest --model Qwen/Qwen2.5-1.5B-Instruct --api-key local-secret --max-model-len 8192. Step 9 has the compose version.
Point the app at vLLM, and compare
Switch from Ollama to vLLM by changing three settings, and know when each option is the right one.
vLLM speaks the same OpenAI-compatible API as Ollama, so your code does not change: only LLM_BASE_URL, LLM_API_KEY and LLM_MODEL. /ready checks the new model exists, through vLLM's own /v1/models.
Reaching the GPU machine safely. Never open vLLM's port to the internet: the API key is the only lock. From your laptop, an SSH tunnel makes the remote port appear on your own computer: ssh -N -L 8001:localhost:8001 you@gpu-machine (leave it running; -N means "no remote command, only the tunnel"). Then start the app on your laptop with the three settings changed, and run step 3's curl commands in another terminal:
LLM_BASE_URL=http://localhost:8001/v1 LLM_API_KEY=local-secret LLM_MODEL=Qwen/Qwen2.5-1.5B-Instruct uv run uvicorn server:app
(PowerShell: set the three variables with $env:NAME="value"; first.)
On a GPU server, compose.vllm.yaml below runs both containers together: the same app image, vLLM instead of Ollama. The key comes from your shell, never from the file.
Ollama, vLLM or a hosted API?
| Ollama | vLLM | Hosted API | |
|---|---|---|---|
| Built for | one developer, one machine | many users on your GPUs | everyone, no hardware |
| Runs on | Mac, Windows, Linux; CPU or GPU | Linux with a GPU | someone else's data centre |
| Many requests at once | a few in parallel per model (OLLAMA_NUM_PARALLEL) |
continuous batching: dozens to hundreds | the provider batches; you get rate limits |
| Throughput | fine for one person | highest per GPU | not your problem |
| Cost | your laptop | GPU hours, busy or idle | per token; nothing when idle |
| Models | many open models, quantized | most open models from Hugging Face | the provider's models, often the strongest |
| Data | never leaves your machine | never leaves your servers | sent to the provider |
The rule of thumb: Ollama to develop. A hosted API while traffic is small or spiky, or when you need the strongest models. vLLM when traffic is steady enough to keep a GPU busy, or when data must stay on your servers. The exercise below computes the break-even point: an idle GPU still costs money every hour.
Try the difference yourself: with a high limit (RATE_BURST=50), send 16 requests at the same time to each setup (mac/Linux: for i in $(seq 16); do curl -s -o /dev/null -w "%{time_total}\n" -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.json & done; wait). With Ollama on a laptop, the later requests wait for the earlier ones and the times grow; with vLLM on a GPU, they finish at about the same time.
# Instead of the Ollama lines: vLLM through the SSH tunnel. Everything else stays.
LLM_BASE_URL=http://localhost:8001/v1
LLM_API_KEY=local-secret
LLM_MODEL=Qwen/Qwen2.5-1.5B-Instruct - vLLM serves the same
/v1API on the port you chose.line 2 - The
--api-keyyou gavevllm serve. vLLM rejects requests without it with 401.line 3 - vLLM names the model by its Hugging Face id, exactly as you passed it to
vllm serve.line 4
# Linux with an NVIDIA GPU only. Start with:
# VLLM_API_KEY=pick-a-long-secret docker compose -f compose.vllm.yaml up -d
services:
app:
build: .
image: chat-service:0.1.0
ports:
- "8000:8000"
environment:
LLM_BASE_URL: http://vllm:8000/v1
LLM_API_KEY: ${VLLM_API_KEY:?set VLLM_API_KEY}
LLM_MODEL: Qwen/Qwen2.5-1.5B-Instruct
ANSWER_TIMEOUT: "120"
RATE_PER_MINUTE: "20"
RATE_BURST: "5"
depends_on:
vllm:
condition: service_healthy
restart: unless-stopped
stop_grace_period: 40s
vllm:
image: vllm/vllm-openai:latest
command: ["--model", "Qwen/Qwen2.5-1.5B-Instruct", "--max-model-len", "8192",
"--api-key", "${VLLM_API_KEY:?set VLLM_API_KEY}"]
ipc: host
volumes:
- hf-cache:/root/.cache/huggingface
healthcheck:
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
interval: 15s
timeout: 5s
start_period: 300s
restart: unless-stopped
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
volumes:
hf-cache: - Inside the compose network, vLLM listens on its default port, 8000, under the service name
vllm.line 10 - compose fills
${...}from your shell.:?stops with that message if the variable is not set, instead of starting with an empty key.line 11 - The three changed settings. The app image is the same one as before.line 12
- vLLM's official image. The
commandlist holds the options for its server, the same ones as aftervllm servein step 8. Pin a version tag in production.line 23 - vLLM's docs ask for this: PyTorch uses shared memory between processes, and Docker's default shared memory is tiny.line 26
- Downloaded weights live in a volume, so a restart does not download them again.line 28
- vLLM's
/healthneeds no key. The image has Python, so Python does the request.line 30 - Up to five minutes to download and load before failures count. The app waits for this check.line 33
- Gives the container every NVIDIA GPU on the machine. vLLM does not start without one.line 35
curl -s -w "\n" localhost:8000/ready
curl -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.json {"status":"ready"}
data: {"type": "token", "text": "Hello"}
data: {"type": "token", "text": "!"}
...
data: {"type": "done"} Stuck on this step?
/readysaysmodel Qwen/Qwen2.5-1.5B-Instruct not foundLLM_MODELmust match the name vLLM serves exactly.curl -s localhost:8001/v1/models -H "Authorization: Bearer local-secret"lists it.- Chat errors with "The model failed while answering." and the log shows
AuthenticationError LLM_API_KEYdoes not match--api-key. Both must be the same string.- To start the GPU compose file
- On the GPU machine, in the project folder:
VLLM_API_KEY=pick-a-long-secret docker compose -f compose.vllm.yaml up -d.-fpicks the file; without it compose usescompose.yaml.
Deploy to a container platform
Push the image to a registry and run it on any platform that runs containers, with the settings it needs.
Every container platform (a managed container service from a cloud provider, a Kubernetes cluster, a platform-as-a-service) asks for the same things: an image in a registry, the port, environment variables and secrets, health checks, and how many copies to run. Your image already answers all of them.
Build for the right CPU. Macs with Apple silicon build arm64 images by default, while most servers are x86_64 (amd64). --platform linux/amd64 builds for the server, and --push uploads the result. Log in to your registry first with docker login and the address your provider gives you; registry.example.com/your-team below stands for it. Tag images with a version, never only latest, so you always know what runs and can roll back.
The checklist for the platform's settings:
- Port: 8000.
- Environment variables:
LLM_BASE_URL,LLM_MODELand the limits.LLM_API_KEYas a secret (the platform's secret store), never as plain text in a config file. - Health checks: liveness on
/health; readiness (or the startup check) on/ready. - Request timeout: longer than
ANSWER_TIMEOUT(120 seconds here). Many platforms cut requests at 30 or 60 seconds by default, which would cut long answers off. - Streaming: make sure the platform's proxy does not buffer responses, or users get the whole answer at once at the end. The
X-Accel-Buffering: noheader the app sends helps with nginx-based proxies. - Shutdown: a grace period of at least 30 seconds, so uvicorn can finish open answers when a new version rolls out.
- Real client IPs: behind the platform's load balancer, set
FORWARDED_ALLOW_IPSto the balancer's addresses (*only if nothing else can reach the container). uvicorn then reads the client's address from theX-Forwarded-Forheader, and the rate limiter sees real users instead of one balancer. - Copies: at least one always running (no cold start while a user waits), more as traffic grows. Each copy has its own in-memory rate limiter; move the buckets to Redis when you run several.
Where the model runs is a separate decision. Most teams start with a hosted API (set the three settings to the provider's values and put the key in the secret store), and add a vLLM server on GPU machines later, behind the same three settings.
docker login registry.example.com
docker buildx build --platform linux/amd64 -t registry.example.com/your-team/chat-service:0.1.0 --push . Login Succeeded [+] Building 41.2s (15/15) FINISHED => [builder 4/5] RUN --mount=type=cache,target=/root/.cache/uv ... => pushing registry.example.com/your-team/chat-service:0.1.0 with docker ...
Stuck on this step?
exec format errorwhen the platform starts the container- The image was built for the wrong CPU, usually
arm64from an Apple silicon Mac. Rebuild with--platform linux/amd64. - The platform keeps restarting the container
- Its liveness check fails. Check the configured path is
/health(not/ready) and the port is 8000. A liveness check on/readyrestarts healthy apps whenever the model server has a hiccup. - Answers arrive all at once at the end
- A proxy in front buffers the stream. Check the platform's docs for streaming or Server-Sent Events support and turn response buffering off.
Check it works
Two checks. The tests pass with no model at all. Then, with the compose stack from step 7 running (docker compose up -d, and the model pulled into it), the app in its container reports it is ready: the image, the settings, the network to Ollama and the model all work together.
For a last look, send a chat request (curl -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.json) and watch the tokens stream from the container.
uv run pytest -q && curl -s -w "\n" localhost:8000/ready .......... [100%]
10 passed in 0.86s
{"status":"ready"} Troubleshooting
The app container exits right away with ERROR: Application startup failed. Exiting.
A setting is invalid. docker compose logs app shows the message from config.py just above, for example ValueError: RATE_BURST must be a number, got 'lots'. Fix the value in compose.yaml (or the platform's settings) and start again.
Code changes do not show up in the container
The image still has the old code. Rebuild: docker compose up -d --build. docker compose restart only restarts the old image.
Every request gets 429 behind a load balancer or proxy
All requests seem to come from the proxy's address, so they share one bucket. Set FORWARDED_ALLOW_IPS to the proxy's address (step 10), so uvicorn uses the real client address from X-Forwarded-For.
Long answers end with "The answer took too long, so it was stopped."
They hit ANSWER_TIMEOUT. On a CPU, answers are slow: raise it, or lower MAX_TOKENS so answers are shorter. Keep the platform's request timeout longer than ANSWER_TIMEOUT.
The image is over 1 GB
Something big was copied in. Check .dockerignore lists .venv/, and that you build from the project folder. docker history chat-service:0.1.0 shows the size of every layer.
What changes in production
- One image, every environment. Build once, test that exact image, and promote it from staging to production by its version tag. Only environment variables differ.
- Liveness and readiness are different questions. Liveness asks "should I restart you?" and must never depend on the model server. Readiness asks "should I send you traffic?" and does.
- Limit everything a request can consume: body size, history length, answer length (
max_tokens), answer time, and requests per client. Each limit turns an outage or a surprise bill into a clear error. - Keep secrets out of images and logs.
.dockerignorekeeps.envout of the image, the platform injects the key at runtime, andrepr=Falsekeeps it out of logs. - Choose where the model runs by traffic and data. A hosted API while traffic is small or spiky, your own vLLM on GPUs when traffic is steady or data must stay in-house, and the same three settings to move between them.
Interview angle
“How would you take an LLM chat service to production, and when would you self-host the model?”
I package the API as a multi-stage Docker image: dependencies from a lockfile in a build stage, then only the virtual environment and code in a slim runtime stage, running as a non-root user, with no secrets inside. Every setting comes from environment variables and is validated at startup. The service exposes a liveness check that never touches the model and a readiness check that does, enforces per-request limits (body size, max_tokens, a deadline for the whole answer) and a per-client rate limit returning 429 with Retry-After, and shuts down gracefully so rollouts do not cut streams. For the model, the client speaks the OpenAI-compatible API, so Ollama, vLLM or a hosted provider is a configuration choice. I start with a hosted API, because idle GPUs cost money; I move to vLLM when traffic is steady enough to keep GPUs busy, since continuous batching and PagedAttention give far higher throughput per GPU, or when data must stay on our servers.
Clean up
Stop and remove the containers. -v also deletes the volume with the downloaded model (about 2 GB); leave it off to keep the model for next time. The last line removes the image you built.
docker compose down -v
docker image rm chat-service:0.1.0 Practice
No model needed: these run in your browser and check your answer.
A sliding-window rate limiter
A different rate limiter: allow at most limit requests in any window seconds. Write allow(log, now, limit, window). log is a list of the times (in seconds) of this client's earlier allowed requests, oldest first. First remove from log every time that is window seconds old or older (now - t >= window). Then, if fewer than limit times remain, append now and return True; otherwise return False and leave log as it is. Change log in place: the caller keeps it between requests.
def allow(log, now, limit, window):
# your code here
log.append(now)
return True
log = []
print([allow(log, t, 2, 10) for t in [0, 1, 2, 10, 11]])
Hint
Remove old entries from the front with `while log and now - log[0] >= window: log.pop(0)`. Then compare `len(log)` with `limit`.
When does your own GPU pay off?
A GPU machine costs the same every hour, busy or idle. Write cost_per_million(gpu_per_hour, tokens_per_second, utilization): the dollars per million generated tokens, where tokens_per_second is the server's total throughput when busy and utilization (0 to 1) is the share of the hour it is actually busy. If utilization is 0, return float("inf") (infinitely expensive per token). Example numbers only: a $2-an-hour GPU producing 1,000 tokens a second, fully busy, costs about $0.56 per million tokens; idle three-quarters of the time, it costs four times as much.
def cost_per_million(gpu_per_hour, tokens_per_second, utilization):
tokens_per_hour = tokens_per_second * 3600
return gpu_per_hour / tokens_per_hour * 1_000_000
print(round(cost_per_million(2.0, 1000, 1.0), 4))
print(round(cost_per_million(2.0, 1000, 0.25), 4))
Hint
Tokens actually produced in an hour are `tokens_per_second * 3600 * utilization`. Divide the hourly price by that, times 1,000,000. Check for 0 first.
The full project
Every file from this lab, as it is after the last step.