Skip to content

feat: Healthcheck for Endpoints - #2

Merged
thushan merged 27 commits into
mainfrom
feature/healthcheck
May 25, 2025
Merged

thushan merged 27 commits into
mainfrom
feature/healthcheck

Conversation

@thushan

@thushan thushan commented May 24, 2025 •

Copy link
Copy Markdown
Owner

Health Check improvements

This PR introduces a heavy modification and implementation of the healthcheck system (precursor to implementing proxy pass-through).

Inspired by Sherpa and lessons learnt from implementing that, this tackles healthchecks a little differently and adds more clarity to the status of the health of endpoints (or ollama nodes).

NOTE:
Notes were originally generated by Github Copilot, then refined (it came out with some strange notes!)

Major Health Check Features Added

Circuit Breaker Pattern

  • Automatic Fault Isolation: Circuit breaker opens after 3 consecutive failures per endpoint
  • Auto-Recovery: Circuits automatically close after 30-second timeout
  • Cascading Failure Prevention: Prevents overwhelming already struggling endpoints
  • Per-Endpoint State: Independent circuit state tracking for each Ollama node

Intelligent Backoff Strategy

  • Exponential Backoff: Failed endpoints get checked less frequently (2x, 4x, 8x, up to 12x intervals)
  • Immediate Recovery: Successful checks reset backoff multiplier to 1x
  • Resource Conservation: Reduces load on unhealthy endpoints while maintaining availability detection

Smart Status Classification

// Network/Connection Errors → StatusOffline
// HTTP 5xx + High Latency → StatusBusy  
// HTTP 2xx + High Latency → StatusBusy
// HTTP 2xx + Normal Latency → StatusHealthy

Advanced Health States

  • StatusHealthy: Ready for full traffic (weight: 1.0)
  • StatusBusy: Responding but slow (weight: 0.3)
  • StatusWarming: Starting up, limited traffic (weight: 0.1)
  • StatusOffline: Unreachable, no traffic (weight: 0.0)
  • StatusUnhealthy: HTTP errors, no traffic (weight: 0.0)

Technical Implementation

Worker Pool Architecture

  • Configurable Workers: Default 10 concurrent health checkers
  • Queue Management: 100-job buffer with overflow protection
  • Batch Processing: Controlled concurrency prevents resource exhaustion

Latency-Based Routing

  • Slow Response Threshold: 10 seconds marks endpoints as "busy"
  • Very Slow Threshold: 30+ seconds for critical performance issues
  • Millisecond Precision: Accurate latency tracking for routing decisions

Pre-computed Health URLs

  • Zero URL Parsing: Health check URLs resolved once during config load
  • Performance Optimisation: Eliminates repeated url.Parse() calls during checks
  • Memory Efficiency: Reuses resolved URL objects across health checks

Monitoring & Observability

Status Transition Tracking

  • Noise Reduction: Only logs status changes, not repeated states
  • Error Batching: Logs every 10th consecutive error or every 5 minutes
  • Atomic Operations: Lock-free status transition detection

Health Check Statistics

{
  "running": true,
  "worker_count": 10,
  "queue_size": 23,
  "queue_cap": 100,
  "queue_usage": 0.23
}

Endpoint Health Summary

{
  "total_endpoints": 4,
  "healthy_endpoints": 2,
  "routable_endpoints": 3,
  "unhealthy_endpoints": 1,
  "endpoints": [...]
}

Performance Improvements

Initial Health Check Optimisation

  • Startup Batching: Groups of 5 endpoints checked concurrently
  • Controlled Parallelism: Prevents goroutine explosion during startup
  • Timeout Management: 30-second initial health check timeout
  • Graceful Degradation: Service starts even if some endpoints are unhealthy

Cleanup & Resource Management

  • Stale Entry Cleanup: 5-minute intervals remove orphaned circuit breaker entries
  • Memory Leak Prevention: Automatic cleanup of removed endpoints
  • Resource Conservation: Efficient memory usage for long-running deployments

Atomic Circuit Breaker

type circuitState struct {
    failures    int64  // atomic counter
    lastFailure int64  // unix nano timestamp
    isOpen      int32  // atomic boolean (0/1)
}

Routing Intelligence

Priority-Based Failover

  • Healthy First: Always prefer healthy endpoints
  • Graceful Degradation: Fall back to busy/warming endpoints if needed
  • Last Resort: Use all endpoints if none are routable

Traffic Weight Distribution

  • Routes traffic based on endpoint health status
  • Automatically reduces load on struggling endpoints
  • Maintains service availability during partial outages

thushan added 27 commits May 24, 2025 11:42
fixes endpoint manager mutex call bug

fix rendering and wierd garbled output

add ports

refine ports
- fix: change StopChecking behaviour, use atomic ops
- add: circuitbreaker for healthchecks
- fix: circuitbreaker
- fix: missing formatting / update formatting
- remove CLI colours for healthcheck and move to list
- enhance circuit breaker logic for failures with network
- add: heap based scheduler, with variable waits
- change variable wait behaviour for blocking
- add new metrics for failures and health checker
- validate configuration
- update healthcheck to remove validation which is now in endpointcoinfig
- use an interface for HttpClient
- missed chagnes to HttpClient
- another miss for HttpClient
- handle degredation of an endpoitn gracefully, how to promote an endpoint that returns?
- update references to styles
- fixup messages
- redo styles
- redo more styles
- fix up list styles
- update main style for errors
- adds new statuses: busy, offline, warming
- now network errors mean offline, 5xx or high latency > busy, 5xx and normal latency -> unhealthy, and 2xx + high latency -> busy
- new backoff technique (needs testing), checks every 5s, first failure interval * 2 and it continues up till 12x. this gives time to recover
- updated theme

fix panic at the disco.../static issues with nodes that are failing aftere healthy

update doucmentation

add traffic weight for balancing

fix doco for balancing

circuit breaker changes for new balancing

fix logging/output to TUI

more TUI messages
- config  hot reloading
- changed config from main to app (chicken & egg problem now, but fixed)
-  fixese for memory leak when endpoints change
bahhh shutdown breaks because of orphan goroutine

more leak fixes

and some more, also change how endpoint updates are retrievd

forgot to delete error counts

adds a cleanup loop

reorganise and cleanup the code abit

tidy work and fix gramar
and batch endpoints to smaller buckets, lots of goroutines in profiler :(
const statuses in tracker

health tracker changes to be lock-free

fix health tracker not removing old entry

alternate approach to getting active endpoints

revert to the old endpoints

atomic ops for circuit_breaker

better way to get active endpoints, maybe not as complicated
broke other tests too

fix cachemu
@thushan
thushan marked this pull request as ready for review May 25, 2025 05:17
@thushan
thushan merged commit 67c4b0c into main May 25, 2025
@thushan
thushan deleted the feature/healthcheck branch May 25, 2025 05:18
thushan added a commit that referenced this pull request May 27, 2025
…ut model bits for now, with basic handling at the root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant