Data Science Advanced

Serving Machine Learning Models in Django: Versioning, Celery Batch Scoring, and Monitoring

Serve a scikit-learn pipeline from Django with versioned skops artifacts, a database registry, a validated JSON endpoint, idempotent Celery batch scoring, and drift, latency and accuracy monitoring.

KC Ramo DjangoZen Team Dec 05, 2026 18 min read 4 views

A trained model becomes a production dependency the moment a view calls it, and it needs the same discipline as any other dependency: a pinned version, a checksum, a controlled rollout and tests. This tutorial builds that around a scikit-learn pipeline in Django. It covers a versioned artifact with metadata, a registry that loads each model once per process, a validated JSON endpoint, an audit trail of predictions, idempotent batch scoring with Celery, and the monitoring that tells you when the model has stopped describing reality.

What we build

The example predicts customer churn from four features: a training command that registers an inactive ModelVersion, a registry that loads the active version once per process, a POST /api/churn/predict/ endpoint, Celery batch tasks, and reports computed from stored predictions.

Versions used: Python 3.13, Django 5.2.20 (the 5.2 LTS line), scikit-learn 1.9.1, skops 0.16.0, Celery 5.7.0 with the Redis extra, pandas 3.1.2, NumPy 2.5.5 and SciPy 1.18.1. Everything shown was run against SQLite in a project called myproject with an app called scoring. Where PostgreSQL behaves differently, the text says so.

python -m venv .venv
.venv/bin/pip install "Django>=5.2,<6.0" "celery[redis]>=5.7,<6.0" "scikit-learn>=1.9,<2.0" \
    "skops>=0.16,<1.0" "scipy>=1.18,<2.0" "pandas>=3.1,<4.0"

Training and the artifact

The artifact is the fitted pipeline, preprocessing included. If scaling or one-hot encoding lives in the view instead, training and serving will drift apart the first time someone edits one side. Next to the artifact we write metadata: version, training time, the exact feature list, the scikit-learn version, evaluation metrics, a SHA-256 of the file, and a reference sample of inputs and scores for drift detection later.

# scoring/training.py (imports omitted; make_dataset() returns a DataFrame
# with the four features and a boolean "churned" column)
NUMERIC = ["tenure_months", "monthly_charges", "support_tickets"]
CATEGORICAL = ["contract"]
FEATURES = NUMERIC + CATEGORICAL
CONTRACTS = ["monthly", "yearly", "two_year"]

def build_pipeline():
    pre = ColumnTransformer([
        ("num", StandardScaler(), NUMERIC),
        ("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL),
    ])
    return Pipeline([("pre", pre), ("clf", LogisticRegression(max_iter=1000))])


def sha256_of(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 16), b""):
            h.update(block)
    return h.hexdigest()


def train_and_save(out_dir, version, df=None):
    df = make_dataset() if df is None else df
    X, y = df[FEATURES], df["churned"]
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=0, stratify=y
    )
    pipe = build_pipeline().fit(X_train, y_train)
    proba = pipe.predict_proba(X_test)[:, 1]

    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    artifact = out_dir / f"churn-{version}.skops"
    sio.dump(pipe, artifact)

    meta = {
        "name": "churn",
        "version": version,
        "trained_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "features": FEATURES,
        "sklearn_version": sklearn.__version__,
        "metrics": {
            "roc_auc": round(roc_auc_score(y_test, proba), 4),
            "accuracy": round(accuracy_score(y_test, proba >= 0.5), 4),
            "n_train": len(X_train),
        },
        # Reference sample of training scores and inputs for drift checks.
        "reference": {
            "score": np.round(pipe.predict_proba(X_train)[:, 1], 4).tolist()[:2000],
            "monthly_charges": X_train["monthly_charges"].tolist()[:2000],
        },
        "artifact": artifact.name,
        "sha256": sha256_of(artifact),
    }
    meta_path = artifact.with_suffix(".json")
    meta_path.write_text(json.dumps(meta, indent=2))
    return artifact, meta

