Ai deployment patterns

From FerroxLabs/murage · View interactive version

Ai deployment patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level ai deployment patterns implementation: ai-ml and devops decision frameworks, production-ready patterns, and concrete templates for ai deployment patterns workflows. Use when the user asks about ai deployment patterns, ai deployment patterns configuration, or ai-ml best practices

How to use this skill

Skill file

AI Deployment Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

Step 1: Classify the Deployment Scenario

Before recommending any pattern, establish the concrete constraints.

Step 2: Select the Core Serving Pattern

Match the classified scenario to the correct serving architecture.

Step 3: Design the Release and Rollout Strategy

Never deploy a new model version directly to 100% of traffic without a staged rollout.

Step 4: Implement Model Versioning and the Model Registry

Model artifacts must be versioned and reproducible before any deployment pattern will work reliably.

Step 5: Build the Inference Serving Infrastructure

Design the serving layer with production requirements, not prototype assumptions.

Step 6: Implement Observability for Production ML

ML systems have failure modes that standard application monitoring misses entirely.

Step 7: Design Fallback and Graceful Degradation

Every production ML system must have a defined behavior when the model is unavailable or returning low-confidence predictions.


Output Format

Produce the following artifacts when designing or documenting an AI deployment pattern.

Deployment Pattern Decision Summary

Model Deployment Decision Record
=================================
Date:           2024-01-15
Author:         <engineer name>
Model:          customer-churn-classifier-v3
Use Case:       Real-time churn risk scoring at checkout

Serving Pattern:    Synchronous REST API (FastAPI + BentoML)
Rationale:          P99 latency SLA = 200ms, RPS = 45 peak, model size = 85MB

Release Strategy:   Shadow mode (48h) → Canary 5% (24h) → Canary 25% (24h) → Full
Rollback Trigger:   P99 > 180ms OR error rate > 0.5% OR prediction_null_rate > 2%
Fallback:           Rule-based threshold (recency + frequency score)

Infrastructure:
  Replicas (min/max):    2 / 10
  Container CPU:         0.5 / 2.0 cores
  Container Memory:      1Gi / 2Gi
  Autoscale Metric:      request queue depth > 50
  
Monitoring:
  Drift Detection:       PSI on 6 input features, 1-hour rolling window
  Alert P1:              error_rate > 1%, P99 > 200ms
  Alert P2:              PSI > 0.2, prediction_mean shift > 1.5 std

Architecture Diagram (ASCII)

Client Request
      |
      v
[API Gateway / Load Balancer]
      |
      |-- Feature Flag: canary? --> [Model v3 Serving Cluster]
      |                                    |
      |-- (else) -----------------> [Model v2 Serving Cluster]
                                          |
                           +-- Input Validation (schema check)
                           +-- Feature Preprocessing
                           +-- [Model Inference Engine]
                           |        |
                           |   [Prediction Cache (Redis, TTL=5min)]
                           |        |
                           +-- Confidence Check
                                  |
                    >= 0.6 -------+------- < 0.6
                      |                       |
               Serve prediction         [Fallback: rule-based]
                      |
                [Prediction Logger]
                      |
                [Response to Client]
                      
Async path:
[Prediction Logger] --> [Kafka topic: model-predictions]
                              |
                   [Drift Detector (Evidently)]
                              |
                   [Metrics Dashboard (Grafana)]
                              |
                   [Alert Manager (PagerDuty)]

Serving Configuration Template (BentoML / FastAPI)

# serving/model_service.py
# Synchronous REST inference service with fallback, caching, and observability

import time
import hashlib
import logging
from typing import Optional
from dataclasses import dataclass

import redis
import bentoml
from bentoml.io import NumpyNdarray, JSON
from prometheus_client import Histogram, Counter, Gauge

# -- Prometheus metrics
INFERENCE_LATENCY = Histogram(
    "model_inference_latency_seconds",
    "Model inference latency",
    buckets=[0.01, 0.025, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0],
    labelnames=["model_version", "path"],  # path: "model" | "cache" | "fallback"
)
PREDICTION_COUNTER = Counter(
    "model_predictions_total",
    "Total predictions served",
    labelnames=["model_version", "path", "confidence_bucket"],
)
FALLBACK_COUNTER = Counter(
    "model_fallback_total",
    "Total fallback activations",
    labelnames=["reason"],  # "low_confidence" | "timeout" | "error"
)

