Health Check

O endpoint de health check permite verificar se a API está operacional e obter informações sobre o status do serviço.

Endpoint

GET /health

[!NOTE]
Este endpoint NÃO requer autenticação — ideal para monitoramento externo.

Uso Básico

curl -X GET https://api.toktus.com/health

Resposta (HTTP 200):

{
  "status": "ok",
  "timestamp": "2026-02-17T14:35:22.183Z",
  "uptime": 86420,
  "version": "1.0.0",
  "database": "connected"
}

Campos da Resposta

CampoTipoDescrição
statusstringStatus do serviço: "ok" (operacional) ou "degraded" (degradado)
timestampstringData/hora da verificação (ISO 8601)
uptimenumberTempo de atividade em segundos
versionstringVersão atual da API
databasestringStatus da conexão com o banco: "connected" ou "disconnected"

Quando Usar

Monitoramento de Disponibilidade

Configure seu sistema de monitoramento (Datadog, New Relic, UptimeRobot, etc.) para fazer polling do endpoint:

  • URL: https://api.toktus.com/health
  • Intervalo: 5 minutos
  • Método: GET
  • Status esperado: HTTP 200
  • Palavra-chave esperada: "ok"

Health Check de Load Balancer

NGINX

    upstream toktus_api {
        server api1.rootgateway.com:3001;
        server api2.rootgateway.com:3001;

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

## AWS Target Group

```json
    {
      "HealthCheckEnabled": true,
      "HealthCheckPath": "/health",
      "HealthCheckProtocol": "HTTP",
      "HealthCheckIntervalSeconds": 30,
      "HealthCheckTimeoutSeconds": 5,
      "HealthyThresholdCount": 2,
      "UnhealthyThresholdCount": 3,
      "Matcher": {
        "HttpCode": "200"
      }
    }
    ```

### Verificação Pre-Deploy

Valide que a API está operacional antes de direcionar tráfego:

```bash
#!/bin/bash
MAX_RETRIES=5
RETRY_COUNT=0

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://api.toktus.com/health)

    if [ $STATUS -eq 200 ]; then
        echo "API is healthy"
        exit 0
    fi

    echo "Health check failed (attempt $((RETRY_COUNT+1))/$MAX_RETRIES)"
    RETRY_COUNT=$((RETRY_COUNT+1))
    sleep 5
done

echo "API is not healthy after $MAX_RETRIES attempts"
exit 1

CI/CD Pipeline (GitHub Actions)

name: Deploy API

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to production
        run: ./deploy.sh

      - name: Wait for deployment
        run: sleep 30

      - name: Health check
        run: |
          STATUS=$(curl -s -o /dev/null -w "%{http_code}" https://api.toktus.com/health)
          if [ $STATUS -ne 200 ]; then
            echo "Health check failed"
            exit 1
          fi
          echo "Deployment successful"

Monitoramento Avançado

Script Python com Alertas

import requests
import time
from datetime import datetime

def check_health():
    try:
        response = requests.get(
            'https://api.toktus.com/health',
            timeout=5
        )

        if response.status_code == 200:
            data = response.json()
            print(f"[OK] [{datetime.now()}] API OK - Uptime: {data['uptime']}s")
            return True
        else:
            print(f"[WARN] [{datetime.now()}] API returned status {response.status_code}")
            return False

    except requests.exceptions.Timeout:
        print(f"[ERROR] [{datetime.now()}] API timeout")
        return False
    except Exception as e:
        print(f"[ERROR] [{datetime.now()}] Error: {str(e)}")
        return False

# Executa a cada 5 minutos
while True:
    check_health()
    time.sleep(300)

Kubernetes Probes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: seu-app
spec:
  template:
    spec:
      containers:
      - name: app
        image: seu-app:latest
        livenessProbe:
          httpGet:
            path: /health
            port: 3001
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /health
            port: 3001
          initialDelaySeconds: 10
          periodSeconds: 5
          timeoutSeconds: 3
          failureThreshold: 2

Docker Compose

version: '3.8'
services:
  api:
    image: rootgateway/api:latest
    ports:
      - "3001:3001"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3001/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

Alertas Recomendados

CondiçãoSeveridadeAção
HTTP 500 ou timeoutCríticoAcionar engenheiro de plantão
status: "degraded" ou indisponibilidadeAvisoNotificar equipe
Latência > 5 segundosAvisoInvestigar performance
Uptime resetado (servidor reiniciou)InformativoRegistrar para análise

SLA Esperado

MétricaValor
Disponibilidade99.9%
Latência P50< 100ms
Latência P95< 500ms
Latência P99< 1000ms