A few details matter more than they look:

  • The feature list is part of the contract. At serving time we build the DataFrame with columns=FEATURES from the metadata, so a reordered dict or an extra key cannot silently shift values into the wrong column.
  • The scikit-learn version is recorded because estimators are only guaranteed to load in the version that saved them. Pin the same version in the serving environment and retrain when you upgrade.
  • The reference sample is capped at 2,000 values per column: enough for PSI and KS tests, small enough to store in the database.
  • OneHotEncoder(handle_unknown="ignore") lets a category that never appeared in training score as "none of the known categories" instead of raising. Input validation still rejects values outside the allowed list, so this is a second line of defence.

The training command

from django.conf import settings
from django.core.management.base import BaseCommand

from scoring.models import ModelVersion
from scoring.training import train_and_save


class Command(BaseCommand):
    help = "Train the churn model and register it (inactive)."

    def add_arguments(self, parser):
        parser.add_argument("version")

    def handle(self, *args, version, **options):
        artifact, meta = train_and_save(settings.ML_MODEL_DIR, version)
        mv = ModelVersion.objects.create(
            name=meta["name"],
            version=version,
            artifact=artifact.name,
            sha256=meta["sha256"],
            features=meta["features"],
            metrics=meta["metrics"],
            reference=meta["reference"],
        )
        self.stdout.write(f"registered {mv} {meta['metrics']}")
        self.stdout.write(f"sha256 {meta['sha256']}")
$ python manage.py train_model 2026.12.1
registered churn:2026.12.1 {'roc_auc': 0.777, 'accuracy': 0.698, 'n_train': 4000}
sha256 aece4b5cf5df5bb06575bec102b456901e5f7f50fc9ad7c5ae78393b91d26349

The version is registered inactive; activation is a separate step after comparing metrics.

A model registry in the database

The database decides which version is live, so switching needs no redeploy or restart.

import uuid

from django.db import models, transaction
from django.db.models import Q


class ModelVersion(models.Model):
    name = models.CharField(max_length=50)
    version = models.CharField(max_length=30)
    artifact = models.CharField(max_length=200)  # file name inside ML_MODEL_DIR
    sha256 = models.CharField(max_length=64)
    features = models.JSONField()
    metrics = models.JSONField(default=dict)
    reference = models.JSONField(default=dict)
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    activated_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=["name", "version"], name="uniq_model_version"),
            models.UniqueConstraint(
                fields=["name"], condition=Q(is_active=True), name="one_active_per_model"
            ),
        ]

    def __str__(self):
        return f"{self.name}:{self.version}"

    def activate(self):
        from django.utils import timezone

        with transaction.atomic():
            # Lock every version of this model so two concurrent switches serialize.
            list(ModelVersion.objects.select_for_update().filter(name=self.name))
            ModelVersion.objects.filter(name=self.name, is_active=True).update(is_active=False)
            ModelVersion.objects.filter(pk=self.pk).update(
                is_active=True, activated_at=timezone.now()
            )
        self.refresh_from_db()


class Prediction(models.Model):
    request_id = models.UUIDField(default=uuid.uuid4, editable=False)
    model_version = models.ForeignKey(ModelVersion, on_delete=models.PROTECT)
    # Business key for batch scoring; empty for online requests.
    customer_id = models.CharField(max_length=50, blank=True)
    batch = models.CharField(max_length=50, blank=True)
    features = models.JSONField()
    score = models.FloatField()
    latency_ms = models.FloatField(null=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    # Filled in later when the real outcome is known.
    actual = models.BooleanField(null=True)
    actual_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["batch", "customer_id", "model_version"],
                condition=~Q(batch=""),
                name="uniq_batch_prediction",
            ),
        ]

The conditional UniqueConstraint becomes a partial unique index: at most one active row per model name. The database enforces it, so a bug or a race cannot produce two active versions. PostgreSQL and SQLite support it; MySQL and MariaDB do not support conditional constraints, and Django skips them there with a system check warning, so on those databases you need a different design.

activate() deactivates first and activates second inside one transaction. The order matters: the constraint is checked per statement, and activating first would violate it. On PostgreSQL, select_for_update() makes two concurrent activations wait for each other. SQLite ignores select_for_update(), but it serialises writers anyway.

