Lesson 4: Build a Production Pipeline

Create an automated CI/CD pipeline that packages, tests, and deploys an active ML classifier.

By • Last updated • 120 min

In this final MLOps project workshop, you will synthesize everything you've learned. You will construct a complete, production-grade, containerized computer vision inference server capable of processing image payloads, performing tensor normalization, tracking sub-millisecond latency metrics, and running in an optimized Docker sandbox!

Project Architecture Overview

Your application will ingest image payloads as Base64 encoded strings, preprocess them to normalized tensor dimensions, execute mock classification inferences, and respond with filtered predictions and performance telemetry:

Inference Server Data Flow:
1. Client --[POST json with base64 string]--> /predict
2. FastAPI/Pydantic parses and validates payload formats
3. Base64 Decoder decodes raw string bytes to image array
4. Preprocessor normalizes channels: z = (x/255.0 - mean) / std
5. Model runs forward pass & measures execution time (latency)
6. Server --[Response json with classes & latency]--> Client

Image Preprocessing Mathematics

For standard deep learning classification models (like ResNet or MobileNet), inputs must be scaled and normalized to match the training distribution. Given an RGB pixel value $x \in [0, 255]$, the normalized pixel value $z$ is formulated as:

z = ((x / 255.0) - mean) / std

Where we utilize the ImageNet distribution standards:

  • mean = [0.485, 0.456, 0.406] (Red, Green, Blue channels)
  • std = [0.229, 0.224, 0.225]

Production Template: Base64 Decodes

APIs typically transmit binary media (like images) using Base64 encoding inside JSON payloads. In Python, you can decode and transform these payloads cleanly:

import base64
from io import BytesIO
from PIL import Image

def decode_image(base64_string: str) -> Image.Image:
    # Decode string, parsing raw bytes buffer
    image_bytes = base64.b64decode(base64_string)
    image = Image.open(BytesIO(image_bytes))
    return image.convert("RGB").resize((224, 224))

Project Goal and Approach

The point of this project is not the model, which is deliberately a mock, but everything around it: a validated API contract, deterministic preprocessing, a model loaded once at startup, measured latency and a reproducible container. Those are the parts that break in production. Build it in this order so each step can be tested before the next:

  1. Write the preprocessing function and test it on a generated image, with no web framework involved.
  2. Define the request and response schemas and check that bad input is rejected.
  3. Wire the endpoint with the mock model and timing.
  4. Call it from a test client, then run it under a real server.
  5. Containerize it and run the same requests against the container.

Preprocessing with NumPy

The normalization formula broadcasts naturally: the image array has shape (224, 224, 3) and the mean and std have shape (3,), so NumPy applies them per color channel. Most PyTorch vision models then expect channels first and a batch dimension:

import numpy as np

MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)

def preprocess(image) -> np.ndarray:
    arr = np.asarray(image, dtype=np.float32) / 255.0   # (224, 224, 3), values in [0, 1]
    arr = (arr - MEAN) / STD                             # per-channel normalization
    return arr.transpose(2, 0, 1)[None, ...]             # (1, 3, 224, 224)

A Minimal Service Skeleton

This sketch shows how the pieces fit. Fill in the details yourself for the tasks below; it uses the standard FastAPIlifespan pattern so the model is created once at startup instead of on every request:

import time
from contextlib import asynccontextmanager

import numpy as np
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.classes = ["Mammal", "Bird", "Reptile", "Amphibian"]   # "load the model" once
    yield

app = FastAPI(lifespan=lifespan)

class PayloadRequest(BaseModel):
    image_base64: str
    confidence_threshold: float = Field(default=0.5, ge=0.0, le=1.0)

