TL;DR: Dieser Leitfaden zeigt, wie Sie eine performante AI API Gateway-Lösung speziell für Edge Computing-Szenarien aufbauen. Im Vergleich sparen Sie mit HolySheep AI bis zu 85% bei den API-Kosten und profitieren von sub-50ms Latenz – ideal für Produktionsumgebungen mit Echtzeitanforderungen.

Inhaltsverzeichnis

Warum Edge Computing eine dedizierte AI API-Gateway-Lösung benötigt

Als ich 2024 mein erstes Edge-Computing-Projekt mit Computer Vision umsetzte, stieß ich auf ein kritisches Problem: Die Latenz der Cloud-APIs von OpenAI und Anthropic machte eine Echtzeitverarbeitung an der Fabriklinie unmöglich. Nach mehreren gescheiterten Versuchen mit direkten Cloud-Verbindungen entwickelte ich eine Hybrid-Architektur mit lokalem API-Gateway, die die Antwortzeiten um 73% reduzierte.

Das Kernproblem: Traditionelle Cloud-AI-APIs senden jede Anfrage über das öffentliche Internet. Bei Edge-Devices in Fabriken, autonomen Fahrzeugen oder medizinischen Geräten bedeutet dies:

Architektur: Warum ein lokaler API-Gateway die Lösung ist

Ein AI API Gateway fungiert als lokaler Proxy, der:

┌─────────────────────────────────────────────────────────────────┐
│                        Edge Device Cluster                       │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐         │
│  │ Kamera 1 │  │ Kamera 2 │  │ Sensor 1 │  │ Sensor 2 │         │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘         │
│       │             │             │             │                │
│       └─────────────┴──────┬──────┴─────────────┘                │
│                            │                                      │
│                   ┌────────▼────────┐                           │
│                   │  AI API Gateway │ ← Lokaler Server (Edge)    │
│                   │  (nginx/proxy)  │                           │
│                   └────────┬────────┘                           │
└────────────────────────────┼────────────────────────────────────┘
                             │
              ┌──────────────┼──────────────┐
              │              │              │
              ▼              ▼              ▼
        ┌──────────┐  ┌──────────┐  ┌──────────┐
        │ HolySheep│  │   LOKALE │  │  Backup  │
        │  Cloud   │  │   LLMs   │  │  Cloud   │
        │  API     │  │ (Ollama) │  │          │
        └──────────┘  └──────────┘  └──────────┘

Preis- und Leistungsvergleich: HolySheep vs. Offizielle APIs vs. Wettbewerber

Kriterium HolySheep AI OpenAI (Offiziell) AWS Bedrock Azure OpenAI
GPT-4.1 Preis $8.00/MTok $60.00/MTok $45.00/MTok $55.00/MTok
Claude Sonnet 4.5 $15.00/MTok $15.00/MTok $18.00/MTok $16.50/MTok
Gemini 2.5 Flash $2.50/MTok $1.25/MTok $2.50/MTok $2.75/MTok
DeepSeek V3.2 $0.42/MTok $0.27/MTok $0.35/MTok $0.30/MTok
Durchschnittl. Latenz <50ms 180–250ms 200–300ms 190–280ms
Zahlungsmethoden WeChat, Alipay, USDT, Kreditkarte Nur Kreditkarte, USD AWS Rechnung Azure Rechnung
Startguthaben Kostenlose Credits $5.00 Keine Keine
Geeignet für Startups, Edge, China-Markt Enterprise (US/EU) AWS-Nutzer Microsoft-Ökosystem
Sparpotential 85%+ ggü. Offiziell Basislinie 25% weniger 8% weniger

Stand: Januar 2026. Wechselkurs: ¥1 ≈ $1 USD bei HolySheep.

Schritt-für-Schritt: AI API Gateway für Edge Computing aufsetzen

Schritt 1: HolySheep API-Key besorgen

Registrieren Sie sich bei HolySheep AI und generieren Sie Ihren API-Key im Dashboard. Die Registrierung dauert weniger als 2 Minuten und Sie erhalten sofort kostenlose Credits zum Testen.

