Deploying Models and AI Apps

Updated · 9 min read
hardPython 3.13aideploymentfastapiservingbatchingcaching

Deploying a model means making it available to real users through a reliable service, usually a web API that other programs call. A good deployment loads the model once, checks every input, reports its own health and version, answers quickly under load, and can be updated or rolled back without downtime. The model is often the easy part; the service around it is what makes it dependable.

Ways to Serve a Model

OptionDescription
Your own API serviceIt is used to wrap the model in a web service such as FastAPI, running on a server or in containers
Serverless functionsIt is used for light, bursty traffic; the cloud runs your code only when called
Model-serving toolsDedicated servers such as vLLM, TGI or Triton for fast LLM and GPU serving
Hosted model APIsIt is used to call a provider's model, so there is no model to run yourself; see "Hosted, Open and Local Models"
On the deviceIt is used to run small models in a phone, browser or laptop app, for privacy and offline use

Example: Campus Helper as a Web Service

The programs in this chapter need pip install fastapi httpx sentence-transformers scikit-learn torch transformers. Several use faq.json from "Semantic Search" and eval_set.json from "Building an Evaluation Set". Download and loading messages are left out of the output shown.

This program serves the semantic-search Campus Helper from "Semantic Search" with FastAPI, the framework from "Frontend, Backend and the Model". FastAPI's test client sends requests to it without starting a server.

Load once, validate, report health, batch and cache
Python
import json
 
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
from sentence_transformers import SentenceTransformer
 
VERSION = "campus-helper 1.0 (all-MiniLM-L6-v2, threshold 0.35)"
DECLINE = "Sorry, I can only answer questions about this school. Please contact the school office."
 
# Load the model and the documents ONCE, when the service starts, not on every request
texts = [item["text"] for item in json.load(open("faq.json"))]
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode(texts, normalize_embeddings=True)
app = FastAPI(title="Campus Helper")
 
class Question(BaseModel):
    question: str = Field(min_length=3, max_length=300)     # reject empty or huge inputs
 
@app.get("/health")
def health():
    return {"status": "ok", "version": VERSION, "documents": len(texts)}
 
@app.post("/ask")
def ask(q: Question):
    scores = vectors @ model.encode(q.question, normalize_embeddings=True)
    best = int(scores.argmax())
    if scores[best] < 0.35:
        return {"answer": DECLINE, "source": None, "score": round(float(scores[best]), 3)}
    return {"answer": texts[best], "source": f"FAQ #{best + 1}", "score": round(float(scores[best]), 3)}
 
client = TestClient(app)                                     # sends requests without starting a server
print(client.get("/health").json())
for question in ["How much is the library fee?", "Who won the game last night?"]:
    r = client.post("/ask", json={"question": question})
    print(r.status_code, r.json())
bad = client.post("/ask", json={"question": ""})
print(bad.status_code, bad.json()["detail"][0]["msg"])
Output
{'status': 'ok', 'version': 'campus-helper 1.0 (all-MiniLM-L6-v2, threshold 0.35)', 'documents': 50}
200 {'answer': 'The library fee is $15 a year and covers book loans and printing.', 'source': 'FAQ #3', 'score': 0.801}
200 {'answer': 'Sorry, I can only answer questions about this school. Please contact the school office.', 'source': None, 'score': 0.152}
422 String should have at least 3 characters

Explanation:

  • The model and documents load once, when the service starts. Loading a model on every request would make each answer take seconds instead of milliseconds.
  • /health reports that the service is up and which version is running, so monitoring tools and the team always know what is in production.
  • /ask answers with the closest FAQ entry, its source and the similarity score, or declines below 0.35. Returning the score helps monitoring spot weak answers later.
  • Question is a Pydantic model that validates input: an empty question is rejected with status 422 before it reaches the model. Limits like max_length=300 also block huge inputs that would waste money or memory.
  • To run it for real, save it as app.py without the test-client lines and start it with uvicorn app:app.

Example: Batching and Caching

Two of the simplest ways to serve more requests on the same hardware are batching (processing many inputs in one call) and caching (remembering answers to repeated inputs). This program measures both, using the 50 questions in eval_set.json.

Python
import json
import time
from functools import lru_cache
 
