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

1 / 8

0 of 10 steps done

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.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
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.

Run
uv --version
You should see
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.

Run
ollama --version
You should see
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.

Run
ollama pull llama3.2:3b
You should see
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.

Run
docker --version
docker compose version
You should seeyour text will differ: the model writes it
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:

Run
nvidia-smi
You should seeyour text will differ: the model writes it
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 5xx.xx       Driver Version: 5xx.xx       CUDA Version: 12.x     |
|   0  NVIDIA L4             ...   |   0MiB / 23034MiB |
+-----------------------------------------------------------------------------+
1

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.

.gitignore
.venv/
__pycache__/
.pytest_cache/
.env
  1. Never commit .env: in production it holds a real key.line 4
hi.json
{"messages": [{"role": "user", "content": "Say hello and name one sorting algorithm."}]}
  1. A chat request body, used by curl -d @hi.json in later steps. The @ tells curl to read the body from this file, which avoids quoting trouble in every shell.line 1
Run
uv init --python 3.12 chat-service
cd chat-service
rm main.py
uv add fastapi uvicorn openai python-dotenv
uv add --dev pytest httpx2
You should seeyour text will differ: the model writes it
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.
2

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.

.env
# 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
  1. 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
  2. Seconds to wait for the model server: to connect, and for each next piece of a streamed answer.line 7
  3. Seconds for one whole answer, however steadily it streams. Step 3 enforces it.line 8
  4. The rate limit (step 4): 20 requests a minute per client, at most 5 at once.line 10
config.py
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),
    )
  1. If there is no .env file, this does nothing and raises no error. That is exactly what happens in the container.line 6
  2. A read-only data class, like a Java record. Nothing can change the settings after startup.line 9
  3. field(repr=False): the key is a normal field, but print(settings()) and log lines leave it out.line 12
  4. Reads a number from the environment. cast is the type to convert to, passed as a function: int or float (in Python a type can be called like a function: int("5") is 5).line 21
  5. from None hides the original int() 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
  6. Zero or negative limits make no sense (and a rate of zero would divide by zero later). Refuse them too.line 27
  7. Builds the settings from the environment. The second argument of each get is the default for when the variable is not set.line 32
Run
uv run python -c "from config import settings; print(settings())"
RATE_BURST=lots uv run python -c "from config import settings; settings()"
You should see
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'
Why this way? This is the "config" rule of twelve-factor apps: one build, many environments, the differences in environment variables. It is also why the key never ends up inside the Docker image.
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 with echo $LLM_MODEL (PowerShell: $env:LLM_MODEL).
3

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_TIMEOUT limits the whole answer, because a model that keeps sending a token every few seconds never trips the first one.
  • max_tokens caps 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."}.

llm.py
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
  1. Built once and shared (get_client in server.py). The client keeps connections to the model server open between requests, which saves time on every call.line 8
  2. timeout comes from LLM_TIMEOUT. One retry for temporary errors (connection failures, 429, 5xx): a user is waiting, so retry little and fail fast.line 10
  3. AsyncIterator[str] is the return type: something you read with async for, getting strings.line 13
  4. The longest answer the model may write. Ollama, vLLM and most hosted APIs accept max_tokens; some hosted APIs prefer the newer name max_completion_tokens.line 18
  5. 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
  6. Each chunk carries a small piece of text in delta.content. Some chunks (like the last one) carry none: skip them.line 24