Rollback is the same operation on the previous version. on_delete=models.PROTECT keeps versions that predictions refer to.

Loading once per process

Deserialising a pipeline per request is the most common performance mistake in model serving. The registry caches loaded models in a module-level dict keyed by the ModelVersion primary key:

import threading
from pathlib import Path

import pandas as pd
import skops.io as sio
from django.conf import settings

from .models import ModelVersion
from .training import sha256_of

# Types the skops loader may construct beyond its built-in safe list.
# Review get_untrusted_types() output before adding anything here.
TRUSTED_TYPES = []


class ArtifactError(RuntimeError):
    pass


class LoadedModel:
    def __init__(self, version: ModelVersion, pipeline):
        self.version = version
        self.pipeline = pipeline
        self.features = list(version.features)

    def predict_proba(self, rows: list[dict]) -> list[float]:
        frame = pd.DataFrame(rows, columns=self.features)
        return self.pipeline.predict_proba(frame)[:, 1].tolist()


_cache: dict[int, LoadedModel] = {}
_lock = threading.Lock()


def load_artifact(mv: ModelVersion):
    path = Path(settings.ML_MODEL_DIR) / mv.artifact
    if sha256_of(path) != mv.sha256:
        raise ArtifactError(f"checksum mismatch for {mv}")
    unknown = sio.get_untrusted_types(file=path)
    not_allowed = [t for t in unknown if t not in TRUSTED_TYPES]
    if not_allowed:
        raise ArtifactError(f"untrusted types in {mv}: {not_allowed}")
    return sio.load(path, trusted=TRUSTED_TYPES)


def load_version(mv: ModelVersion) -> LoadedModel:
    loaded = _cache.get(mv.pk)
    if loaded is not None:
        return loaded
    with _lock:
        loaded = _cache.get(mv.pk)  # another thread may have won the race
        if loaded is None:
            loaded = LoadedModel(mv, load_artifact(mv))
            _cache[mv.pk] = loaded
    return loaded


def get_model(name: str = "churn") -> LoadedModel:
    # One indexed query per call; the artifact itself is loaded once per process.
    return load_version(ModelVersion.objects.get(name=name, is_active=True))


def clear_cache():
    with _lock:
        _cache.clear()

How this behaves under a real server:

  • Processes. Each gunicorn or uWSGI worker process has its own cache and loads the model on its first request. Memory use is roughly model size times worker count; plan for it.
  • Threads. With threaded workers, two requests may miss the cache at the same moment. The lock with a second check inside it (double-checked locking) guarantees the artifact is loaded once. The fast path does not take the lock.
  • Sharing the estimator. predict_proba on a fitted scikit-learn pipeline does not modify the estimator, so one instance can serve concurrent threads. Never call fit or set_params on the shared object.
  • Switching. get_model() asks the database which version is active on every call. That is one indexed query. After an activation, every process picks up the new version on its next request without a restart. Old entries stay in the dict; with a few versions per deploy that is fine, otherwise evict all keys except the active one after a switch.

Security of model files

pickle.load and joblib.load execute code while loading: loading an untrusted pickle is remote code execution with your application's privileges. Therefore:

  1. Never load model files that a user or an external party can supply.
  2. Prefer the skops format. skops.io.load only constructs types on an allow-list and refuses anything else.
  3. Verify the checksum recorded at registration before loading, so a file that was replaced on disk is rejected.
  4. Store artifacts outside MEDIA_ROOT and STATIC_ROOT, read-only for the application user.

skops reports types that are not on its default allow-list. Our pipeline contains only standard scikit-learn and NumPy types, so the list is empty and TRUSTED_TYPES stays empty. A pipeline with a custom function shows what happens otherwise:

>>> sio.get_untrusted_types(file="x.skops")
['myfeatures.clip_tickets']
>>> sio.load("x.skops")
UntrustedTypesFoundException: Untrusted types found in the file: ['myfeatures.clip_tickets'].

Review the code behind each reported name before adding it to TRUSTED_TYPES. Do not pass trusted=get_untrusted_types(...) automatically; that trusts whatever the file asks for and defeats the purpose.

The prediction endpoint