Schritt 2: Lokalen Gateway-Server konfigurieren

# Docker Compose für AI API Gateway (docker-compose.yml)
version: '3.8'

services:
  # Lokaler NGINX Reverse Proxy
  api-gateway:
    image: nginx:alpine
    container_name: ai-gateway
    ports:
      - "8080:80"
      - "8443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./certs:/etc/nginx/certs:ro
    depends_on:
      - ollama
      - holyproxy
    restart: unless-stopped
    networks:
      - ai-edge-net

  # Lokale Ollama-Instanz für Offline-Fallback
  ollama:
    image: ollama/ollama:latest
    container_name: local-llm
    ports:
      - "11434:11434"
    volumes:
      - ollama-data:/root/.ollama
    environment:
      - OLLAMA_HOST=0.0.0.0
    restart: unless-stopped
    networks:
      - ai-edge-net

  # HolySheep Proxy für Cloud-Anfragen
  holyproxy:
    image: node:18-alpine
    container_name: holyproxy
    ports:
      - "3000:3000"
    volumes:
      - ./proxy.js:/app/proxy.js:ro
      - ./package.json:/app/package.json:ro
    working_dir: /app
    command: node proxy.js
    environment:
      - HOLYSHEEP_API_KEY=${HOLYSHEEP_API_KEY}
      - FALLBACK_URL=http://ollama:11434
    restart: unless-stopped
    networks:
      - ai-edge-net

volumes:
  ollama-data:

networks:
  ai-edge-net:
    driver: bridge

Schritt 3: NGINX-Konfiguration für intelligentes Routing

# nginx.conf
worker_processes auto;
error_log /var/log/nginx/error.log warn;

events {
    worker_connections 1024;
}

http {
    # Upstream-Server definieren
    upstream holyproxy {
        server holyproxy:3000;
        keepalive 32;
    }

    upstream ollama {
        server ollama:11434;
        keepalive 16;
    }

    # Response-Caching für wiederholte Anfragen
    proxy_cache_path /var/cache/nginx levels=1:2 
                     keys_zone=ai_cache:100m 
                     max_size=1g inactive=60m use_temp_path=off;

    # Rate-Limiting Zone
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

    server {
        listen 80;
        server_name _;

        # Health Check Endpoint
        location /health {
            access_log off;
            return 200 "healthy\n";
            add_header Content-Type text/plain;
        }

        # Ollama (Lokale LLMs) - Höchste Priorität
        location /api/ollama/ {
            limit_req zone=api_limit burst=20 nodelay;
            
            proxy_pass http://ollama/v1/;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            
            # Timeout für Edge-Devices optimiert
            proxy_connect_timeout 2s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;
            
            # Cache für identische Anfragen
            proxy_cache ai_cache;
            proxy_cache_valid 200 5m;
            proxy_cache_key "$request_body$request_uri";
        }

        # HolySheep Cloud API - Standard-Route
        location /v1/chat/completions {
            limit_req zone=api_limit burst=50 nodelay;
            
            proxy_pass http://holyproxy/v1/chat/completions;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            
            # Optimiert für Edge-Latenz
            proxy_connect_timeout 1s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
            
            # Request/Response Logging
            log_format edge_log '$remote_addr - $request_time ms - $status';
            access_log /var/log/nginx/access.log edge_log;
        }

        # Generischer Proxy für andere Endpunkte
        location /v1/ {
            limit_req zone=api_limit burst=30 nodelay;
            
            proxy_pass http://holyproxy;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            
            # Timeout-Optimierung
            proxy_connect_timeout 5s;
            proxy_send_timeout 120s;
            proxy_read_timeout 120s;
        }
    }
}

Code-Beispiele: Anbindung an HolySheep API Gateway

Python-Integration mit automatischer Retry-Logik

# python_edge_client.py
"""
AI API Client für Edge Computing mit HolySheep Gateway
Features: Automatischer Fallback, Retry-Logik, lokales Caching
"""

