Deploying large language models in production requires more than just infrastructure setup—it demands comprehensive monitoring and observability to ensure reliability, detect issues early, and maintain service quality. As LLM workloads grow in complexity and scale, the ability to instrument, measure, and respond to system behavior becomes critical. This guide provides practical strategies for monitoring LLM applications from inference latency to cost tracking.
Inference Performance Monitoring
Latency Tracking and Alerting
Response time is the most immediate indicator of LLM service health. Implement granular latency tracking across different model layers and prompt types.
import time
import structlog
from typing import Dict, Any
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__)
def track_inference_latency(start_time: float, model_name: str,
prompt_type: str, success: bool) -> None:
duration = time.time() - start_time
logger.info(
"inference_completed",
model=model_name,
prompt_type=prompt_type,
latency_ms=int(duration * 1000),
success=success,
)
# Middleware example
class LatencyTrackingMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
start = time.time()
try:
await self.app(scope, receive, send)
finally:
duration = time.time() - start
# Extract model and prompt info from request
track_inference_latency(start, model_name="gpt-4",
prompt_type="chat", success=True)
Token Usage Monitoring
Track input and output token consumption to understand usage patterns and identify optimization opportunities.
class TokenUsageTracker:
def __init__(self):
self.usage_stats: Dict[str, Dict] = {}
def record_usage(self, model: str, input_tokens: int, output_tokens: int,
request_id: str) -> None:
if model not in self.usage_stats:
self.usage_stats[model] = {
"total_input": 0,
"total_output": 0,
"request_count": 0,
"per_request": [],
}
stats = self.usage_stats[model]
stats["total_input"] += input_tokens
stats["total_output"] += output_tokens
stats["request_count"] += 1
stats["per_request"].append({
"request_id": request_id,
"input": input_tokens,
"output": output_tokens,
})
def get_summary(self, model: str) -> Dict[str, Any]:
stats = self.usage_stats.get(model, {})
return {
"model": model,
"total_requests": stats.get("request_count", 0),
"total_input_tokens": stats.get("total_input", 0),
"total_output_tokens": stats.get("total_output", 0),
"average_input": stats.get("total_input", 0) / max(stats.get("request_count", 1), 1),
"average_output": stats.get("total_output", 0) / max(stats.get("request_count", 1), 1),
}
Error Detection and Classification
Error Pattern Analysis
Categorize and track different error types to identify systemic issues and inform optimization efforts.
class ErrorClassifier:
ERROR_CATEGORIES = {
"rate_limit": "API rate limit exceeded",
"context_length": "Prompt exceeds model context window",
"authentication": "Invalid API credentials",
"content_filter": "Content policy violation",
"model_unavailable": "Model endpoint not responding",
"internal_error": "Unexpected system error",
}
@classmethod
def classify_error(cls, error: Exception) -> str:
error_msg = str(error).lower()
for category, description in cls.ERROR_CATEGORIES.items():
if category in error_msg:
return category
return "internal_error"
@classmethod
def log_error(cls, error: Exception, context: Dict[str, Any]) -> None:
category = cls.classify_error(error)
logger.error(
"request_failed",
error=error,
category=category,
context=context,
)
Health Check Endpoints
Implement structured health checks for different system components.
# Example: Kubernetes liveness and readiness probes
apiVersion: v1
kind: ConfigMap
metadata:
name: llm-health-probes
data:
liveness-probe.yaml:
apiVersion: v1
kind: PodSpec
spec:
containers:
- name: llm-inference
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 avoid resource exhaustion.
import psutil
import structlog
structlog.configure(
processors=[
structlog.stdlib.add_logger_name,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer(),
],
)
logger = structlog.get_logger(__name__)
def monitor_resource_usage(process_id: int = None) -> Dict[str, Any]:
if process_id is None:
process_id = os.getpid()
process = psutil.Process(process_id)
mem_info = process.memory_info()
cpu_percent = process.cpu_percent()
logger.info(
"resource_monitored",
process_id=process_id,
memory_rss_mb=mem_info.rss / 1024 / 1024,
memory_vms_mb=mem_info.vms / 1024 / 1024,
cpu_percent=cpu_percent,
)
return {
"memory_rss_mb": mem_info.rss / 1024 / 1024,
"memory_vms_mb": mem_info.vms / 1024 / 1024,
"cpu_percent": cpu_percent,
}
GPU Monitoring for LLM Workloads
For GPU-accelerated deployments, track GPU memory, utilization, and temperature.
# Example: NVIDIA SMI-based GPU monitoring
import subprocess
import json
def get_gpu_status() -> Dict[str, Any]:
try:
result = subprocess.run(
["nvidia-smi", "--query-gpu=utilization.gpu,memory.used,memory.total,temperature.gpu",
"--format=csv,no,nounits"],
capture_output=True,
text=True,
)
gpu_data = result.stdout.strip().split("\n")
gpu_info = {}
for i, line in enumerate(gpu_data):
parts = [p.strip() for p in line.split(", ")]
gpu_info[f"gpu_{i}"] = {
"utilization_percent": int(parts[0]),
"memory_used_mb": int(parts[1]),
"memory_total_mb": int(parts[2]),
"temperature_c": int(parts[3]),
}
return gpu_info
except FileNotFoundError:
return {"error": "nvidia-smi not available"}
Cost Tracking and Budget Management
Per-Request Cost Calculation
Monitor and calculate the cost of each inference request based on model pricing.
class LLM CostTracker:
PRICING_TIER = {
"gpt-4-32k": {"input": 0.06, "output": 0.12}, # per 1K tokens
"gpt-4": {"input": 0.03, "output": 0.06},
"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):
self.daily_spend: float = 0.0
self.monthly_spend: float = 0.0
self.request_count: int = 0
self.model_breakdown: Dict[str, Dict] = {}
def calculate_request_cost(self, model: str, input_tokens: int,
output_tokens: int) -> float:
pricing = self.PRICING_TIER.get(model, {"input": 0.01, "output": 0.02})
input_cost = (input_tokens / 1000) * pricing["input"]
output_cost = (output_tokens / 1000) * pricing["output"]
total_cost = input_cost + output_cost
self.daily_spend += total_cost
self.monthly_spend += total_cost
self.request_count += 1
if model not in self.model_breakdown:
self.model_breakdown[model] = {"cost": 0.0, "count": 0}
self.model_breakdown[model]["cost"] += total_cost
self.model_breakdown[model]["count"] += 1
return total_cost
def check_budget(self, daily_limit: float, monthly_limit: float) -> bool:
exceeded = False
if self.daily_spend > daily_limit:
logger.warning(
"daily_budget_exceeded",
spent_today=self.daily_spend,
limit=daily_limit,
)
exceeded = True
if self.monthly_spend > monthly_limit:
logger.warning(
"monthly_budget_exceeded",
spent_this_month=self.monthly_spend,
limit=monthly_limit,
)
exceeded = True
return not exceeded
Cost Optimization Insights
Use monitoring data to identify cost-saving opportunities.
def analyze_cost_optimization(opts: LLM CostTracker) -> Dict[str, Any]:
insights = {
"model_switching_opportunities": [],
"prompt_optimization_candidates": [],
"caching_opportunities": [],
}
# Analyze model breakdown for cheaper alternatives
for model, data in opts.model_breakdown.items():
if "gpt-4" in model.lower() and data["count"] > 100:
insights["model_switching_opportunities"].append({
"current_model": model,
"suggestion": "Consider gpt-3.5-turbo for non-critical workloads",
"potential_savings": data["cost"] * 0.02, # rough estimate
})
return insights
User Experience and Feedback Monitoring
Success Rate Tracking
Monitor request success rates to identify degradation in service quality.
class SuccessRateMonitor:
def __init__(self):
self.total_requests: int = 0
self.successful_requests: int = 0
self.error_requests: int = 0
self.success_history: list = []
def record_request(self, success: bool) -> None:
self.total_requests += 1
if success:
self.successful_requests += 1
else:
self.error_requests += 1
success_rate = (self.successful_requests / self.total_requests) * 100
self.success_history.append({
"timestamp": datetime.utcnow().isoformat(),
"success_rate": success_rate,
})
@property
def current_success_rate(self) -> float:
return (self.successful_requests / self.total_requests * 100) if self.total_requests > 0 else 100.0
@property
def rolling_success_rate(self, window: int = 100) -> float:
window_data = self.success_history[-window:] if len(self.success_history) >= window else self.success_history
if not window_data:
return 100.0
rates = [entry["success_rate"] for entry in window_data]
return sum(rates) / len(rates)
User Feedback Collection
Implement mechanisms for collecting and analyzing user feedback.
def collect_user_feedback(request_id: str, rating: int, comment: str = None) -> None:
"""Store user feedback for quality analysis."""
feedback_record = {
"request_id": request_id,
"rating": rating, # 1-5 scale
"comment": comment,
"timestamp": datetime.utcnow().isoformat(),
}
# Store in database or analytics system
logger.info("user_feedback_collected", **feedback_record)
Alerting and Incident Response
Automated Alert Configuration
Set up alerts for critical thresholds and anomalies.
# Example: Alert configuration 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"]
latency_spike:
description: "P95 latency exceeds 5 seconds over 10-minute window"
condition: "p95_latency_10min > 5000"
severity: "medium"
notification_channels: ["slack:#engineering"]
cost_overrun:
description: "Daily spend exceeds 80% of budget"
condition: "daily_spend > budget_daily * 0.8"
severity: "medium"
notification_channels: ["slack:#finance"]
Incident Response Playbooks
Define standard responses for common incident types.
# LLM Service Incident Playbook
## High Error Rate Response
1. **Identify Scope**: Check affected models, endpoints, and time windows
2. **Verify External Dependencies**: API status, rate limits, network issues
3. **Review Recent Deployments**: Check for recent code or configuration changes
4. **Implement Mitigation**:
- Enable fallback model if available
- Reduce request volume via circuit breaker
- Clear any stuck queues or caches
5. **Communicate**: Notify stakeholders and provide estimated resolution time
6. **Root Cause Analysis**: Document findings and prevent recurrence
Dashboard and Visualization
Key Metrics Dashboards
Create comprehensive dashboards for different stakeholder perspectives.
# LLM Service Operations Dashboard
## Real-Time Metrics
- Current request latency (p50, p95, p99)
- Requests per second
- Error rate by model and endpoint
- Active concurrent requests
## Health Indicators
- Model availability status
- GPU utilization percentages
- Memory pressure levels
- Cache hit rates
## Cost Metrics
- Daily/monthly spend
- Cost per request by model
- Budget utilization percentage
- ROI tracking for different use cases
Related Catalog Entry
For infrastructure and deployment best practices, 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.