> ## Documentation Index
> Fetch the complete documentation index at: https://concentrate.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Health Check

## Overview

The health check endpoint provides a simple way to verify that the Concentrate AI API is operational. This endpoint does not require authentication and is useful for monitoring, uptime checks, and service health verification.

## Authentication

<Info>
  This endpoint **does not require** authentication. You can call it without an API key.
</Info>

## Request Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.concentrate.ai/v1/responses/health
  ```

  ```python Python theme={null}
  import requests

  response = requests.get("https://api.concentrate.ai/v1/responses/health")

  if response.status_code == 200:
      print("API is healthy")
  else:
      print("API is experiencing issues")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api.concentrate.ai/v1/responses/health");

  if (response.ok) {
    console.log("API is healthy");
  } else {
    console.log("API is experiencing issues");
  }
  ```

  ```go Go theme={null}
  package main

  import (
      "fmt"
      "net/http"
  )

  func main() {
      resp, err := http.Get("https://api.concentrate.ai/v1/responses/health")
      if err != nil {
          fmt.Println("Failed to reach API:", err)
          return
      }
      defer resp.Body.Close()

      if resp.StatusCode == 200 {
          fmt.Println("API is healthy")
      } else {
          fmt.Println("API is experiencing issues")
      }
  }
  ```
</CodeGroup>

## Response

### Success (200 OK)

Empty response body with 200 status code indicates the API is operational.

```bash theme={null}
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 0
```

### Failure (5xx)

If the API is experiencing issues, you may receive a 5xx status code or no response at all.

## Use Cases

### 1. Uptime Monitoring

Use health checks in your monitoring system:

<CodeGroup>
  ```python Uptime Monitor theme={null}
  import requests
  import time
  from datetime import datetime

  def check_api_health():
      try:
          response = requests.get(
              "https://api.concentrate.ai/v1/responses/health",
              timeout=5
          )
          return response.status_code == 200
      except:
          return False

  # Monitor every 60 seconds
  while True:
      is_healthy = check_api_health()
      status = "UP" if is_healthy else "DOWN"
      print(f"[{datetime.now()}] API Status: {status}")

      if not is_healthy:
          # Alert or take action
          send_alert("Concentrate AI API is down!")

      time.sleep(60)
  ```

  ```javascript Health Check with Retry theme={null}
  async function checkHealthWithRetry(maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
      try {
        const response = await fetch(
          "https://api.concentrate.ai/v1/responses/health",
          { signal: AbortSignal.timeout(5000) }
        );

        if (response.ok) {
          return { healthy: true, attempts: i + 1 };
        }
      } catch (error) {
        if (i === maxRetries - 1) {
          return { healthy: false, attempts: maxRetries, error };
        }
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
      }
    }
  }

  // Usage
  const result = await checkHealthWithRetry();
  console.log(result.healthy ? "API is up" : "API is down");
  ```
</CodeGroup>

### 2. Pre-Flight Checks

Verify API availability before making critical requests:

<CodeGroup>
  ```python Pre-Flight Check theme={null}
  def make_critical_request(payload):
      # Check if API is healthy first
      try:
          health = requests.get(
              "https://api.concentrate.ai/v1/responses/health",
              timeout=3
          )

          if health.status_code != 200:
              raise Exception("API is not healthy")

      except Exception as e:
          return {"error": f"API unavailable: {str(e)}"}

      # API is healthy, proceed with main request
      response = requests.post(
          "https://api.concentrate.ai/v1/responses",
          headers={"Authorization": "Bearer YOUR_API_KEY"},
          json=payload
      )

      return response.json()
  ```

  ```typescript TypeScript theme={null}
  async function makeRequestWithHealthCheck(payload: any) {
    // Check API health first
    try {
      const healthCheck = await fetch(
        "https://api.concentrate.ai/v1/responses/health",
        { signal: AbortSignal.timeout(3000) }
      );

      if (!healthCheck.ok) {
        throw new Error("API health check failed");
      }
    } catch (error) {
      console.error("API is not available:", error);
      throw new Error("Service unavailable");
    }

    // Proceed with actual request
    const response = await fetch(
      "https://api.concentrate.ai/v1/responses",
      {
        method: "POST",
        headers: {
          "Authorization": "Bearer YOUR_API_KEY",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
      }
    );

    return response.json();
  }
  ```
</CodeGroup>

### 3. Load Balancer Health Checks

Configure your load balancer to use this endpoint:

```yaml AWS ALB Target Group theme={null}
HealthCheckEnabled: true
HealthCheckPath: "/health"
HealthCheckProtocol: "HTTPS"
HealthCheckIntervalSeconds: 30
HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 2
UnhealthyThresholdCount: 3
Matcher:
  HttpCode: "200"
```

```nginx Nginx Configuration theme={null}
upstream concentrate_api {
    server api.concentrate.ai:443;

    # Health check configuration
    check interval=3000 rise=2 fall=3 timeout=1000 type=http;
    check_http_send "GET /v1/responses/health HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx;
}
```

### 4. Circuit Breaker Integration

Use health checks to control circuit breaker state:

```python theme={null}
from datetime import datetime, timedelta

class HealthAwareCircuitBreaker:
    def __init__(self, failure_threshold=3, recovery_timeout=60):
        self.failure_threshold = failure_threshold
        self.recovery_timeout = recovery_timeout
        self.failures = 0
        self.state = "closed"  # closed, open, half-open
        self.last_failure = None

    def check_health(self):
        try:
            response = requests.get(
                "https://api.concentrate.ai/v1/responses/health",
                timeout=2
            )
            return response.status_code == 200
        except:
            return False

    def is_open(self):
        if self.state == "closed":
            return False

        if self.state == "open":
            # Try to recover
            if datetime.now() - self.last_failure > timedelta(seconds=self.recovery_timeout):
                if self.check_health():
                    self.state = "closed"
                    self.failures = 0
                    return False

        return True

    def record_failure(self):
        self.failures += 1
        self.last_failure = datetime.now()
        if self.failures >= self.failure_threshold:
            self.state = "open"

    def record_success(self):
        self.failures = 0
        self.state = "closed"
```

## Monitoring Best Practices

<AccordionGroup>
  <Accordion title="Set appropriate timeouts" icon="clock">
    Always use short timeouts for health checks to avoid hanging:

    ```python theme={null}
    # Good: 3-5 second timeout
    requests.get(url, timeout=5)

    # Bad: No timeout or very long timeout
    requests.get(url)  # May hang indefinitely
    requests.get(url, timeout=30)  # Too long for health check
    ```
  </Accordion>

  <Accordion title="Use exponential backoff" icon="arrows-rotate">
    Don't hammer the health endpoint on failures:

    ```javascript theme={null}
    async function checkWithBackoff() {
      const delays = [1000, 2000, 4000, 8000]; // ms

      for (let i = 0; i < delays.length; i++) {
        const isHealthy = await checkHealth();
        if (isHealthy) return true;

        await new Promise(resolve => setTimeout(resolve, delays[i]));
      }

      return false;
    }
    ```
  </Accordion>

  <Accordion title="Monitor from multiple locations" icon="globe">
    Check from different regions to detect regional outages:

    ```python theme={null}
    regions = [
        "us-east-1",
        "us-west-2",
        "eu-west-1",
        "ap-southeast-1"
    ]

    results = {}
    for region in regions:
        # Run health check from each region
        results[region] = check_health_from_region(region)

    # Alert if multiple regions fail
    failures = sum(1 for v in results.values() if not v)
    if failures >= 2:
        send_alert("Multiple regions reporting API down")
    ```
  </Accordion>

  <Accordion title="Track response times" icon="gauge">
    Monitor latency to detect degradation:

    ```javascript theme={null}
    async function checkHealthWithMetrics() {
      const start = Date.now();

      try {
        const response = await fetch(
          "https://api.concentrate.ai/v1/responses/health"
        );

        const latency = Date.now() - start;
        const healthy = response.ok;

        // Log metrics
        console.log({
          timestamp: new Date(),
          healthy,
          latency,
          status: response.status
        });

        // Alert on slow responses
        if (latency > 5000 && healthy) {
          console.warn("API is slow but healthy");
        }

        return healthy;
      } catch (error) {
        console.error("Health check failed:", error);
        return false;
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Health Check Metrics

Track these metrics for effective monitoring:

| Metric                   | Description                   | Alert Threshold |
| ------------------------ | ----------------------------- | --------------- |
| **Availability**         | % of successful health checks | \< 99.9%        |
| **Response Time**        | Average latency               | > 1000ms        |
| **Error Rate**           | % of failed checks            | > 1%            |
| **Consecutive Failures** | Failures in a row             | >= 3            |

## Status Page

For real-time API status and incident updates, visit:

**[status.concentrate.ai](https://statuspage.incident.io/concentrate-ai)**

<Tip>
  Subscribe to status page updates to receive notifications about planned maintenance and incidents.
</Tip>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Health check always fails" icon="circle-xmark">
    **Possible causes:**

    * Network connectivity issues
    * DNS resolution problems
    * Firewall blocking requests
    * SSL/TLS certificate issues

    **Debug steps:**

    ```bash theme={null}
    # Test DNS resolution
    nslookup api.concentrate.ai

    # Test connectivity
    ping api.concentrate.ai

    # Test HTTPS
    curl -v https://api.concentrate.ai/v1/responses/health

    # Check SSL certificate
    openssl s_client -connect api.concentrate.ai:443
    ```
  </Accordion>

  <Accordion title="Intermittent failures" icon="triangle-exclamation">
    **Possible causes:**

    * Network instability
    * Timeout too short
    * Load balancer issues
    * API experiencing high load

    **Solutions:**

    * Increase timeout to 5-10 seconds
    * Implement retry logic with backoff
    * Check from multiple locations
    * Review status page for incidents
  </Accordion>

  <Accordion title="Slow response times" icon="hourglass">
    **Possible causes:**

    * API under heavy load
    * Network latency
    * Regional routing issues

    **Solutions:**

    * Monitor response time trends
    * Check if issue is regional
    * Consider using a closer endpoint
    * Review status page
  </Accordion>
</AccordionGroup>

## Example: Complete Health Monitoring System

<CodeGroup>
  ```python Complete Monitor theme={null}
  import requests
  import time
  from datetime import datetime
  from collections import deque

  class APIHealthMonitor:
      def __init__(self, check_interval=60, history_size=100):
          self.check_interval = check_interval
          self.history = deque(maxlen=history_size)
          self.consecutive_failures = 0

      def check_health(self):
          start = time.time()
          try:
              response = requests.get(
                  "https://api.concentrate.ai/v1/responses/health",
                  timeout=5
              )
              latency = (time.time() - start) * 1000  # ms
              success = response.status_code == 200

              return {
                  "timestamp": datetime.now(),
                  "success": success,
                  "latency": latency,
                  "status_code": response.status_code
              }
          except Exception as e:
              return {
                  "timestamp": datetime.now(),
                  "success": False,
                  "latency": None,
                  "error": str(e)
              }

      def get_availability(self):
          if not self.history:
              return 0

          successful = sum(1 for check in self.history if check["success"])
          return (successful / len(self.history)) * 100

      def get_avg_latency(self):
          latencies = [c["latency"] for c in self.history
                      if c.get("latency") is not None]
          return sum(latencies) / len(latencies) if latencies else 0

      def monitor(self):
          while True:
              result = self.check_health()
              self.history.append(result)

              if result["success"]:
                  self.consecutive_failures = 0
                  status = "✓ UP"
              else:
                  self.consecutive_failures += 1
                  status = "✗ DOWN"

              print(f"[{result['timestamp']}] {status}")
              print(f"  Availability: {self.get_availability():.2f}%")
              print(f"  Avg Latency: {self.get_avg_latency():.0f}ms")

              # Alert on consecutive failures
              if self.consecutive_failures >= 3:
                  self.send_alert("API has been down for 3 consecutive checks")

              time.sleep(self.check_interval)

      def send_alert(self, message):
          print(f"🚨 ALERT: {message}")
          # Implement actual alerting (email, Slack, PagerDuty, etc.)

  # Usage
  monitor = APIHealthMonitor(check_interval=60)
  monitor.monitor()
  ```

  ```typescript TypeScript System theme={null}
  interface HealthCheckResult {
    timestamp: Date;
    success: boolean;
    latency?: number;
    statusCode?: number;
    error?: string;
  }

  class APIHealthMonitor {
    private history: HealthCheckResult[] = [];
    private consecutiveFailures = 0;

    constructor(
      private checkInterval = 60000,
      private historySize = 100
    ) {}

    async checkHealth(): Promise<HealthCheckResult> {
      const start = Date.now();

      try {
        const response = await fetch(
          "https://api.concentrate.ai/v1/responses/health",
          { signal: AbortSignal.timeout(5000) }
        );

        const latency = Date.now() - start;

        return {
          timestamp: new Date(),
          success: response.ok,
          latency,
          statusCode: response.status
        };
      } catch (error) {
        return {
          timestamp: new Date(),
          success: false,
          error: error instanceof Error ? error.message : String(error)
        };
      }
    }

    getAvailability(): number {
      if (this.history.length === 0) return 0;

      const successful = this.history.filter(h => h.success).length;
      return (successful / this.history.length) * 100;
    }

    getAverageLatency(): number {
      const latencies = this.history
        .map(h => h.latency)
        .filter((l): l is number => l !== undefined);

      if (latencies.length === 0) return 0;

      return latencies.reduce((a, b) => a + b, 0) / latencies.length;
    }

    async monitor() {
      while (true) {
        const result = await this.checkHealth();

        this.history.push(result);
        if (this.history.length > this.historySize) {
          this.history.shift();
        }

        if (result.success) {
          this.consecutiveFailures = 0;
          console.log(`✓ UP - Latency: ${result.latency}ms`);
        } else {
          this.consecutiveFailures++;
          console.log(`✗ DOWN - ${result.error}`);
        }

        console.log(`Availability: ${this.getAvailability().toFixed(2)}%`);
        console.log(`Avg Latency: ${this.getAverageLatency().toFixed(0)}ms\n`);

        if (this.consecutiveFailures >= 3) {
          this.sendAlert("API down for 3 consecutive checks");
        }

        await new Promise(resolve =>
          setTimeout(resolve, this.checkInterval)
        );
      }
    }

    private sendAlert(message: string) {
      console.error(`🚨 ALERT: ${message}`);
      // Implement alerting
    }
  }

  // Usage
  const monitor = new APIHealthMonitor(60000);
  monitor.monitor();
  ```
</CodeGroup>

## Related Documentation

<CardGroup cols={2}>
  <Card title="Error Handling" icon="triangle-exclamation" href="/docs/api-reference/endpoint/errors">
    Handle API errors
  </Card>

  <Card title="Create Response" icon="message" href="/docs/api-reference/endpoint/create-response">
    Main API endpoint
  </Card>
</CardGroup>