A Django form gives typed, bounded validation without extra dependencies:

from django import forms

from .training import CONTRACTS


class ChurnInputForm(forms.Form):
    tenure_months = forms.IntegerField(min_value=0, max_value=600)
    monthly_charges = forms.FloatField(min_value=0, max_value=10_000)
    support_tickets = forms.IntegerField(min_value=0, max_value=1_000)
    contract = forms.ChoiceField(choices=[(c, c) for c in CONTRACTS])
import hmac
import json
import time

from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .forms import ChurnInputForm
from .models import ModelVersion, Prediction
from .registry import get_model

MAX_BODY = 10_000  # bytes; one prediction never needs more


def _authorized(request):
    header = request.headers.get("Authorization", "")
    expected = f"Bearer {settings.SCORING_API_TOKEN}"
    return hmac.compare_digest(header.encode(), expected.encode())


@csrf_exempt  # token-authenticated machine-to-machine endpoint, no cookies
@require_POST
def predict(request):
    if not _authorized(request):
        return JsonResponse({"error": "unauthorized"}, status=401)
    if request.content_type != "application/json":
        return JsonResponse({"error": "expected application/json"}, status=415)
    if len(request.body) > MAX_BODY:
        return JsonResponse({"error": "body too large"}, status=413)
    try:
        payload = json.loads(request.body)
    except json.JSONDecodeError:
        return JsonResponse({"error": "invalid JSON"}, status=400)
    if not isinstance(payload, dict):
        return JsonResponse({"error": "expected a JSON object"}, status=400)

    unknown = set(payload) - set(ChurnInputForm.base_fields)
    if unknown:
        return JsonResponse({"error": f"unknown fields: {sorted(unknown)}"}, status=400)
    form = ChurnInputForm(payload)
    if not form.is_valid():
        return JsonResponse({"errors": form.errors.get_json_data()}, status=400)

    try:
        model = get_model("churn")
    except ModelVersion.DoesNotExist:
        return JsonResponse({"error": "no active model"}, status=503)

    started = time.perf_counter()
    score = model.predict_proba([form.cleaned_data])[0]
    latency_ms = (time.perf_counter() - started) * 1000

    pred = Prediction.objects.create(
        model_version=model.version,
        features=form.cleaned_data,
        score=score,
        latency_ms=latency_ms,
    )
    return JsonResponse({
        "request_id": str(pred.request_id),
        "model_version": model.version.version,
        "churn_probability": round(score, 4),
    })

Other services call this endpoint without cookies, so it uses a bearer token compared in constant time and is exempt from CSRF; if browsers call it with a session, drop csrf_exempt. Unknown fields are rejected, which catches renamed fields early. Latency covers the model call only.

POST /api/churn/predict/
{"tenure_months": 3, "monthly_charges": 89.5, "support_tickets": 4, "contract": "monthly"}
200 {"request_id": "61720534-f848-4199-b900-c3e565caf192", "model_version": "2026.12.1",
     "churn_probability": 0.937}

{"tenure_months": -1, "monthly_charges": "abc", "contract": "weekly"}
400 {"errors": {"tenure_months": [{"message": "Ensure this value is greater than or equal to 0.",
     "code": "min_value"}], "monthly_charges": [{"message": "Enter a number.", "code": "invalid"}],
     "support_tickets": [{"message": "This field is required.", "code": "required"}],
     "contract": [{"message": "Select a valid choice. weekly is not one of the available choices.",
     "code": "invalid_choice"}]}}

With Django REST framework (3.18.3 at the time of writing), the form maps one-to-one onto a serializers.Serializer with the same min_value, max_value and ChoiceField bounds, and the token check moves into an authentication class.

Storing predictions for auditing

Every prediction row records the validated input, the score, the model version and the request id returned to the caller. That answers the questions after an incident (which version, which inputs, how slow) and feeds every monitoring query below.

Two practical points. First, inputs may be personal data. Store only the features the model uses, define a retention period, and delete or aggregate old rows with a scheduled task. Second, at high request rates, consider writing rows in bulk from a queue; keep returning the request id either way.

Batch scoring with Celery