logger = logging.getLogger(__name__)


@dataclass
class InferenceConfig:
    model_tag: str                  # e.g. "churn-classifier:v3.2.1"
    model_version: str              # e.g. "v3.2.1" for labels
    confidence_threshold: float     # e.g. 0.60
    cache_ttl_seconds: int          # e.g. 300
    inference_timeout_ms: int       # e.g. 150
    redis_url: str                  # e.g. "redis://redis-svc:6379/0"
    warmup_requests: int            # e.g. 20


class ModelService:
    def __init__(self, config: InferenceConfig) -> None:
        self.config = config
        self.runner = bentoml.models.get(config.model_tag).to_runner()
        self.cache = redis.from_url(config.redis_url, decode_responses=True)
        self._warmup()

    def _warmup(self) -> None:
        """Run warmup inferences before marking service ready."""
        import numpy as np
        dummy_input = np.zeros((1, 12), dtype=np.float32)  # match training feature count
        for i in range(self.config.warmup_requests):
            self.runner.predict.run(dummy_input)
        logger.info(
            "Warmup complete",
            extra={"warmup_requests": self.config.warmup_requests}
        )

    def _cache_key(self, features: dict) -> str:
        canonical = str(sorted(features.items()))
        return f"pred:{hashlib.sha256(canonical.encode()).hexdigest()[:16]}"

    def _rule_based_fallback(self, features: dict) -> dict:
        """
        Rule-based fallback: deterministic churn score from recency + frequency.
        Returns same schema as model output for transparent substitution.
        """
        recency_days = features.get("days_since_last_order", 999)
        order_count = features.get("order_count_90d", 0)
        score = min(1.0, recency_days / 180.0) * (1.0 - min(1.0, order_count / 10.0))
        return {
            "churn_probability": round(score, 4),
            "confidence": 0.0,          # signal to downstream that this is a fallback
            "prediction_source": "fallback_rules",
        }

    async def predict(self, features: dict) -> dict:
        start = time.perf_counter()
        cache_key = self._cache_key(features)

        # -- Cache check
        cached = self.cache.get(cache_key)
        if cached:
            elapsed = (time.perf_counter() - start) * 1000
            INFERENCE_LATENCY.labels(
                model_version=self.config.model_version, path="cache"
            ).observe(elapsed / 1000)
            PREDICTION_COUNTER.labels(
                model_version=self.config.model_version,
                path="cache",
                confidence_bucket="high",
            ).inc()
            return {"churn_probability": float(cached), "prediction_source": "cache"}

        # -- Model inference with timeout guard
        import asyncio
        import numpy as np

        feature_vector = np.array(
            [list(features.values())], dtype=np.float32
        )
        try:
            result = await asyncio.wait_for(
                self.runner.predict.async_run(feature_vector),
                timeout=self.config.inference_timeout_ms / 1000.0,
            )
            churn_prob = float(result[0][1])  # index 1 = churn class probability
            confidence = max(churn_prob, 1.0 - churn_prob)

            elapsed = (time.perf_counter() - start) * 1000
            confidence_bucket = "high" if confidence >= 0.6 else "low"
            INFERENCE_LATENCY.labels(
                model_version=self.config.model_version, path="model"
            ).observe(elapsed / 1000)
            PREDICTION_COUNTER.labels(
                model_version=self.config.model_version,
                path="model",
                confidence_bucket=confidence_bucket,
            ).inc()

            # -- Confidence gate
            if confidence < self.config.confidence_threshold:
                FALLBACK_COUNTER.labels(reason="low_confidence").inc()
                return self._rule_based_fallback(features)

            # -- Cache successful high-confidence prediction
            self.cache.setex(cache_key, self.config.cache_ttl_seconds, str(churn_prob))

            return {
                "churn_probability": round(churn_prob, 4),
                "confidence": round(confidence, 4),
                "prediction_source": f"model:{self.config.model_version}",
            }

        except asyncio.TimeoutError:
            FALLBACK_COUNTER.labels(reason="timeout").inc()
            logger.warning("Model inference timeout", extra={"timeout_ms": self.config.inference_timeout_ms})
            return self._rule_based_fallback(features)

        except Exception as exc:
            FALLBACK_COUNTER.labels(reason="error").inc()
            logger.error("Model inference error", exc_info=exc)
            return self._rule_based_fallback(features)

