chain-rdeveloper portal
build

Health Checks

Overview

Health checks provide real-time monitoring of service availability, performance, and operational status across the Chainr platform.

Health Check Types

Liveness Probes

  • Determine if service needs restart

  • Check basic service functionality

  • Quick response time (< 1 second)

Readiness Probes

  • Determine if service can accept traffic

  • Check dependencies (database, external services)

  • Used by load balancers

Startup Probes

  • Check if service has started successfully

  • Allow slow-starting services time to initialize

  • Prevent premature traffic routing

Service Health Endpoints

Authentication Service

@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "service": "auth",
        "version": "1.0.0",
        "timestamp": datetime.utcnow().isoformat()
    }

@app.get("/health/ready")
async def readiness_check(db: Session = Depends(get_db)):
    try:
        # Check database connectivity
        db.execute(text("SELECT 1"))
        return {"status": "ready", "database": "connected"}
    except Exception as e:
        raise HTTPException(status_code=503, detail="Database unavailable")

@app.get("/health/live")
async def liveness_check():
    # Basic liveness check
    return {"status": "alive"}

Core Service Health Checks

@app.get("/health/comprehensive")
async def comprehensive_health(
    db: Session = Depends(get_db),
    redis_client: Redis = Depends(get_redis)
):
    health_status = {
        "status": "healthy",
        "checks": {}
    }

    # Database check
    try:
        db.execute(text("SELECT 1"))
        health_status["checks"]["database"] = "healthy"
    except Exception as e:
        health_status["checks"]["database"] = f"unhealthy: {str(e)}"
        health_status["status"] = "unhealthy"

    # Redis check
    try:
        redis_client.ping()
        health_status["checks"]["redis"] = "healthy"
    except Exception as e:
        health_status["checks"]["redis"] = f"unhealthy: {str(e)}"
        health_status["status"] = "unhealthy"

    # External service checks
    try:
        # Check AI service
      response = requests.get("http://svc-ai:5000/health", timeout=5)
        health_status["checks"]["ai_service"] = "healthy" if response.status_code == 200 else "unhealthy"
    except Exception as e:
        health_status["checks"]["ai_service"] = f"unhealthy: {str(e)}"

    return health_status

Infrastructure Health Checks

Docker Health Checks

# docker-compose.yml
services:
  svc-core:
    build: .
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health/ready"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

Kubernetes Health Checks

apiVersion: v1
kind: Pod
metadata:
  name: chainr-core
spec:
  containers:
    - name: core
      image: chainr/core:latest
      livenessProbe:
        httpGet:
          path: /health/live
          port: 8000
        initialDelaySeconds: 30
        periodSeconds: 10
      readinessProbe:
        httpGet:
          path: /health/ready
          port: 8000
        initialDelaySeconds: 5
        periodSeconds: 5

Monitoring Integration

Prometheus Metrics

from prometheus_client import Gauge, Counter, Histogram
import time

# Health check metrics
health_check_duration = Histogram(
    'health_check_duration_seconds',
    'Time spent processing health checks',
    ['service', 'check_type']
)

health_check_status = Gauge(
    'health_check_status',
    'Health check status (1=healthy, 0=unhealthy)',
    ['service', 'component']
)

@app.get("/health")
async def health_check():
    start_time = time.time()

    # Perform health checks
    db_healthy = check_database()
    redis_healthy = check_redis()

    # Record metrics
    health_check_status.labels(service='core', component='database').set(1 if db_healthy else 0)
    health_check_status.labels(service='core', component='redis').set(1 if redis_healthy else 0)

    duration = time.time() - start_time
    health_check_duration.labels(service='core', check_type='comprehensive').observe(duration)

    status = "healthy" if (db_healthy and redis_healthy) else "unhealthy"
    return {"status": status, "response_time": duration}

Grafana Dashboards

  • Service availability over time

  • Health check response times

  • Dependency status overview

  • Alert status summary

Alerting Rules

Prometheus Alerting

groups:
  - name: chainr_health
    rules:
      - alert: ServiceUnhealthy
        expr: health_check_status{component="database"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Database health check failed"

      - alert: ServiceSlowResponse
        expr: histogram_quantile(0.95, rate(health_check_duration_seconds[5m])) > 5
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Health check response time too slow"

Dependency Health Checks

Database Connectivity

async def check_database() -> bool:
    try:
        async with engine.begin() as conn:
            await conn.execute(text("SELECT 1"))
        return True
    except Exception as e:
        logger.error(f"Database health check failed: {e}")
        return False

External Service Checks

async def check_external_service(url: str, timeout: int = 5) -> bool:
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(url, timeout=aiohttp.ClientTimeout(total=timeout)) as response:
                return response.status == 200
    except Exception as e:
        logger.error(f"External service check failed for {url}: {e}")
        return False

Cache Health

async def check_redis() -> bool:
    try:
        await redis.ping()
        # Check memory usage
        info = await redis.info()
        memory_usage = info['used_memory'] / info['total_system_memory']
        if memory_usage > 0.9:  # 90% memory usage
            logger.warning("Redis memory usage is high")
        return True
    except Exception as e:
        logger.error(f"Redis health check failed: {e}")
        return False

Automated Recovery

Self-Healing Actions

  • Database connection pool refresh

  • Cache clearing on memory pressure

  • Service restart on persistent failures

  • Circuit breaker activation

Maintenance Mode

@app.put("/maintenance")
async def set_maintenance_mode(enabled: bool):
    global MAINTENANCE_MODE
    MAINTENANCE_MODE = enabled

    if enabled:
        # Signal load balancer to stop routing traffic
        # Close existing connections gracefully
        # Prepare for maintenance operations
        pass
    else:
        # Resume normal operations
        # Warm up caches
        # Validate all dependencies
        pass

    return {"maintenance_mode": MAINTENANCE_MODE}

Health Check Best Practices

Response Format

{
  "status": "healthy|unhealthy|degraded",
  "timestamp": "2024-01-01T12:00:00Z",
  "version": "1.0.0",
  "uptime": 3600,
  "checks": {
    "database": {
      "status": "healthy",
      "response_time": 0.023,
      "details": "Connected to PostgreSQL 14.2"
    },
    "redis": {
      "status": "healthy",
      "response_time": 0.005,
      "details": "Cache hit rate: 94%"
    }
  }
}

Performance Guidelines

  • Health checks should complete in < 1 second

  • Avoid expensive operations in health checks

  • Use cached results where appropriate

  • Implement timeouts to prevent hanging

Security Considerations

  • Don't expose sensitive information in health responses

  • Use separate endpoints for internal vs external health checks

  • Implement authentication for health check endpoints if needed

  • Rate limit health check requests