Nightly scoring of the whole customer base should not go through HTTP. A coordinating task splits the ids into chunks and fans out one task per chunk:

import logging

from celery import group, shared_task
from django.db import transaction

from .models import ModelVersion, Prediction
from .registry import load_version

log = logging.getLogger(__name__)
CHUNK_SIZE = 500


def fetch_customers(ids):
    """Stand-in for your feature query: returns one dict per customer."""
    from .training import make_dataset

    df = make_dataset(n=len(ids), seed=int(ids[0]))
    df["customer_id"] = [str(i) for i in ids]
    return df.drop(columns="churned").to_dict("records")


@shared_task(
    bind=True,
    autoretry_for=(ConnectionError, TimeoutError),
    retry_backoff=True,
    retry_backoff_max=600,
    retry_jitter=True,
    max_retries=5,
)
def score_chunk(self, batch, customer_ids, model_version_id):
    mv = ModelVersion.objects.get(pk=model_version_id)
    done = set(
        Prediction.objects.filter(
            batch=batch, model_version=mv, customer_id__in=customer_ids
        ).values_list("customer_id", flat=True)
    )
    todo = [c for c in customer_ids if c not in done]
    if not todo:
        return 0

    model = load_version(mv)  # pinned: a switch mid-batch does not mix versions
    rows = fetch_customers(todo)
    scores = model.predict_proba(rows)
    objs = [
        Prediction(
            model_version=mv,
            batch=batch,
            customer_id=row["customer_id"],
            features={k: row[k] for k in model.features},
            score=score,
        )
        for row, score in zip(rows, scores)
    ]
    with transaction.atomic():
        Prediction.objects.bulk_create(objs, ignore_conflicts=True)
    return len(objs)


@shared_task
def score_all(batch, customer_ids, model_name="churn"):
    mv = ModelVersion.objects.get(name=model_name, is_active=True)
    chunks = [
        customer_ids[i : i + CHUNK_SIZE] for i in range(0, len(customer_ids), CHUNK_SIZE)
    ]
    log.info("batch %s: %d customers in %d chunks", batch, len(customer_ids), len(chunks))
    return group(score_chunk.s(batch, chunk, mv.pk) for chunk in chunks).apply_async().id

The design decisions:

  • Chunking. 500 customers per task keeps tasks short and spreads the batch over workers. Pass ids, not feature rows, so messages stay small.
  • Pinned version. The coordinator resolves the active version once and passes its id to every chunk, so an activation halfway through does not mix versions.
  • Idempotency. A chunk can run twice: after a retry, a worker crash with acks_late, or a manual re-run. The task skips customers already scored in this batch, and the partial unique constraint on (batch, customer_id, model_version) plus ignore_conflicts=True covers the race where two copies run at the same time. Note that with ignore_conflicts, the returned objects do not get primary keys set.
  • Retries. autoretry_for retries only transient errors, with exponential backoff and jitter so retries do not arrive in waves. A bug such as a missing feature raises immediately instead of retrying five times.
  • Delivery. CELERY_TASK_ACKS_LATE = True acknowledges a message after the task finishes, so a killed worker's chunk is delivered again. CELERY_WORKER_PREFETCH_MULTIPLIER = 1 stops one worker from reserving many long chunks. Late acknowledgement is only safe because the task is idempotent.

In tests and experiments, call the task function directly, or set CELERY_TASK_ALWAYS_EAGER = True so delay() runs in-process. Running the batch twice for 1,200 customers:

>>> score_all.delay("2026-12-05", list(range(1, 1201)))
>>> Prediction.objects.filter(batch="2026-12-05").count()
1200
>>> score_chunk("2026-12-05", [str(i) for i in range(1, 501)], mv.pk)
0

Eager mode hides serialisation and broker problems, so run at least one end-to-end test against a real broker in CI.

Monitoring

A deployed model fails quietly: no exception, just worse decisions. Four signals catch most problems, and all of them can be computed from the Prediction table.

import numpy as np
from django.db.models import Avg, Count, FloatField, Q
from django.db.models.functions import Cast
from scipy import stats

from .models import ModelVersion, Prediction