@app.post("/predict")
def predict(req: PayloadRequest):
    start = time.perf_counter()
    try:
        tensor = preprocess(decode_image(req.image_base64))
    except Exception:
        raise HTTPException(status_code=422, detail="image_base64 is not a valid image")
    rng = np.random.default_rng(int(abs(float(tensor.sum())) * 1000) % (2**32))
    logits = rng.normal(size=len(app.state.classes))
    probs = np.exp(logits) / np.exp(logits).sum()           # softmax: sums to 1
    predictions = [
        {"label": c, "confidence": float(p)}
        for c, p in zip(app.state.classes, probs)
        if p >= req.confidence_threshold
    ]
    return {"predictions": predictions,
            "latency_ms": (time.perf_counter() - start) * 1000}

Seeding the random generator from the input makes the mock deterministic: the same image always gives the same output, which makes tests possible. The endpoint is a plain def rather than async def because decoding and NumPy work is CPU-bound; FastAPI runs plain functions in a thread pool so they do not block the event loop.

Containerizing Well

Docker caches each instruction as a layer and reuses it until something above it changes. Copy the dependency list and install packages before copying your source code, so editing main.py does not reinstall everything:

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Binding to 0.0.0.0 matters: a server listening on 127.0.0.1 inside a container is unreachable from outside it. Pin dependency versions in requirements.txt so a rebuild next month produces the same image, and add a .dockerignore to keep virtual environments and caches out of the build context.

How to Evaluate Your Service

  • Correctness: unit-test preprocess on a solid-color image and check the output shape and that values are finite.
  • Contract: send a malformed base64 string and a threshold of 1.5. You should get a 4xx error, not a 500.
  • Determinism: the same image twice should return identical predictions.
  • Latency: send 100 requests and look at the median and the 95th percentile, not just the mean. The first request is often slower because of warm-up.
  • Container parity: the same requests should behave identically against docker run -p 8000:8000 and against the local server.

Common Pitfalls

  • Loading the model inside the endpoint, which repeats expensive work on every request.
  • Forgetting .convert("RGB"). PNGs with transparency or grayscale images have a different channel count and break the normalization.
  • Resizing differently from training. A mismatch between training and serving preprocessing silently degrades accuracy without any error.
  • Unbounded payloads. Base64 inflates size by about a third. Enforce a maximum request size so one client cannot exhaust memory.
  • Running as root and unpinned dependencies in the image; add a non-root user for anything that will face the internet.

Extension Ideas

  • Replace the mock with a real small model such as a pretrained MobileNet, keeping the API unchanged.
  • Add a /health endpoint and a Docker HEALTHCHECK.
  • Expose request counts and latency histograms in Prometheus format.
  • Accept multipart file uploads instead of base64, and compare the payload sizes.
  • Add a GitHub Actions workflow that runs the tests and builds the image on each push.

Project Tasks: Build a Production Pipeline

Implement the following end-to-end components in the workspace to construct your production classifier pipeline:

  • [ ]Task 1: Define a decode_and_preprocess(base64_str: str) function. It must decode base64 strings into a resized $224 \times 224$ RGB image and normalize pixel coordinates based on the standard ImageNet formula.
  • [ ]Task 2: Define a Pydantic schema PayloadRequest that requires image_base64 (string) and a confidence_threshold (float, default=0.5).
  • [ ]Task 3: Define a Pydantic schema PredictionItem containing label and confidence, and a ClassificationResponse containing prediction arrays and latency_ms.
  • [ ]Task 4: Initialize a FastAPI application with a lifespan manager caching mock model classes: ["Mammal", "Bird", "Reptile", "Amphibian"].
  • [ ]Task 5: Implement a POST endpoint /predict. Use time.perf_counter() to track execution latency around the decoding, preprocessing, and prediction segments.
  • [ ]Task 6: Inside /predict, simulate classifier confidence calculations. Filter any outputs scoring below the request's confidence_threshold, and return a ClassificationResponse.
  • [ ]Task 7: Create a complete accompanying production Dockerfile using the python:3.11-slim image base, optimized pip library caching layers, and launching the application.
Graduation Challenge: Once all tasks are complete, you will have built a fully containerized ML inference service ready for massive web scale. Run docker build locally to verify your pipeline!

Related articles

main.py
Run your code to see output here.