Deploying large language models in production demands comprehensive monitoring to ensure reliability, detect issues early, and maintain cost efficiency. This guide provides practical strategies for implementing effective monitoring across performance, resource, cost, and user feedback dimensions.
Core Monitoring Components
Performance Metrics and Latency Tracking
Response time is the most immediate indicator of LLM service health. Production deployments require granular latency tracking across different model configurations, prompt types, and request patterns. Implement structured logging with consistent formats to enable aggregation and analysis.
import time
import structlog
from typing import Dict, Any, Optional
from dataclasses import dataclass
from datetime import datetime
structlog.configure(
processors=[
structlog.stdlib.add_logger_name,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer(),
],
logger_factory=structlog.stdlib.LoggerFactory(),
)
logger = structlog.get_logger(__name__)
@dataclass
class InferenceMetrics:
model_name: str
prompt_type: str
latency_ms: int
success: bool
input_tokens: int
output_tokens: int
timestamp: str = None
def __post_init__(self):
if self.timestamp is None:
self.timestamp = datetime.utcnow().isoformat()
def track_inference(metrics: InferenceMetrics) -> None:
logger.info(
"llm_inference",
model=metrics.model_name,
prompt_type=metrics.prompt_type,
latency_ms=metrics.latency_ms,
success=metrics.success,
input_tokens=metrics.input_tokens,
output_tokens=metrics.output_tokens,
)
# Usage example in request handler
async def handle_request(request_data: Dict[str, Any]) -> Dict[str, Any]:
start_time = time.time()
try:
result = await llm_inference(request_data)
duration = int((time.time() - start_time) * 1000)
metrics = InferenceMetrics(
model_name=request_data.get("model", "unknown"),
prompt_type=request_data.get("prompt_type", "chat"),
latency_ms=duration,
success=True,
input_tokens=result.get("input_tokens", 0),
output_tokens=result.get("output_tokens", 0),
)
track_inference(metrics)
return result
except Exception as e:
duration = int((time.time() - start_time) * 1000)
metrics = InferenceMetrics(
model_name=request_data.get("model", "unknown"),
prompt_type=request_data.get("prompt_type", "chat"),
latency_ms=duration,
success=False,
input_tokens=0,
output_tokens=0,
)
track_inference(metrics)
raise
Error Classification and Pattern Analysis
Track and categorize errors to identify systemic issues and inform optimization efforts. Different error types require different responses—rate limits need backoff strategies, context length errors need prompt truncation, and authentication errors need credential rotation.
class ErrorMonitor:
ERROR_TYPES = {
"rate_limit": "API rate limit exceeded",
"context_length": "Prompt exceeds model context window",
"authentication": "Invalid credentials",
"content_filter": "Policy violation",
"model_unavailable": "Service unavailable",
"timeout": "Request timeout",
"validation_error": "Invalid request parameters",
}
def __init__(self):
self.error_counts: Dict[str, int] = {}
self.error_history: List[Dict[str, Any]] = []
def record_error(self, error_type: str, context: Optional[Dict] = None) -> None:
self.error_counts[error_type] = self.error_counts.get(error_type, 0) + 1
error_record = {
"type": error_type,
"description": self.ERROR_TYPES.get(error_type, "Unknown error"),
"context": context or {},
"timestamp": datetime.utcnow().isoformat(),
}
self.error_history.append(error_record)
logger.error("error_occurred", **error_record)
def get_error_summary(self, window_minutes: int = 60) -> Dict[str, Any]:
cutoff = datetime.utcnow() - timedelta(minutes=window_minutes)
recent_errors = [
e for e in self.error_history
if datetime.fromisoformat(e["timestamp"]) > cutoff
]
return {
"total_errors": len(recent_errors),
"by_type": Counter(e["type"] for e in recent_errors),
"error_rate": len(recent_errors) / max(window_minutes, 1),
}
Health Check Endpoints and Readiness Probes
Implement structured health checks for different system components to enable automated failover and deployment strategies.
# Kubernetes liveness and readiness probe configuration
apiVersion: v1
kind: Pod
metadata:
name: llm-inference-service
spec:
containers:
- name: llm-inference
image: your-llm-service:latest
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /health/live
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /health/ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
Resource Utilization Monitoring
CPU and Memory Tracking
Monitor compute resource consumption to optimize instance sizing and prevent resource exhaustion. Set up alerts for memory pressure and CPU saturation.
import psutil
import os
def get_system_metrics() -> Dict[str, Any]:
mem = psutil.virtual_memory()
cpu = psutil.cpu_percent(interval=1)
process = psutil.Process(os.getpid())
process_mem = process.memory_info()
return {
"system_memory_percent": mem.percent,
"system_memory_available_gb": mem.available / (1024**3),
"system_cpu_percent": cpu,
"process_memory_rss_mb": process_mem.rss / (1024**2),
"process_memory_vms_mb": process_mem.vms / (1024**2),
"timestamp": datetime.utcnow().isoformat(),
}
GPU Monitoring for Accelerated Deployments
For GPU-accelerated LLM deployments, track GPU memory, utilization, and temperature to optimize batch sizes and prevent thermal throttling.
import subprocess
import json
from typing import List, Dict, Any
def get_gpu_metrics() -> List[Dict[str, Any]]:
try:
result = subprocess.run(
["nvidia-smi",
"--query-gpu=index,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw",
"--format=csv,noheader,nounits"],
capture_output=True,
text=True,
timeout=5,
)
gpu_metrics = []
for line in result.stdout.strip().split("\n"):
if line.strip():
parts = [p.strip() for p in line.split(",")]
gpu_metrics.append({
"index": int(parts[0]),
"utilization_percent": int(parts[1]),
"memory_used_mb": int(parts[2]),
"memory_total_mb": int(parts[3]),
"temperature_c": int(parts[4]),
"power_draw_w": float(parts[5]) if parts[5] != "[Not Supported]" else None,
"timestamp": datetime.utcnow().isoformat(),
})
return gpu_metrics
except Exception as e:
logger.error("gpu_metrics_failed", error=str(e))
return [{"error": "GPU monitoring unavailable"}]
Cost Monitoring and Budget Management
Per-Request Cost Calculation
Calculate and monitor costs based on model pricing to prevent budget overruns and identify optimization opportunities.
class CostMonitor:
PRICING = {
"gpt-4": {"input": 0.03, "output": 0.06},
"gpt-4-32k": {"input": 0.06, "output": 0.12},
"gpt-3.5-turbo": {"input": 0.001, "output": 0.002},
"claude-3-opus": {"input": 0.015, "output": 0.075},
"claude-3-sonnet": {"input": 0.003, "output": 0.015},
}
def __init__(self, daily_budget: float = 100.0, monthly_budget: float = 3000.0):
self.daily_budget = daily_budget
self.monthly_budget = monthly_budget
self.daily_spend = 0.0
self.monthly_spend = 0.0
self.request_costs: List[Dict] = []
def calculate_cost(self, model: str, input_tokens: int, output_tokens: int) -> float:
pricing = self.PRICING.get(model, {"input": 0.01, "output": 0.02})
cost = (input_tokens / 1000) * pricing["input"] + (output_tokens / 1000) * pricing["output"]
return cost
def record_cost(self, model: str, input_tokens: int, output_tokens: int) -> float:
cost = self.calculate_cost(model, input_tokens, output_tokens)
self.daily_spend += cost
self.monthly_spend += cost
self.request_costs.append({
"model": model,
"cost": cost,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"timestamp": datetime.utcnow().isoformat(),
})
# Alert on budget thresholds
if self.daily_spend > self.daily_budget * 0.8:
logger.warning("daily_budget_warning", spent=self.daily_spend, budget=self.daily_budget)
if self.monthly_spend > self.monthly_budget * 0.8:
logger.warning("monthly_budget_warning", spent=self.monthly_spend, budget=self.monthly_budget)
return cost
def get_cost_summary(self) -> Dict[str, Any]:
return {
"daily_spend": self.daily_spend,
"daily_budget": self.daily_budget,
"daily_utilization": self.daily_spend / self.daily_budget,
"monthly_spend": self.monthly_spend,
"monthly_budget": self.monthly_budget,
"monthly_utilization": self.monthly_spend / self.monthly_budget,
"total_requests": len(self.request_costs),
"average_cost_per_request": sum(c["cost"] for c in self.request_costs) / max(len(self.request_costs), 1),
}
User Feedback and Quality Monitoring
Success Rate and Satisfaction Tracking
Monitor request success rates and user satisfaction to gauge service quality and identify degradation.
class QualityMonitor:
def __init__(self):
self.total_requests = 0
self.successful_requests = 0
self.user_ratings: List[Dict] = []
def record_request(self, success: bool) -> None:
self.total_requests += 1
if success:
self.successful_requests += 1
def record_feedback(self, request_id: str, rating: int, comment: Optional[str] = None) -> None:
feedback = {
"request_id": request_id,
"rating": max(1, min(5, rating)),
"comment": comment,
"timestamp": datetime.utcnow().isoformat(),
}
self.user_ratings.append(feedback)
logger.info("user_feedback", **feedback)
@property
def success_rate(self) -> float:
return (self.successful_requests / self.total_requests * 100) if self.total_requests > 0 else 0
@property
def average_rating(self) -> float:
if not self.user_ratings:
return 0.0
return sum(r["rating"] for r in self.user_ratings) / len(self.user_ratings)
def get_quality_summary(self) -> Dict[str, Any]:
return {
"success_rate": self.success_rate,
"total_requests": self.total_requests,
"successful_requests": self.successful_requests,
"average_rating": self.average_rating,
"feedback_count": len(self.user_ratings),
}
Alerting and Incident Response
Automated Alert Configuration
Set up alerts for critical thresholds and anomalies to enable rapid response.
# Example alert rules for LLM services
alerts:
high_error_rate:
description: "Error rate exceeds 5% over 5-minute window"
condition: "error_rate_5min > 0.05"
severity: "high"
notification_channels: ["pagerduty", "slack:#oncall"]
runbook: "https://wiki.example.com/runbooks/high-error-rate"
latency_spike:
description: "P95 latency exceeds 5 seconds over 10-minute window"
condition: "p95_latency_10min > 5000"
severity: "medium"
notification_channels: ["slack:#engineering"]
runbook: "https://wiki.example.com/runbooks/latency-spike"
cost_overrun:
description: "Daily spend exceeds 80% of budget"
condition: "daily_spend > budget_daily * 0.8"
severity: "medium"
notification_channels: ["slack:#finance"]
runbook: "https://wiki.example.com/runbooks/cost-overrun"
gpu_memory_pressure:
description: "GPU memory usage exceeds 90%"
condition: "gpu_memory_percent > 0.9"
severity: "high"
notification_channels: ["pagerduty", "slack:#platform"]
runbook: "https://wiki.example.com/runbooks/gpu-memory"
Dashboard and Visualization Strategy
Role-Based Dashboards
Create dashboards tailored to different stakeholder perspectives:
Engineering Dashboard:
- Real-time request latency (p50, p95, p99)
- Error rates by model and endpoint
- GPU/CPU utilization and memory pressure
- Request throughput and queue depths
Operations Dashboard:
- Service health status and uptime
- Deployment status and version information
- Incident timeline and resolution status
- Capacity planning metrics
Finance Dashboard:
- Daily/monthly spend by model
- Cost per request trends
- Budget utilization and forecasting
- ROI metrics for different use cases
Implementation Best Practices
- Structured Logging: Use consistent JSON log formats with semantic field names
- Alert Thresholds: Set meaningful thresholds based on historical baselines and business impact
- Dashboard Design: Create role-specific views that surface actionable information
- Integration: Connect monitoring with incident response and deployment systems
- Regular Review: Schedule weekly analysis of monitoring data and alert tuning
- Documentation: Maintain runbooks for common alert scenarios
Conclusion
Effective monitoring transforms LLM deployments from reactive to proactive operations. By implementing comprehensive monitoring across performance, resource, cost, and user feedback dimensions, teams can ensure reliable service delivery while optimizing costs and user experience. Start with core metrics, then expand monitoring coverage based on observed patterns and stakeholder needs.
Related Catalog Entry
For comprehensive deployment checklists and infrastructure patterns, see the related article: LLM Production Deployment: Essential Checklist and Best Practices. This complementary guide covers architecture patterns, infrastructure requirements, and operational checklists for LLM deployment.