def psi(reference, current, bins=10, eps=1e-6):
    """Population Stability Index with quantile bins taken from the reference."""
    reference = np.asarray(reference, dtype=float)
    current = np.asarray(current, dtype=float)
    edges = np.unique(np.quantile(reference, np.linspace(0, 1, bins + 1)))
    edges[0], edges[-1] = -np.inf, np.inf
    ref_pct = np.histogram(reference, edges)[0] / len(reference)
    cur_pct = np.histogram(current, edges)[0] / len(current)
    ref_pct = np.clip(ref_pct, eps, None)
    cur_pct = np.clip(cur_pct, eps, None)
    return float(np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct)))


def drift_report(mv: ModelVersion, since):
    preds = Prediction.objects.filter(model_version=mv, created_at__gte=since)
    current = {
        "score": list(preds.values_list("score", flat=True)),
        "monthly_charges": list(preds.values_list("features__monthly_charges", flat=True)),
    }
    report = {}
    for column, ref in mv.reference.items():
        cur = current[column]
        if len(cur) < 100:
            report[column] = {"status": "insufficient data", "n": len(cur)}
            continue
        ks = stats.ks_2samp(ref, cur)
        report[column] = {
            "n": len(cur),
            "psi": round(psi(ref, cur), 4),
            "ks_stat": round(float(ks.statistic), 4),
            "ks_pvalue": float(f"{ks.pvalue:.3g}"),
        }
    return report


def latency_percentiles(mv: ModelVersion, since):
    values = list(
        Prediction.objects.filter(model_version=mv, created_at__gte=since, latency_ms__isnull=False)
        .values_list("latency_ms", flat=True)
    )
    if not values:
        return {}
    p50, p95, p99 = np.percentile(values, [50, 95, 99])
    return {"n": len(values), "p50": round(float(p50), 2), "p95": round(float(p95), 2), "p99": round(float(p99), 2)}


def labelled_accuracy(mv: ModelVersion, threshold=0.5):
    qs = Prediction.objects.filter(model_version=mv, actual__isnull=False)
    return qs.aggregate(
        labelled=Count("id"),
        correct=Count(
            "id",
            filter=Q(score__gte=threshold, actual=True) | Q(score__lt=threshold, actual=False),
        ),
        mean_score=Avg("score"),
        base_rate=Avg(Cast("actual", FloatField())),
    )

Input drift: PSI and the KS test

The Population Stability Index bins the reference sample into deciles and compares the share of current values in each bin. Common rules of thumb: below 0.1 is stable, 0.1 to 0.25 deserves a look, above 0.25 is a significant shift. The two-sample Kolmogorov-Smirnov test compares the full distributions and returns a p-value. On the same data, shifting monthly_charges by 15 gives:

psi same    0.0052
psi shifted 0.5343
KstestResult(statistic=np.float64(0.3075), pvalue=np.float64(7.017206358218433e-84), ...)

And the report over the stored predictions from the batch and the online requests:

{
  "score": {"n": 1401, "psi": 0.0165, "ks_stat": 0.0258, "ks_pvalue": 0.63},
  "monthly_charges": {"n": 1401, "psi": 0.0221, "ks_stat": 0.0385, "ks_pvalue": 0.169}
}

Prefer PSI or the KS statistic for alerting, not the p-value. With tens of thousands of predictions, the KS test reports tiny, irrelevant differences as highly significant. Also note that values_list("features__monthly_charges") uses a JSON key lookup that works on SQLite and PostgreSQL. For features you monitor heavily, a real column with an index is faster.

Prediction distribution

The score entry is drift of the model's output. It catches changes a per-feature check misses, such as a correlated shift across several features, and a jump in the share of high scores is often the first symptom of an upstream data bug.

Latency

>>> latency_percentiles(mv, since)
{'n': 201, 'p50': 3.77, 'p95': 4.66, 'p99': 5.24}

Percentiles are computed in Python to stay database-neutral; on PostgreSQL, percentile_cont in a custom aggregate does it in SQL. Alert on p95 and p99, not the mean.

Labels that arrive later

Churn is only known weeks after the prediction. When it is, write it back to actual and actual_at on the stored predictions with bulk_update. Real accuracy then becomes a query:

