Skip to main content

Lesson 4 of 9

Real-Time Model Performance Monitoring, Metrics Export & Prometheus/Grafana Setup

Deploying a model is only day one of the ML lifecycle. Production systems require real-time telemetry: tracking inference latency percentiles (p50, p95, p99), HTTP error rates, input feature null rates, prediction score distributions, and system resource utilization (CPU, GPU, RAM). Prometheus scrapes these time-series metrics from the inference microservice, exposing them to interactive Grafana operational dashboards.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Prometheus Metric Instrumentation in an ML Serving Service

Prometheus Metric Instrumentation in an ML Serving Service
import time
import numpy as np

# Simulated Prometheus Metrics Client
class MockPrometheusMetrics:
    def __init__(self):
        self.request_counter = 0
        self.latency_samples = []
        self.prediction_classes = {0: 0, 1: 0}
        self.null_feature_count = 0

    def record_inference(self, latency_ms: float, prediction: int, had_nulls: bool):
        self.request_counter += 1
        self.latency_samples.append(latency_ms)
        self.prediction_classes[prediction] += 1
        if had_nulls:
            self.null_feature_count += 1

    def scrape_prometheus_metrics(self) -> str:
        p95_lat = np.percentile(self.latency_samples, 95) if self.latency_samples else 0.0
        p99_lat = np.percentile(self.latency_samples, 99) if self.latency_samples else 0.0
        
        output = [
            "# HELP ml_predictions_total Total inference requests served",
            f"ml_predictions_total {self.request_counter}",
            "# HELP ml_inference_latency_p95_ms 95th percentile latency",
            f"ml_inference_latency_p95_ms {p95_lat:.2f}",
            "# HELP ml_inference_latency_p99_ms 99th percentile latency",
            f"ml_inference_latency_p99_ms {p99_lat:.2f}",
            "# HELP ml_positive_prediction_rate Ratio of class 1 predictions",
            f"ml_positive_prediction_rate {self.prediction_classes[1] / max(self.request_counter, 1):.4f}",
            "# HELP ml_null_feature_warnings Total requests containing unexpected nulls",
            f"ml_null_feature_warnings {self.null_feature_count}"
        ]
        return "\n".join(output)

# Simulate traffic stream
metrics = MockPrometheusMetrics()
for _ in range(500):
    lat = np.random.lognormal(mean=2.0, sigma=0.4) # ~7ms typical
    pred = np.random.choice([0, 1], p=[0.92, 0.08])
    null_flag = np.random.uniform(0, 1) < 0.02 # 2% null rate
    metrics.record_inference(lat, pred, null_flag)

print("=== PROMETHEUS /METRICS EXPORT PAYLOAD ===")
print(metrics.scrape_prometheus_metrics())

Pro Tip: Monitor Prediction Output Distribution Shifts

You often lack ground truth labels in real time, but you ALWAYS have the model's output probabilities. If your fraud model historically flags 2.5% of transactions as positive, and suddenly the positive prediction rate spikes to 12.0% over an hour, an upstream data corruption or fraud attack is actively occurring.

Diagram
Loading diagramโ€ฆ

MlModelMonitoring Visual Representation

Hands-On Challenge: Build a Grafana Alert Rule

Define a Prometheus alert query in PromQL: `rate(ml_null_feature_warnings[5m]) > 0.05` that triggers a PagerDuty incident when the incoming null feature rate exceeds 5% over a 5-minute rolling window.

Quick Quiz & Key Concept Checks

Common Pitfall: Storing Unbounded Histograms in RAM

Storing every individual latency floating-point value in a Python list indefinitely will eventually cause a memory leak. Use a rolling ring buffer (e.g. `collections.deque(maxlen=10000)`) or Prometheus histogram buckets.

Topics in This Module

0/9 done