server.py
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"})
  1. uvicorn prints this logger (despite the name, it is uvicorn's general log), so your lines appear next to its request lines.line 17
  2. @lru_cache remembers 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
  3. One shared client for the whole app, also cached.line 26
  4. Code that runs once at startup (before yield) and once at shutdown (after it), like @PostConstruct and @PreDestroy.line 31
  5. 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
  6. 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
  7. 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
  8. 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 @MockBean in a Spring test.line 54
  9. lambda messages: ... is a one-line anonymous function, like messages -> ... in Java. Calling it starts a stream for those messages.line 56
  10. TimeoutError is Python's built-in timeout exception, raised by the answer deadline below. It is not related to the SDK's APITimeoutError.line 60
  11. Order matters: APITimeoutError is a subclass of APIConnectionError, so check it first or it can never match.line 62
  12. A plain def is fine here: it does no waiting. FastAPI runs plain functions in a thread pool and async def ones on the event loop.line 72
  13. GET /v1/models: Ollama, vLLM and hosted APIs all list their models there. with_options makes a copy of the client with a short timeout and no retries, because a readiness check must answer quickly.line 81
  14. APIError is the parent of every SDK error, so this catches connection errors and error statuses alike. 503 means "not ready, try later".line 82
  15. The server answers but your model is not there, for example not pulled yet in a fresh Ollama container (step 7).line 85
  16. The moment the answer must be finished: now plus ANSWER_TIMEOUT seconds, on the event loop's clock.line 97
  17. asyncio.timeout_at raises TimeoutError if the code inside is still waiting at the deadline. It wraps only the wait for the next token, never the yield: a timeout around a yield would fire while the server is busy sending, outside this generator, and break the response.line 101
  18. anext() is the async version of next(): wait for the next token. When the stream has no more, it raises StopAsyncIteration and the loop ends.line 102
  19. 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
  20. Anything else, including the deadline's TimeoutError. The real error goes to the log (%r shows its type); the client gets a safe message as an event, because the 200 OK was sent long ago.line 111
  21. finally always runs. aclose() closes the model stream if it is still open, so an abandoned answer never keeps the model busy.line 115
Run
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.json
You should seeyour text will differ: the model writes it
{"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?
/ready says {"status":"model server unreachable"}
Ollama is not running. Open the Ollama app (or run ollama serve). The uvicorn terminal shows the real error on its WARNING: Not ready: line.
/ready says {"status":"model llama3.2:3b not found"}
The model is not pulled, or LLM_MODEL is spelled differently from what ollama list shows. Run ollama 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. -w adds text after the response; curl turns \n into 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 8001 and use that port in the curl commands.
4

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:

ratelimit.py
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
  1. clock is any function that returns the time in seconds. The default, time.monotonic, only ever moves forward, even if the computer's clock is changed (like System.nanoTime() in Java). Tests pass a fake clock.line 8
  2. One entry per client: how many tokens are left, and when we last looked. A tuple is a fixed pair of values.line 12
  3. A new client starts with a full bucket. get(key, default) returns the default when the key is missing.line 17
  4. Refill: the time since the last check, times the rate. min stops the bucket from filling beyond burst, so an hour of quiet does not allow a burst of 1,000.line 18
  5. Refused: the seconds until one whole token is back. That number becomes the Retry-After header.line 23
server.py 12 new or changed lines
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"})
  1. One limiter for the whole process, built from the settings. Tests replace it with their own.line 33
  2. async def on purpose: FastAPI runs async dependencies on the event loop, one at a time, so two requests never change the buckets at the same moment. A plain def would run in a thread pool, and two threads could both spend the last token.line 67
  3. 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
  4. Raising HTTPException in a dependency stops the request before the endpoint runs: no model call. math.ceil rounds up, so clients never retry a fraction of a second too early.line 71
  5. dependencies=[...] runs rate_limit before the endpoint without passing its result in. Only /chat has it.line 105
Run
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.json
You should seeyour text will differ: the model writes it
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
Why this way? Rate limiting belongs in the app even if a gateway adds its own later: the app knows who the user is and what a request costs. In-memory buckets are right for one process; with several replicas, keep the buckets in a shared store such as Redis, so the limit holds across all of them.
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=3 on the same line as the command.
What do -o /dev/null, -w and -D - do?
-o /dev/null throws the body away (NUL on Windows), -w "%{http_code}\n" prints only the status code, and -D - prints the response headers to the terminal.
5

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.MockTransport sends 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, and stream_reply is tested for real.
  • test_server.py: fake dependencies. app.dependency_overrides swaps the streamer, the limiter, the settings or the client for one test. FastAPI's TestClient calls 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.

test_ratelimit.py
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]
  1. __call__ makes an object callable like a function: clock() returns clock.now. So it can stand in for time.monotonic.line 8
  2. 60 per minute is one token per second, which makes the numbers easy to check by hand.line 14
  3. A list comprehension: call check three times and collect the results. _ is the usual name for a loop variable you do not use.line 15
  4. An hour passes instantly. The bucket refills only up to burst, so the third request is refused.line 32
test_llm.py
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"]
  1. One streamed piece in the exact OpenAI format: a data: line with a chat.completion.chunk object, then a blank line.line 10
  2. A fake server is just a function from request to response.line 16
  3. It also checks what the code sent: streaming on, and the max_tokens limit passed through.line 20
  4. OpenAI-compatible streams end with data: [DONE]. The SDK stops reading there.line 21
  5. An async list comprehension: async for inside the brackets collects every token into a list.line 27
  6. An HTTP client whose "network" is the function above. The SDK accepts it through http_client=.line 31
  7. asyncio.run runs an async function from normal code and returns its result, so the test itself stays a plain function.line 33
test_server.py
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"}
  1. Calls the app in-process, like Spring's MockMvc or supertest in Node.line 13
  2. 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
  3. And this one after every test, so one test's fakes never leak into the next.line 29
  4. A fake streamer: the same shape as the real one (takes the messages, yields strings), with fixed output.line 33
  5. dataclasses.replace copies the frozen settings with one field changed. Only this test gets the short deadline.line 58
  6. 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
  7. Six a minute is one every 10 seconds, so a client with an empty bucket must wait exactly 10.line 74
  8. A real SDK client with a fake network, the same trick as test_llm.py. Used for the /ready tests.line 78
  9. What the SDK sees when nothing listens on the port: the test needs no stopped server, just this exception.line 97
Run
uv run pytest -q
You should see
..........                                                               [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 import server.py.
6

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

Dockerfile
# 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"]
  1. Use the current Dockerfile syntax. Needed for the --mount options below.line 1
  2. The official slim Python 3.12 image on Debian 12 ("bookworm"), named builder so stage 2 can copy from it. Both stages use the same image, so Python sits at the same path in both, which the .venv relies on.line 4
  3. Copies the uv program out of uv's official image, pinned to an exact version so every build uses the same uv.line 5
  4. Compile .py files to bytecode during the build, so the container starts faster.line 7
  5. 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
  6. Use the image's Python; never download another one.line 9
  7. A cache that survives between builds (but is never part of the image), so packages are not downloaded again every time.line 12
  8. Bind mounts make uv.lock and pyproject.toml visible to this one command without copying them into a layer.line 13
  9. --locked fails if uv.lock does not match pyproject.toml, so the image always has exactly the tested versions. --no-dev leaves out pytest and httpx2. --no-install-project installs only the dependencies; this project is a plain folder of modules with nothing to install itself.line 15
  10. Now your code, minus everything in .dockerignore.line 17
  11. A user and group called app with no login and no home folder. If someone breaks into the app, they are not root inside the container.line 22
  12. Copy /app (the .venv and the code) from stage 1, owned by the new user.line 25
  13. Puts the .venv programs (python, uvicorn) first on the PATH: the same as activating the virtual environment.line 27
  14. Print log lines immediately instead of holding them in a buffer, so docker logs shows them as they happen.line 28
  15. Every command from here, including the app itself, runs as app, not root.line 31
  16. Documents the port. It does not open anything: -p (or ports: in compose) does.line 32
  17. Docker calls /health every 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
  18. The list form starts uvicorn directly (no shell in between), so it receives Docker's stop signal. --host 0.0.0.0 listens 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
.dockerignore
.venv/
__pycache__/
.pytest_cache/
.git/
.env
test_*.py
  1. Your laptop's environment, possibly for macOS or Windows. The image builds its own.line 1
  2. Keys stay out of the image. Settings arrive as environment variables when the container starts.line 5
  3. Tests run before the build (in CI), not inside the production image.line 6
Run
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.0
You should seeyour text will differ: the model writes it
[+] 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)
Why this way? Stop the old 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.lock yet (for example, you downloaded the project instead of running uv add). Run uv lock once, and commit the file.
The lockfile at uv.lock needs to be updated
You changed pyproject.toml by hand. Run uv lock (or use uv add, which updates both), then build again.
/ready from the container says the model server is unreachable
LLM_BASE_URL points at localhost inside the container. Use the -e LLM_BASE_URL=http://host.docker.internal:11434/v1 form on macOS and Windows, and --network host on 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 docker group yet. Run sudo 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).
7

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:

compose.yaml
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:
  1. Build the image from the Dockerfile in this folder, and tag it with the name below.line 3
  2. computer:container. Only the app is published.line 6
  3. ollama is the service name below: compose's network resolves it to that container.line 8
  4. Quoted, so YAML keeps them as text, which is what environment variables always are. config.py turns them into numbers and checks them at startup.line 11
  5. Start the app only after Ollama's health check passes.line 16
  6. Restart a container that crashes, or after the machine reboots, unless you stopped it yourself.line 17
  7. 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
  8. Ollama's official image. latest is 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
  9. Where Ollama keeps models inside the container, stored in a named volume.line 23
  10. ollama list asks the Ollama server for its models, so it fails until the server is up.line 25
  11. The standard compose way to give a container NVIDIA GPUs. Linux only, with the NVIDIA Container Toolkit installed.line 31
Run
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.json
You should seeyour text will differ: the model writes it
[+] 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"}
Why this way? -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 run docker compose up -d again.
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.
8

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

Run
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
You should seeyour text will differ: the model writes it
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.
Why this way? The "Maximum concurrency" line is vLLM telling you how many full-length requests fit in the KV cache at once. That number, not the speed of one answer, is why you would run vLLM: it is the difference between serving one user and serving dozens from the same GPU.
Stuck on this step?
CUDA out of memory at startup
The model plus its KV cache does not fit. Lower --max-model-len (for example 4096), pick a smaller model, or check nvidia-smi for 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 half to the command.
Startup takes minutes
The first start downloads the weights and compiles GPU kernels. Later starts reuse ~/.cache/huggingface and 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.
9

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.

.env
# 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
  1. vLLM serves the same /v1 API on the port you chose.line 2
  2. The --api-key you gave vllm serve. vLLM rejects requests without it with 401.line 3
  3. vLLM names the model by its Hugging Face id, exactly as you passed it to vllm serve.line 4
compose.vllm.yaml
# 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:
  1. Inside the compose network, vLLM listens on its default port, 8000, under the service name vllm.line 10
  2. compose fills ${...} from your shell. :? stops with that message if the variable is not set, instead of starting with an empty key.line 11
  3. The three changed settings. The app image is the same one as before.line 12
  4. vLLM's official image. The command list holds the options for its server, the same ones as after vllm serve in step 8. Pin a version tag in production.line 23
  5. vLLM's docs ask for this: PyTorch uses shared memory between processes, and Docker's default shared memory is tiny.line 26
  6. Downloaded weights live in a volume, so a restart does not download them again.line 28
  7. vLLM's /health needs no key. The image has Python, so Python does the request.line 30
  8. Up to five minutes to download and load before failures count. The app waits for this check.line 33
  9. Gives the container every NVIDIA GPU on the machine. vLLM does not start without one.line 35
Run
curl -s -w "\n" localhost:8000/ready
curl -sN -X POST localhost:8000/chat -H "Content-Type: application/json" -d @hi.json
You should seeyour text will differ: the model writes it
{"status":"ready"}
data: {"type": "token", "text": "Hello"}

data: {"type": "token", "text": "!"}

...

data: {"type": "done"}
Why this way? Because every setting came from the environment from step 2 on, moving between a laptop model, your own GPU server and a hosted API is a deployment decision, not a code change. You can even run them side by side and route some traffic to each.
Stuck on this step?
/ready says model Qwen/Qwen2.5-1.5B-Instruct not found
LLM_MODEL must 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_KEY does 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. -f picks the file; without it compose uses compose.yaml.
10

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_MODEL and the limits. LLM_API_KEY as 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: no header 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_IPS to the balancer's addresses (* only if nothing else can reach the container). uvicorn then reads the client's address from the X-Forwarded-For header, 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.

Run
docker login registry.example.com
docker buildx build --platform linux/amd64 -t registry.example.com/your-team/chat-service:0.1.0 --push .
You should seeyour text will differ: the model writes it
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
...
Why this way? Twelve-factor settings, a small non-root image, health checks, graceful shutdown and limits are not platform features: they live in your app and image. Get them right once and the app runs the same on any platform, which also keeps you free to change platforms later.
Stuck on this step?
exec format error when the platform starts the container
The image was built for the wrong CPU, usually arm64 from 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 /ready restarts 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.

Test
uv run pytest -q && curl -s -w "\n" localhost:8000/ready
You should see
..........                                                               [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. .dockerignore keeps .env out of the image, the platform injects the key at runtime, and repr=False keeps 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.

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

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

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

Download Python project (.zip)