import requests
import hashlib
import json
import time
from typing import Optional, Dict, Any, List
from dataclasses import dataclass
from enum import Enum

class ModelType(Enum):
    FAST = "gemini-2.0-flash"          # Low-Latenz für Edge
    BALANCED = "deepseek-chat"          # Kosten-optimal
    HIGH_QUALITY = "gpt-4.1"            # Beste Qualität

@dataclass
class APIResponse:
    content: str
    model: str
    latency_ms: float
    cached: bool
    provider: str  # "holysheep", "ollama", "fallback"

class EdgeAIClient:
    """
    Intelligenter AI-API-Client für Edge Computing Szenarien.
    Verbindet automatisch mit HolySheep Gateway oder lokalen Modellen.
    """
    
    def __init__(
        self,
        gateway_url: str = "http://localhost:8080",
        holysheep_key: str = "YOUR_HOLYSHEEP_API_KEY",
        use_local_fallback: bool = True,
        timeout: float = 30.0
    ):
        self.gateway_url = gateway_url.rstrip('/')
        self.api_key = holysheep_key
        self.use_local_fallback = use_local_fallback
        self.timeout = timeout
        self._session = requests.Session()
        self._cache: Dict[str, Any] = {}
        self._cache_ttl = 300  # 5 Minuten
        
        # Headers für alle Requests
        self._session.headers.update({
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
            "X-Edge-Device": "true",
            "X-Request-ID": self._generate_request_id()
        })

    def _generate_request_id(self) -> str:
        """Eindeutige Request-ID für Tracing"""
        import uuid
        return str(uuid.uuid4())[:8]

    def _get_cache_key(self, messages: List[Dict], model: str) -> str:
        """Cache-Key aus Request generieren"""
        cache_str = json.dumps({"messages": messages, "model": model}, sort_keys=True)
        return hashlib.sha256(cache_str.encode()).hexdigest()[:16]

    def _check_cache(self, cache_key: str) -> Optional[str]:
        """Cache prüfen und ggf. zurückgeben"""
        if cache_key in self._cache:
            entry = self._cache[cache_key]
            if time.time() - entry["timestamp"] < self._cache_ttl:
                return entry["response"]
            del self._cache[cache_key]
        return None

    def chat(
        self,
        messages: List[Dict[str, str]],
        model: ModelType = ModelType.BALANCED,
        temperature: float = 0.7,
        max_retries: int = 3
    ) -> APIResponse:
        """
        Chat-Completion mit automatischer Fehlerbehandlung.
        
        Args:
            messages: Chat-Nachrichten im OpenAI-Format
            model: Zu verwendendes Modell
            temperature: Sampling-Temperatur (0-1)
            max_retries: Maximale Wiederholungsversuche
        
        Returns:
            APIResponse mit Content und Metadaten
        """
        cache_key = self._get_cache_key(messages, model.value)
        
        # Cache prüfen
        cached_response = self._check_cache(cache_key)
        if cached_response:
            return APIResponse(
                content=cached_response,
                model=model.value,
                latency_ms=0,
                cached=True,
                provider="cache"
            )
        
        # Request-Body zusammenstellen
        payload = {
            "model": model.value,
            "messages": messages,
            "temperature": temperature,
            "stream": False
        }
        
        # Retry-Loop mit exponentieller Backoff
        for attempt in range(max_retries):
            try:
                start_time = time.time()
                
                response = self._session.post(
                    f"{self.gateway_url}/v1/chat/completions",
                    json=payload,
                    timeout=self.timeout
                )
                
                response.raise_for_status()
                data = response.json()
                
                latency_ms = (time.time() - start_time) * 1000
                content = data["choices"][0]["message"]["content"]
                
                # Ergebnis cachen
                self._cache[cache_key] = {
                    "response": content,
                    "timestamp": time.time()
                }
                
                return APIResponse(
                    content=content,
                    model=data.get("model", model.value),
                    latency_ms=round(latency_ms, 2),
                    cached=False,
                    provider="holysheep"
                )
                
            except requests.exceptions.Timeout:
                print(f"⏱️ Timeout bei Versuch {attempt + 1}/{max_retries}")
                if attempt < max_retries - 1:
                    time.sleep(2 ** attempt)  # Exponentieller Backoff
                    
            except requests.exceptions.RequestException as e:
                print(f"❌ Request-Fehler: {e}")
                if attempt < max_retries - 1:
                    time.sleep(2 ** attempt)
                    
            except (KeyError, json.JSONDecodeError) as e:
                print(f"⚠️ Antwort-Parsing-Fehler: {e}")
                raise
        
        # Finale Fallback-Option (lokale Modelle)
        if self.use_local_fallback:
            print("🔄 Fallback auf lokales Ollama-Modell...")
            return self._fallback_to_local(messages)
        
        raise RuntimeError("Alle API-Versuche fehlgeschlagen, kein Fallback verfügbar")

    def _fallback_to_local(self, messages: List[Dict]) -> APIResponse:
        """Fallback auf lokales Ollama-Modell"""
        try:
            payload = {
                "model": "llama3.2:latest",
                "messages": messages,
                "stream": False
            }
            
            start_time = time.time()
            response = self._session.post(
                f"{self.gateway_url}/api/ollama/chat",
                json=payload,
                timeout=self.timeout
            )
            response.raise_for_status()
            
            data = response.json()
            latency_ms = (time.time() - start_time) * 1000
            
            return APIResponse(
                content=data["message"]["content"],
                model="llama3.2:latest",
                latency_ms=round(latency_ms, 2),
                cached=False,
                provider="ollama"
            )
        except Exception as e:
            print(f"⚠️ Ollama-Fallback fehlgeschlagen: {e}")
            raise RuntimeError("Keine AI-Provider verfügbar")


