Sub topic 12
Deploying and Serving Models
Assume you know how to train and evaluate a supervised model, use Git, and deploy a basic web service. This chapter focuses on turning a trained model into a reliable production component.
From model artifact to prediction
A model artifact is a saved model and its required metadata. It may include learned weights, the feature order, preprocessing rules, and the model version. Serving is the process of loading this artifact and using it to produce predictions for new data.
A production service must use the same feature definitions and preprocessing steps as training. If training converted income from dollars to thousands but serving does not, the model receives values on the wrong scale. This training-serving skew can make a technically healthy service produce poor predictions.
An online endpoint commonly accepts structured input and returns a prediction:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class PredictionRequest(BaseModel):
features: list[float]
@app.post("/predict")
def predict(request: PredictionRequest) -> dict[str, float]:
# Replace this calculation with a loaded, versioned model artifact.
score = sum(request.features) / len(request.features)
return {"score": score}The endpoint should also validate input, expose a health check, record request metadata, and avoid logging sensitive feature values.
Choosing a deployment pattern
The right pattern depends on latency, traffic, cost, and how quickly predictions must reflect new data.
| Pattern | Typical use | Main trade-off |
|---|---|---|
| Batch scoring | Daily risk scores or recommendations | Low cost, but predictions are not immediate |
| Online serving | Fraud checks or search ranking | Low latency, but requires always-on operations |
| Streaming scoring | Events that need near-real-time decisions | Fresh results, but more complex infrastructure |
| Staged rollout | Releasing a new model safely | Safer changes, but requires traffic control and comparison |
Batch scoring runs a model on a collection of records on a schedule. Online serving keeps a process ready to answer one request at a time. Streaming scoring consumes events from a queue and emits predictions as events arrive.
Releasing a new model safely
A staged rollout separates deployment from full release. First, deploy the candidate model without sending it user traffic. This is a shadow deployment. The candidate receives copied requests, but its predictions do not affect users. Compare latency, errors, and predictions with the production model.
Next, send a small percentage of real traffic to the candidate. This is a canary release. Increase traffic only when its quality and operational metrics meet the release criteria. A blue-green deployment instead keeps two complete environments and switches traffic from the old environment to the new one.
Common errors
- Shipping a model without its preprocessing code or feature schema.
- Comparing a candidate with production on different time periods.
- Releasing globally before testing a small traffic slice.
- Treating rollback as only a code operation when the model, features, and configuration also changed.
- Measuring only average latency. Tail latency, such as the 99th percentile, often determines user experience.
Exercise
A fraud model must respond within 100 milliseconds, but a nightly customer-ranking model does not need immediate results. Which deployment patterns fit these models?
Show answer
Use online serving for fraud detection because it needs low-latency responses. Use batch scoring for customer ranking because scheduled predictions are sufficient and usually cheaper.