6. Monitoring & Logs
Logging Model Inputs and Predictions
In a production environment, simply returning a prediction is insufficient. You must log the input features and the resulting model output to create an audit trail for debugging and retraining.
The standard practice is to use the Python logging module or specialized telemetry libraries to capture JSON-formatted records containing a request ID, input data, and the prediction value.
Below is a simple implementation of a structured logger that records interaction data to a mock persistence layer.
import json import datetime def log_prediction(request_id, features, prediction): record = { 'timestamp': datetime.datetime.utcnow().isoformat(), 'request_id': request_id, 'features': features, 'prediction': prediction } # In real scenarios, send this to ELK or CloudWatch print(f'LOGGED: {json.dumps(record)}') log_prediction('req-123', {'age': 25, 'income': 50000}, 0.85)
Detecting Performance Drift and Data Shift
Performance drift occurs when model accuracy declines over time. Data distribution shift (or covariate shift) happens when the statistical properties of the input features change compared to the training data.
Monitoring these shifts involves comparing the distribution of incoming features against a baseline distribution (the reference dataset used during training).
The following table compares the two core concepts of monitoring degradation.
| Feature | Description |
|---|---|
| Data Shift | The input data statistics change (e.g., mean feature value increases). |
| Performance Drift | The relationship between input and target changes, causing lower accuracy. |
Measuring Endpoint Latency and Error Rates
Infrastructure monitoring is critical for service reliability. Latency measures how long the model takes to respond, while error rates measure the frequency of 4xx and 5xx HTTP responses.
You should instrument your inference code to capture timing metrics using decorators or middleware to ensure that performance bottlenecks in the model pipeline are identified immediately.
Below is a basic timer decorator to track inference performance.
import time def monitor_latency(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f'Latency: {end - start:.4f} seconds') return result return wrapper @monitor_latency def predict(x): time.sleep(0.1) return x * 2 predict(10)
Health Check Endpoints
Orchestrators like Kubernetes require health check endpoints (/health) to verify if a container is Ready (can handle traffic) or Liveness (needs a restart).
A proper health check does not just return 200 OK; it verifies that essential dependencies like the model file, the GPU, or database connections are initialized.
The example below simulates an endpoint check that verifies model load status.
class ModelServer: def __init__(self): self.model_loaded = True def health_check(self): if self.model_loaded: return {'status': 'healthy', 'code': 200} return {'status': 'unhealthy', 'code': 503} server = ModelServer() print(server.health_check())
Knowledge Check
Ready to test your understanding of 6. Monitoring & Logs?