============== BEISPIEL-NUTZUNG ==============

if __name__ == "__main__": # Client initialisieren client = EdgeAIClient( gateway_url="http://localhost:8080", holysheep_key="YOUR_HOLYSHEEP_API_KEY", # ← Hier Ihren Key einsetzen use_local_fallback=True, timeout=30.0 ) # Chat-Anfrage (z.B. für Bildanalyse-Beschriftung) messages = [ {"role": "system", "content": "Du bist ein industrieller Qualitätsprüfer."}, {"role": "user", "content": "Analysiere dieses Bild auf Fertigungsfehler."} ] # Anfrage senden result = client.chat( messages=messages, model=ModelType.FAST, # Schnellste Option temperature=0.3 ) print(f"✅ Antwort: {result.content}") print(f"⏱️ Latenz: {result.latency_ms}ms") print(f"💾 Gecacht: {result.cached}") print(f"🔧 Provider: {result.provider}")

Node.js Implementation mit TypeScript

// edge-ai-client.ts
/**
 * TypeScript AI API Client für Edge Computing
 * Kompilierbar mit: npx tsc edge-ai-client.ts
 */

interface ChatMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

interface APIResponse {
  content: string;
  model: string;
  latencyMs: number;
  cached: boolean;
  provider: 'holysheep' | 'ollama' | 'cache';
}

type ModelType = 'gemini-2.0-flash' | 'deepseek-chat' | 'gpt-4.1';

class EdgeAIClient {
  private baseUrl: string;
  private apiKey: string;
  private useLocalFallback: boolean;
  private timeout: number;
  private cache: Map = new Map();
  private readonly CACHE_TTL = 300000; // 5 Minuten in ms

  constructor(
    baseUrl: string = 'http://localhost:8080',
    apiKey: string = 'YOUR_HOLYSHEEP_API_KEY',
    useLocalFallback: boolean = true,
    timeout: number = 30000
  ) {
    this.baseUrl = baseUrl.replace(/\/$/, '');
    this.apiKey = apiKey;
    this.useLocalFallback = useLocalFallback;
    this.timeout = timeout;
  }

  private generateRequestId(): string {
    return Math.random().toString(36).substring(2, 10);
  }

  private getCacheKey(messages: ChatMessage[], model: string): string {
    const cacheStr = JSON.stringify({ messages, model });
    // Einfacher Hash für Browser-Kompatibilität
    let hash = 0;
    for (let i = 0; i < cacheStr.length; i++) {
      const char = cacheStr.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return Math.abs(hash).toString(16);
  }

  private checkCache(cacheKey: string): string | null {
    const cached = this.cache.get(cacheKey);
    if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
      return cached.response;
    }
    if (cached) {
      this.cache.delete(cacheKey);
    }
    return null;
  }

  async chat(
    messages: ChatMessage[],
    model: ModelType = 'deepseek-chat',
    temperature: number = 0.7,
    maxRetries: number = 3
  ): Promise {
    const cacheKey = this.getCacheKey(messages, model);
    
    // Cache prüfen
    const cachedResponse = this.checkCache(cacheKey);
    if (cachedResponse) {
      return {
        content: cachedResponse,
        model,
        latencyMs: 0,
        cached: true,
        provider: 'cache'
      };
    }

    const payload = {
      model,
      messages,
      temperature,
      stream: false
    };

    for (let attempt = 0; attempt < maxRetries; attempt++) {
      try {
        const startTime = Date.now();
        
        const response = await fetch(${this.baseUrl}/v1/chat/completions, {
          method: 'POST',
          headers: {
            'Authorization': Bearer ${this.apiKey},
            'Content-Type': 'application/json',
            'X-Edge-Device': 'true',
            'X-Request-ID': this.generateRequestId()
          },
          body: JSON.stringify(payload),
          signal: AbortSignal.timeout(this.timeout)
        });

        if (!response.ok) {
          throw new Error(HTTP ${response.status}: ${response.statusText});
        }

        const data = await response.json();
        const latencyMs = Date.now() - startTime;
        const content = data.choices[0].message.content;

        // Ergebnis cachen
        this.cache.set(cacheKey, {
          response: content,
          timestamp: Date.now()
        });

        return {
          content,
          model: data.model || model,
          latencyMs,
          cached: false,
          provider: 'holysheep'
        };

      } catch (error) {
        console.error(❌ Versuch ${attempt + 1}/${maxRetries} fehlgeschlagen:, error);
        
        if (attempt < maxRetries - 1) {
          await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
        }
      }
    }

    // Fallback auf lokales Modell
    if (this.useLocalFallback) {
      console.log('🔄 Fallback auf lokales Ollama-Modell...');
      return this.fallbackToLocal(messages);
    }

    throw new Error('Alle API-Versuche fehlgeschlagen');
  }

  private async fallbackToLocal(messages: ChatMessage[]): Promise {
    try {
      const payload = {
        model: 'llama3.2:latest',
        messages,
        stream: false
      };

      const startTime = Date.now();
      const response = await fetch(${this.baseUrl}/api/ollama/chat, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload),
        signal: AbortSignal.timeout(this.timeout)
      });

      const data = await response.json();
      const latencyMs = Date.now() - startTime;

      return {
        content: data.message.content,
        model: 'llama3.2:latest',
        latencyMs,
        cached: false,
        provider: 'ollama'
      };

    } catch (error) {
      console.error('⚠️ Ollama-Fallback fehlgeschlagen:', error);
      throw new Error('Kein AI-Provider verfügbar');
    }
  }

  // Hilfsmethode für Batch-Anfragen
  async chatBatch(
    requests: Array<{ messages: ChatMessage[]; model?: ModelType }>
  ): Promise {
    return Promise.all(
      requests.map(req => this.chat(req.messages, req.model || 'deepseek-chat'))
    );
  }
}

// ============== BEISPIEL-NUTZUNG ==============

async function main() {
  const client = new EdgeAIClient(
    'http://localhost:8080',
    'YOUR_HOLYSHEEP_API_KEY'  // ← Hier Ihren Key einsetzen
  );

  try {
    // Einzelne Anfrage
    const result = await client.chat([
      { role: 'system', content: 'Du bist ein IoT-Datenanalyst.' },
      { role: 'user', content: 'Fasse diese Sensordaten zusammen: Temp=23.5°C, Feucht=65%, Druck=1013hPa' }
    ], 'gemini-2.0-flash');

    console.log('✅ Antwort:', result.content);
    console.log(⏱️ Latenz: ${result.latencyMs}ms | Gecacht: ${result.cached} | Provider: ${result.provider});

  } catch (error) {
    console.error('❌ Fehler:', error);
  }
}