Drift Monitoring Configuration

# drift_config.yaml -- Evidently AI drift profile
reference_dataset: s3://ml-artifacts/churn-v3/reference/training_sample_10k.parquet
monitoring_window_hours: 1
alert_channel: pagerduty-p2

features:
  - name: days_since_last_order
    type: numerical
    drift_method: psi
    alert_threshold: 0.20

  - name: order_count_90d
    type: numerical
    drift_method: psi
    alert_threshold: 0.20

  - name: payment_method
    type: categorical
    drift_method: chi_square
    alert_threshold: 0.05   # p-value threshold

  - name: customer_tier
    type: categorical
    drift_method: chi_square
    alert_threshold: 0.05

prediction_monitoring:
  metric: mean_predicted_probability
  baseline_window_days: 30
  alert_on_shift_std: 2.0

Rules

  1. Never skip shadow mode for a significant model change. A "significant" change includes: different training data vintage, different feature set, different model architecture or framework, or > 5% change in offline evaluation metrics. Shadow mode is cheap insurance. Skipping it is how silent prediction regressions reach production.
  1. Define rollback criteria before the canary starts, not after. Specifying rollback thresholds retroactively creates pressure to rationalize away degradation signals. Write the thresholds in the deployment record before the rollout begins and treat them as hard gates, not guidelines.
  1. Never bake model weights into the container image for models larger than 500MB. Image pull times for large images during autoscale events will exceed your latency SLA. Load weights from object storage at startup, use a persistent volume claim for caching, or use a dedicated model download init container.
  1. Always set a hard timeout on model inference that is no more than 60% of the total request SLA. Leaving 40% of the time budget for network, preprocessing, and postprocessing prevents a slow model from consuming the entire timeout and leaving no room for the fallback path to execute within SLA.
  1. Never use random per-request routing for A/B model experiments. Random per-request routing means the same user can get different model versions in consecutive requests, creating inconsistent experiences and confounding session-level business metrics. Always hash on a stable user or entity identifier.
  1. Always version the preprocessing pipeline alongside the model weights. A model trained on a specific scaler, encoder, or tokenizer will produce garbage predictions if the preprocessing changes without retraining. The model artifact must include or reference the exact preprocessing code and parameters used during training.
  1. Never disable prediction logging in production, even under load. Prediction logs are required for debugging, retraining, and drift detection. If logging is causing latency problems, make it asynchronous (fire-and-forget to a Kafka topic) rather than disabling it. The cost of losing prediction logs during an incident is higher than the latency overhead.
  1. Always implement readiness and liveness probes with different behaviors. The liveness probe should only check that the process is alive (not deadlocked). The readiness probe should verify that the model is loaded and has passed warmup. Conflating them causes Kubernetes to restart healthy-but-loading containers during startup.
  1. Never deploy to GPU without profiling the actual batch size vs. throughput curve for your specific model. The optimal batch size is not always the maximum. For transformer models, throughput often plateaus at batch size 16-32 and memory requirements grow quadratically with sequence length. Profile before setting max_batch_size in production.
  1. Always store the training data version or data snapshot identifier alongside the model artifact. Without this, debugging a model regression is nearly impossible -- you cannot reproduce the training run, understand what distribution the model was trained on, or determine whether a drift alert indicates real world change or a data pipeline bug.

Edge Cases

LLM-Backed Services with Non-Deterministic Latency

Large language model inference has highly variable latency -- a short prompt may complete in 200ms while a long generation takes 15+ seconds. Standard synchronous REST patterns break under this variability.

Multi-Model Cascade (Cheap Screener + Expensive Specialist)

When a fast cheap model handles easy cases and a slow expensive model handles hard cases, the cascade pattern introduces complexity around what "hard" means.

GPU Node Interruptions and Spot/Preemptible Instance Use

GPU compute is expensive, and spot or preemptible instances can reduce cost by 60-80%, but they can be interrupted with 2-minute notice.