from sentence_transformers import SentenceTransformer
 
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
questions = [case["question"] for case in json.load(open("eval_set.json"))]   # from "Building an Evaluation Set"
model.encode(questions[:2])                                  # warm up once, as a running service would be
 
start = time.perf_counter()
for q in questions:
    model.encode(q)                                          # one request at a time
one_by_one = time.perf_counter() - start
 
start = time.perf_counter()
model.encode(questions, batch_size=50)                       # all 50 in one batch
batched = time.perf_counter() - start
print(f"50 questions one by one: {one_by_one * 1000:6.1f} ms ({one_by_one / 50 * 1000:.2f} ms each)")
print(f"50 questions in a batch: {batched * 1000:6.1f} ms ({batched / 50 * 1000:.2f} ms each)")
print(f"Batching was {one_by_one / batched:.1f} times faster")
 
@lru_cache(maxsize=1000)                                     # remember answers to repeated questions
def embed(question):
    return model.encode(question)
 
popular = ["What time is lunch?"] * 30 + questions[:20]       # many parents ask the same thing
start = time.perf_counter()
for q in popular:
    embed(q)
cached = time.perf_counter() - start
info = embed.cache_info()
print(f"\n50 requests with a cache: {cached * 1000:.1f} ms, {info.hits} served from the cache, {info.misses} computed")
Output
50 questions one by one:  174.6 ms (3.49 ms each)
50 questions in a batch:   64.1 ms (1.28 ms each)
Batching was 2.7 times faster
 
50 requests with a cache: 62.3 ms, 29 served from the cache, 21 computed

Explanation:

  • One by one, each question took about 3.49 ms; in one batch of 50, about 1.28 ms each, 2.7 times faster. A model processes a batch with the same matrix operations it uses for one input, so the hardware stays busier. LLM servers do this constantly, combining requests from many users.
  • lru_cache remembers results for up to 1,000 different questions. With 30 copies of "What time is lunch?" among 50 requests, 29 were served from the cache, and only 21 needed the model.
  • These timings are one run on this laptop; they change between runs and machines, but the pattern holds.

Releasing Safely

PracticeWhat it does
ContainersPackage the code, model and libraries together, so they run the same everywhere
StagingTest a new version in a copy of production before real users see it
Canary or staged rolloutSend a few percent of traffic to the new version first; see "Launching AI Features: Pilots and Experiments"
RollbackKeep the previous version ready, and switch back in minutes if quality drops
Rate limits and timeoutsProtect the service and your budget from floods of requests
Secrets managementKeep API keys in a secrets store, never in code; see "Tokens, Cost and Rate Limits"

Common Mistakes

Loading the model inside the request handler. Every request pays the loading time.

No input limits. Huge or malformed inputs waste money and can crash the service.

Deploying without a version label. When users report a problem, you can't tell which version answered.

Testing only one request at a time. Real traffic arrives in bursts; test under realistic load.

Interview Corner

How would you deploy a model as an API?

Wrap it in a web service that loads the model once at startup, validates inputs, exposes prediction and health endpoints with the version, and runs in containers behind a load balancer. Release it with a staged rollout and keep the previous version ready for rollback.

How do batching and caching improve serving?

Batching processes several inputs in one model call, using the hardware more efficiently; caching returns stored results for repeated inputs without calling the model. Both raise throughput and cut cost, as long as cached answers are safe to share.

Practice

Exercise: a version endpoint and a limit. Add max_length=100 to Question, and send a 150-character question. What status and message come back? Then add a /version endpoint that returns only the version string.

Check your understanding:

  1. Why should the model load at startup instead of inside /ask?
  2. What did status 422 mean for the empty question?
  3. When would caching answers be unsafe?

Quick check: deploying models

4 questions
1What did the service return for an empty question?
2How much faster was batching here?
3Why does /health report the version?
4What is a canary rollout?

Key Takeaways

Quick reference

NeedCode or practice
An endpoint@app.post("/ask")
Validate inputclass Question(BaseModel): question: str = Field(min_length=3, max_length=300)
Test without a serverTestClient(app).post("/ask", json={...})
Run for realuvicorn app:app
Batchmodel.encode(list_of_texts, batch_size=50)
Cache@lru_cache(maxsize=1000)

Was this tutorial helpful?

Lesson 159 of 186