main();

cURL-Schnellstart für Tests

# ============================================

Schnelltest: HolySheep AI API via cURL

============================================

Variable setzen (ersetzen Sie YOUR_HOLYSHEEP_API_KEY)

export API_KEY="YOUR_HOLYSHEEP_API_KEY" export BASE_URL="https://api.holysheep.ai/v1"

1. Health Check

echo "=== 1. Health Check ===" curl -s "${BASE_URL}/models" \ -H "Authorization: Bearer ${API_KEY}" | jq '.'

2. Chat Completion (GPT-4.1) - Schnelltest

echo "" echo "=== 2. Chat Completion (GPT-4.1) ===" time curl -s "${BASE_URL}/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${API_KEY}" \ -d '{ "model": "gpt-4.1", "messages": [ {"role": "user", "content": "Erkläre in einem Satz, was Edge Computing ist."} ], "max_tokens": 100, "temperature": 0.7 }' | jq '.'

3. DeepSeek V3.2 - Kostenoptimaler Test

echo "" echo "=== 3. DeepSeek V3.2 (Kostenoptimal) ===" curl -s "${BASE_URL}/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${API_KEY}" \ -d '{ "model": "deepseek-chat", "messages": [ {"role": "system", "content": "Du bist ein hilfreicher Assistent."}, {"role": "user", "content": "Liste 5 Vorteile von Edge Computing auf."} ], "max_tokens": 200 }' | jq '.choices[0].message.content'

4. Latenz-Messung (mehrere Requests)

echo "" echo "=== 4. Latenz-Messung (5 Requests) ===" for i in {1..5}; do START=$(date +%s%N) curl -s "${BASE_URL}/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${API_KEY}" \ -d '{"model": "gemini-2.0-flash", "messages": [{"role": "user", "content": "Ping"}], "max_tokens": 10}' \ > /dev/null END=$(date +%s%N) ELAPSED=$(( (END - START) / 1000000 )) echo "Request $i: ${ELAPSED}ms" done

5. Stream Response Test

echo "" echo "=== 5. Stream Response Test ===" curl -s "${BASE_URL}/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${API_KEY}" \ -d '{ "model": "deepseek-chat", "messages": [{"role": "user", "content": "Zähle von 1 bis 5"}], "stream": true, "max_tokens": 50 }' | head -c 500 echo "" echo "" echo "✅ Alle Tests abgeschlossen!" echo "" echo "📊 HolySheep API Dashboard: https://www.holysheep.ai/dashboard" echo "💰 WeChat/Alipay Zahlung verfügbar | Startguthaben inklusive"

Häufige Fehler und Lösungen

Basierend auf meiner praktischen Erfahrung mit Edge-Deployments in Fabriken und Logistikzentren hier die häufigsten Probleme und deren Lösungen:

Fehler 1: Connection Timeout bei instabiler Netzwerkverbindung

# PROBLEM: Requests scheitern bei Netzwerkausfällen

FEHLERMELDUNG: requests.exceptions.ReadTimeout, HTTP 408

LÖSUNG: Implementiere exponential Backoff und Circuit Breaker Pattern

Python: Erweiterte Retry-Logik mit Circuit Breaker

import time import functools from collections import defaultdict from threading import Lock class CircuitBreaker: """Verhindert Cascade-Failures bei wiederholten Ausfällen""" def __init__(self, failure_threshold=5, timeout=60, recovery_timeout=300): self.failure_threshold = failure_threshold self.timeout = timeout # Sekunden bis Retry erlaubt self.recovery_timeout = recovery_timeout # Sekunden bis Reset self.failures = 0 self.last_failure_time = None self.state = "CLOSED" #