Model Registry and Serving Across Multiple Environments (Dev/Staging/Production)

Model versions and their promotion states must be environment-aware without creating per-environment artifact duplication.

Prediction Schema Drift Between Model Versions

When a new model version changes input feature names, adds features, or changes output schema, the serving layer must handle both old and new schemas during the rollout window.

Cold Start Latency on Serverless and Auto-Scaled Deployments

When the serving infrastructure scales to zero or starts a new replica from scratch, the first request experiences significantly higher latency due to container image pull, process startup, and model weight loading.


Example

Input: "We have a fraud detection model (an XGBoost classifier, ~12MB, 45 features) that currently runs as a nightly batch job, scoring all transactions from the day before. The fraud team wants real-time scoring at transaction time with a P99 latency of 150ms. We're on AWS and use Kubernetes. The model is already in SageMaker Model Registry. What deployment pattern should we use and how do we roll it out safely?"


Output:

Step 1: Deployment Pattern Selection

This is a synchronous real-time REST API deployment. The requirements are:

Reject async/queue-based pattern because the fraud decision must block the transaction authorization -- 150ms is the budget for the full synchronous call, not for a polling loop. A queue-based pattern would add 500ms-2 seconds of round-trip to check job status.

Reject the batch pattern for real-time use cases -- the current nightly batch job should be retained as a secondary reconciliation job to catch transactions missed during a serving outage, but it cannot fulfill the real-time requirement.

Step 2: Architecture

Transaction Service (Spring Boot)
         |
         | POST /v1/predict  (timeout: 100ms hard limit)
         v
[AWS ALB -- weighted target groups for canary]
         |
    +----+----+
    |         |
  [v1]      [v2]         <- during canary window
  [XGB]     [XGB]
         |
[FastAPI inference container on EKS]
    |
    +-- Input validation (45-feature schema check, null imputation)
    +-- XGBoost model inference (< 5ms)
    +-- Confidence gate: if max_probability < 0.55 --> return fraud_score=null, route_to_review=true
    +-- Redis cache (TTL=60s, key=hash(card_token + merchant_id + amount_bucket))
    +-- Prediction logger (async, Kafka topic: fraud-predictions)
         |
    [Flink consumer]
         |
    [Drift detector (Evidently)]  -->  [CloudWatch Metrics + PagerDuty alerts]

Step 3: Rollout Plan

Week 1 -- Shadow Mode:

Week 2 -- Canary 5%:

Week 3 -- Canary 25% then 100%:

Step 4: Infrastructure Configuration (EKS)

# k8s/fraud-inference-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: fraud-inference-v2
  labels:
    app: fraud-inference
    version: v2
spec:
  replicas: 3          # minimum 3 for HA + rolling updates without downtime
  selector:
    matchLabels:
      app: fraud-inference
      version: v2
  template:
    spec:
      containers:
        - name: inference
          image: 123456789.dkr.ecr.us-east-1.amazonaws.com/fraud-inference:v2.3.1
          resources:
            requests:
              cpu: "500m"
              memory: "512Mi"
            limits:
              cpu: "2000m"
              memory: "1Gi"
          env:
            - name: MODEL_PATH
              value: "/app/models/xgb_fraud_v2.3.1.ubj"   # baked in image (12MB is fine)
            - name: CONFIDENCE_THRESHOLD
              value: "0.55"
            - name: INFERENCE_TIMEOUT_MS
              value: "80"         # 80ms leaves 70ms for network + preprocessing within 150ms SLA
            - name: REDIS_URL
              valueFrom:
                secretKeyRef:
                  name: fraud-inference-secrets
                  key: redis-url
          livenessProbe:
            httpGet:
              path: /healthz       # only checks process is alive
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /readyz        # checks model loaded + warmup complete
              port: 8080
            initialDelaySeconds: 15   # enough time for warmup (20 requests x 5ms = 100ms)
            periodSeconds: 5
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: fraud-inference-v2-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: fraud-inference-v2
  minReplicas: 3
  maxReplicas: 20
  metrics:
    - type: Pods
      pods:
        metric:
          name: http_requests_in_flight    # custom metric via KEDA or Prometheus adapter
        target:
          type: AverageValue
          averageValue: "50"              # scale when avg 50 concurrent requests per pod

