8.3 KiB
8.3 KiB
Subtask: Health Check and Monitoring
Parent Task: Decomp/001 Subtask ID: Decomp/001-12 Dependencies: All previous subtasks
Description
Implement health check endpoints and monitoring for the service. Support readiness/liveness probes, dependency health checks, and metrics collection.
Requirements
- Health check endpoint (/health)
- Readiness check (database, redis connectivity)
- Liveness check (basic service status)
- Metrics endpoint (Prometheus format)
- Dependency health monitoring
Technical Specifications
Health Check Endpoints
# Liveness probe - is the service running?
GET /health/live
Response 200 OK:
{"status": "alive"}
# Readiness probe - is the service ready to serve traffic?
GET /health/ready
Response 200 OK:
{
"status": "ready",
"checks": {
"database": "ok",
"redis": "ok",
"analytics_queue": "ok"
}
}
Response 503 Service Unavailable:
{
"status": "not_ready",
"checks": {
"database": "failed",
"redis": "ok",
"analytics_queue": "ok"
},
"failed_checks": ["database"]
}
# Detailed health with metrics
GET /health
Response 200 OK:
{
"status": "healthy",
"version": "1.0.0",
"uptime_seconds": 3600,
"checks": {
"database": {"status": "ok", "latency_ms": 5},
"redis": {"status": "ok", "latency_ms": 2},
"analytics_queue": {"status": "ok", "queue_size": 123}
},
"metrics": {
"total_urls": 1234567,
"total_clicks": 98765432,
"cache_hit_rate": 0.87,
"active_connections": 42
}
}
Health Check Implementation
from datetime import datetime
from time import time
class HealthChecker:
def __init__(self, db, redis, analytics_queue):
self.db = db
self.redis = redis
self.analytics_queue = analytics_queue
self.start_time = time()
async def check_liveness(self) -> dict:
"""Basic liveness check."""
return {"status": "alive"}
async def check_readiness(self) -> dict:
"""Check if all dependencies are ready."""
checks = {}
failed = []
# Database check
try:
start = time()
await self.db.fetch_one("SELECT 1")
checks["database"] = "ok"
except Exception as e:
checks["database"] = f"failed: {str(e)}"
failed.append("database")
# Redis check
try:
start = time()
await self.redis.ping()
checks["redis"] = "ok"
except Exception as e:
checks["redis"] = f"failed: {str(e)}"
failed.append("redis")
# Analytics queue check
try:
queue_size = await self.analytics_queue.qsize()
checks["analytics_queue"] = "ok"
except Exception as e:
checks["analytics_queue"] = f"failed: {str(e)}"
failed.append("analytics_queue")
if failed:
return {
"status": "not_ready",
"checks": checks,
"failed_checks": failed
}
return {
"status": "ready",
"checks": checks
}
async def check_detailed(self) -> dict:
"""Detailed health check with metrics."""
checks = {}
metrics = {}
# Database health with latency
try:
start = time()
await self.db.fetch_one("SELECT 1")
db_latency = (time() - start) * 1000
# Get some metrics
url_count = await self.db.fetch_one("SELECT COUNT(*) as count FROM urls")
click_count = await self.db.fetch_one("SELECT SUM(access_count) as count FROM urls")
checks["database"] = {"status": "ok", "latency_ms": round(db_latency, 2)}
metrics["total_urls"] = url_count['count']
metrics["total_clicks"] = click_count['count'] or 0
except Exception as e:
checks["database"] = {"status": "failed", "error": str(e)}
# Redis health with latency
try:
start = time()
await self.redis.ping()
redis_latency = (time() - start) * 1000
# Get cache info
info = await self.redis.info('stats')
hit_rate = info.get('keyspace_hits', 0) / max(1, info.get('keyspace_hits', 0) + info.get('keyspace_misses', 0))
checks["redis"] = {"status": "ok", "latency_ms": round(redis_latency, 2)}
metrics["cache_hit_rate"] = round(hit_rate, 3)
except Exception as e:
checks["redis"] = {"status": "failed", "error": str(e)}
# Analytics queue
try:
queue_size = await self.analytics_queue.qsize()
checks["analytics_queue"] = {"status": "ok", "queue_size": queue_size}
except Exception as e:
checks["analytics_queue"] = {"status": "failed", "error": str(e)}
uptime = time() - self.start_time
return {
"status": "healthy" if all(c.get("status") == "ok" for c in checks.values()) else "degraded",
"version": os.getenv("APP_VERSION", "1.0.0"),
"uptime_seconds": round(uptime, 2),
"checks": checks,
"metrics": metrics
}
Prometheus Metrics Endpoint
GET /metrics
Response 200 OK (text/plain):
# HELP url_shortener_urls_total Total number of URLs
# TYPE url_shortener_urls_total gauge
url_shortener_urls_total 1234567
# HELP url_shortener_clicks_total Total number of clicks
# TYPE url_shortener_clicks_total gauge
url_shortener_clicks_total 98765432
# HELP url_shortener_cache_hits Cache hits
# TYPE url_shortener_cache_hits counter
url_shortener_cache_hits 87654321
# HELP url_shortener_cache_misses Cache misses
# TYPE url_shortener_cache_misses counter
url_shortener_cache_misses 12345678
# HELP url_shortener_request_latency_seconds Request latency
# TYPE url_shortener_request_latency_seconds histogram
url_shortener_request_latency_seconds_bucket{le="0.005"} 12345
url_shortener_request_latency_seconds_bucket{le="0.01"} 23456
...
url_shortener_request_latency_seconds_bucket{le="+Inf"} 99999
url_shortener_request_latency_seconds_sum 456.78
url_shortener_request_latency_seconds_count 99999
# HELP url_shortener_rate_limit_exceeded Rate limit exceeded
# TYPE url_shortener_rate_limit_exceeded counter
url_shortener_rate_limit_exceeded 1234
Metrics Implementation
from prometheus_client import Counter, Histogram, Gauge, generate_latest
# Define metrics
url_count = Gauge('url_shortener_urls_total', 'Total number of URLs')
click_count = Gauge('url_shortener_clicks_total', 'Total number of clicks')
cache_hits = Counter('url_shortener_cache_hits', 'Cache hits')
cache_misses = Counter('url_shortener_cache_misses', 'Cache misses')
request_latency = Histogram('url_shortener_request_latency_seconds', 'Request latency')
rate_limit_exceeded = Counter('url_shortener_rate_limit_exceeded', 'Rate limit exceeded')
async def metrics_handler():
"""Prometheus metrics endpoint."""
# Update gauges from database
urls = await db.fetch_one("SELECT COUNT(*) as count FROM urls")
url_count.set(urls['count'])
clicks = await db.fetch_one("SELECT SUM(access_count) as count FROM urls")
click_count.set(clicks['count'] or 0)
return Response(content=generate_latest(), media_type="text/plain")
Acceptance Criteria
- GET /health/live returns 200 with {"status": "alive"}
- GET /health/ready returns 200 when all dependencies OK, 503 otherwise
- GET /health returns detailed status with metrics
- GET /metrics returns Prometheus format metrics
- Health checks have <100ms timeout for each dependency
- Liveness check always succeeds (no external dependencies)
- Readiness check fails fast on dependency issues
Notes
- Kubernetes probes: Use /health/live for liveness, /health/ready for readiness
- Timeout: Each health check should timeout within 100ms
- Circuit breaker: Mark service unhealthy after 3 consecutive failures
- Metrics: Use prometheus_client for standard metrics
Edge Cases
- Database timeout → mark as failed, don't block
- Redis down → continue serving (with degraded performance)
- High queue size → alert but don't fail readiness
- Partial metrics available → return what's available
Monitoring Checklist
- Uptime (should be 99.9%+)
- Response times (p50, p95, p99)
- Error rates (4xx, 5xx)
- Cache hit rate (>80% target)
- Queue sizes
- Database connection pool usage