>>> labelled_accuracy(mv)
{'labelled': 400, 'correct': 287, 'mean_score': 0.39413993936683483, 'base_rate': 0.37}

Compare mean_score with base_rate for calibration, and accuracy with the offline metric in the version's metadata. The Cast to a float in base_rate is needed on PostgreSQL, which has no AVG over booleans; SQLite stores booleans as integers and would work without it. Run the drift and accuracy reports from a Celery beat task once a day, store the results, and alert on thresholds rather than having someone read dashboards.

Testing with the test client

The tests train a small model into a temporary directory once per class, then exercise the endpoint, the registry and the batch task:

import shutil
import tempfile

import numpy as np
from django.db import IntegrityError
from django.test import TestCase, override_settings

from . import registry
from .models import ModelVersion, Prediction
from .monitoring import psi
from .tasks import score_chunk
from .training import make_dataset, train_and_save

MODEL_DIR = tempfile.mkdtemp()
AUTH = {"Authorization": "Bearer test-token"}
VALID = {"tenure_months": 3, "monthly_charges": 89.5, "support_tickets": 4, "contract": "monthly"}


def tearDownModule():
    shutil.rmtree(MODEL_DIR, ignore_errors=True)


@override_settings(ML_MODEL_DIR=MODEL_DIR, SCORING_API_TOKEN="test-token")
class ScoringTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        _, meta = train_and_save(MODEL_DIR, "t1", df=make_dataset(n=1000))
        cls.mv = ModelVersion.objects.create(
            name="churn", version="t1", artifact=meta["artifact"], sha256=meta["sha256"],
            features=meta["features"], metrics=meta["metrics"], reference=meta["reference"],
        )
        cls.mv.activate()

    def setUp(self):
        registry.clear_cache()

    def post(self, payload, headers=AUTH):
        return self.client.post(
            "/api/churn/predict/", payload, content_type="application/json", headers=headers
        )

    def test_prediction_is_returned_and_stored(self):
        response = self.post(VALID)
        self.assertEqual(response.status_code, 200)
        body = response.json()
        self.assertEqual(body["model_version"], "t1")
        self.assertTrue(0 <= body["churn_probability"] <= 1)
        stored = Prediction.objects.get(request_id=body["request_id"])
        self.assertEqual(stored.features["contract"], "monthly")

    # ... invalid input (400), missing token (401), no active model (503),
    # second active version (IntegrityError), activation switch, cache reuse

    def test_tampered_artifact_is_refused(self):
        ModelVersion.objects.filter(pk=self.mv.pk).update(sha256="0" * 64)
        with self.assertRaises(registry.ArtifactError):
            registry.get_model("churn")

    def test_batch_chunk_is_idempotent(self):
        ids = [str(i) for i in range(1, 51)]
        self.assertEqual(score_chunk("b1", ids, self.mv.pk), 50)
        self.assertEqual(score_chunk("b1", ids, self.mv.pk), 0)
        self.assertEqual(Prediction.objects.filter(batch="b1").count(), 50)
$ python manage.py test scoring
Found 10 test(s).
..........
----------------------------------------------------------------------
Ran 10 tests in 0.170s

OK

Clear the registry cache in setUp: it is module-level and outlives each test's transaction.

Checklist

  1. The artifact contains the full pipeline, including preprocessing, and is saved with skops.
  2. Metadata records version, training time, features, metrics, library versions and SHA-256.
  3. The serving environment pins the scikit-learn version the model was trained with.
  4. The checksum is verified and untrusted types are refused before loading.
  5. Exactly one active version per model is enforced by a database constraint.
  6. Models load once per process; the cache is thread-safe and tests clear it.
  7. The endpoint rejects unknown fields, out-of-range values and oversized bodies, and requires authentication.
  8. Every prediction is stored with its version, inputs, score and request id, under a retention policy.
  9. Batch tasks are chunked, pinned to one version, idempotent, and retry only transient errors.
  10. Daily jobs compute PSI, score distribution, latency percentiles and accuracy on labelled rows, and alert on thresholds.

Found a mistake in this tutorial? Let us know and we will fix it.