Step 5: Prediction Logger (Async, Non-Blocking)

# serving/prediction_logger.py
import json
import time
import threading
from queue import Queue, Full
from dataclasses import dataclass, asdict
from typing import Optional
from kafka import KafkaProducer

@dataclass
class PredictionRecord:
    request_id: str
    timestamp_ms: int
    model_version: str
    # Features stored as hash to avoid logging PII card numbers
    feature_hash: str
    # Store non-PII features directly for drift analysis
    transaction_amount_bucket: str    # e.g. "0-10", "10-50", "50-200", "200+"
    merchant_category_code: str
    hour_of_day: int
    day_of_week: int
    # Outputs
    fraud_probability: float
    fraud_decision: bool              # True = flagged
    prediction_source: str            # "model:v2" | "fallback_rules" | "cache"
    inference_latency_ms: float
    confidence: float

class AsyncPredictionLogger:
    """
    Non-blocking prediction logger. Drops events if the queue is full
    rather than blocking the inference response path.
    Acceptable loss rate for logging: < 0.1% of events.
    """
    def __init__(self, kafka_bootstrap: str, topic: str, queue_maxsize: int = 10_000):
        self._queue: Queue = Queue(maxsize=queue_maxsize)
        self._producer = KafkaProducer(
            bootstrap_servers=kafka_bootstrap,
            value_serializer=lambda v: json.dumps(v).encode("utf-8"),
            acks=1,            # leader ack only -- prioritize throughput over durability for logs
            compression_type="gzip",
        )
        self._dropped_count = 0
        self._thread = threading.Thread(target=self._flush_loop, daemon=True)
        self._thread.start()

    def log(self, record: PredictionRecord) -> None:
        try:
            self._queue.put_nowait(asdict(record))
        except Full:
            self._dropped_count += 1
            # Log to stderr only -- do NOT block or raise
            if self._dropped_count % 1000 == 0:
                print(f"WARN: PredictionLogger queue full, dropped {self._dropped_count} events")

    def _flush_loop(self) -> None:
        while True:
            record = self._queue.get()
            try:
                self._producer.send("fraud-predictions", value=record)
            except Exception as e:
                print(f"WARN: Kafka send failed: {e}")

Step 6: Monitoring Alert Rules (Prometheus / Alertmanager)

# alerts/fraud-inference-alerts.yaml
groups:
  - name: fraud_inference_p1
    rules:
      - alert: FraudInferenceHighErrorRate
        expr: |
          rate(http_requests_total{job="fraud-inference", status=~"5.."}[5m])
          / rate(http_requests_total{job="fraud-inference"}[5m]) > 0.01
        for: 2m
        labels:
          severity: critical
          team: ml-platform
        annotations:
          summary: "Fraud inference error rate > 1% for 2 minutes"

      - alert: FraudInferenceP99LatencyBreach
        expr: |
          histogram_quantile(0.99,
            rate(model_inference_latency_seconds_bucket{job="fraud-inference"}[5m])
          ) > 0.12   # 120ms = 80% of 150ms SLA -- alert before the SLA is actually breached
        for: 3m
        labels:
          severity: critical

  - name: fraud_inference_p2
    rules:
      - alert: FraudInferenceFallbackRateHigh
        expr: |
          rate(model_fallback_total{job="fraud-inference"}[15m]) > 0.05
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Fallback activation rate > 5% -- model may be degrading"

      - alert: FraudInferencePredictionDistributionShift
        expr: |
          abs(
            avg_over_time(fraud_prediction_mean[1h])
            - avg_over_time(fraud_prediction_mean[30d])
          ) / stddev_over_time(fraud_prediction_mean[30d]) > 2.0
        for: 30m
        labels:
          severity: warning
        annotations:
          summary: "Fraud score distribution shifted > 2 std from 30-day baseline"

Expected Outcomes

After full rollout to 100% of real-time traffic:

The nightly batch job is retained as a reconciliation mechanism for 30 days, then decommissioned. Keep the batch infrastructure configuration in version control for 90 days post-decommission in case an outage requires temporary reactivation.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.