Là một kỹ sư backend đã vận hành hệ thống AI trung lập với hơn 50 triệu request mỗi tháng, tôi đã trải qua đủ các "cơn đau đầu" về latency spike, cold start, và token rate limit. Bài viết này sẽ chia sẻ chiến lược thực chiến để tối ưu warm-up và keep-alive cho API mô hình lớn, giúp bạn giảm độ trễ từ 2000ms xuống dưới 100ms một cách đáng tin cậy.

Bảng So Sánh: HolySheep AI vs API Chính Thức vs Dịch Vụ Relay

Tiêu chíHolySheep AIAPI Chính Thức (OpenAI/Anthropic)Dịch Vụ Relay Thông Thường
Chi phí GPT-4.1 $8/MTok $60/MTok $15-30/MTok
Chi phí Claude Sonnet 4.5 $15/MTok $45/MTok $25-40/MTok
Chi phí Gemini 2.5 Flash $2.50/MTok $7.50/MTok $5-10/MTok
Chi phí DeepSeek V3.2 $0.42/MTok $0.55/MTok $0.50-0.80/MTok
Độ trễ trung bình <50ms 150-500ms 100-300ms
Cold start Không có 2-8 giây 1-5 giây
Thanh toán WeChat/Alipay/VNPay Thẻ quốc tế Thẻ quốc tế
Tín dụng miễn phí Có, khi đăng ký $5 trial Không
Tỷ giá ¥1 ≈ $1 USD native USD native

Với mức tiết kiệm 85%+ so với API chính thức và không có cold start, HolySheep AI là lựa chọn tối ưu cho production. Đăng ký tại đây để nhận tín dụng miễn phí.

Tại Sao Warm-up và Keep-alive Lại Quan Trọng?

Khi triển khai ứng dụng sử dụng API mô hình lớn, có ba vấn đề chính mà hầu hết developer đều gặp phải:

Trong production thực tế của tôi, việc không implement warm-up đúng cách đã gây ra 3 lần incident lớn với p99 latency lên đến 15 giây — trong khi target chỉ là 500ms.

Chiến Lược Warm-up API Toàn Diện

1. Warm-up Cấp Kết Nối (Connection Level)

Trước khi xử lý request thực, cần đảm bảo connection pool đã được khởi tạo hoàn chỉnh. Dưới đây là implementation với Python sử dụng HolySheep API:

import openai
import asyncio
import httpx
from typing import Optional

class HolySheepAPIManager:
    """
    HolySheep AI API Manager với chiến lược Warm-up tự động
    base_url: https://api.holysheep.ai/v1
    """
    
    def __init__(
        self,
        api_key: str,
        base_url: str = "https://api.holysheep.ai/v1",
        max_connections: int = 100,
        warmup_timeout: float = 30.0
    ):
        self.api_key = api_key
        self.base_url = base_url
        self.warmup_timeout = warmup_timeout
        
        # HTTPX client với connection pooling
        self._client: Optional[httpx.AsyncClient] = None
        
        # OpenAI-compatible client
        self._openai_client: Optional[openai.AsyncOpenAI] = None
        
        # Trạng thái warm-up
        self._is_warmed = False
        self._last_warmup: Optional[float] = None
        
    async def initialize(self) -> bool:
        """
        Khởi tạo connection pool và warm-up ngay lập tức
        """
        # Khởi tạo HTTPX client với keep-alive
        self._client = httpx.AsyncClient(
            base_url=self.base_url,
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            },
            timeout=httpx.Timeout(self.warmup_timeout),
            limits=httpx.Limits(
                max_connections=max_connections,
                max_keepalive_connections=20,
                keepalive_expiry=300.0  # 5 phút
            )
        )
        
        # Khởi tạo OpenAI-compatible client
        self._openai_client = openai.AsyncOpenAI(
            api_key=self.api_key,
            base_url=self.base_url,
            http_client=httpx.AsyncClient(
                timeout=httpx.Timeout(self.warmup_timeout),
                limits=httpx.Limits(max_connections=max_connections)
            )
        )
        
        # Warm-up ngay lập tức
        await self.warmup()
        return self._is_warmed
    
    async def warmup(self) -> dict:
        """
        Thực hiện warm-up với nhiều model để prepare connection
        """
        import time
        start_time = time.time()
        
        warmup_results = {
            "status": "success",
            "models_tested": [],
            "latencies": {},
            "total_time_ms": 0
        }
        
        # Danh sách models cần warm-up
        models_to_warmup = [
            "gpt-4.1",
            "claude-sonnet-4-5",
            "gemini-2.5-flash",
            "deepseek-v3.2"
        ]
        
        for model in models_to_warmup:
            try:
                model_start = time.time()
                
                # Warm-up request nhẹ (echo test)
                response = await self._openai_client.chat.completions.create(
                    model=model,
                    messages=[{"role": "user", "content": "ping"}],
                    max_tokens=1,
                    temperature=0
                )
                
                model_latency = (time.time() - model_start) * 1000
                warmup_results["models_tested"].append(model)
                warmup_results["latencies"][model] = round(model_latency, 2)
                
            except Exception as e:
                warmup_results["status"] = "partial"
                warmup_results.setdefault("errors", {})[model] = str(e)
        
        warmup_results["total_time_ms"] = round(
            (time.time() - start_time) * 1000, 2
        )
        
        self._is_warmed = True
        self._last_warmup = time.time()
        
        return warmup_results
    
    async def close(self):
        """Đóng connection pool"""
        if self._client:
            await self._client.aclose()
        if self._openai_client:
            await self._openai_client.close()

Sử dụng

async def main(): manager = HolySheepAPIManager( api_key="YOUR_HOLYSHEEP_API_KEY", max_connections=100 ) await manager.initialize() results = await manager.warmup() print(f"Warm-up completed in {results['total_time_ms']}ms") print(f"Latencies: {results['latencies']}") asyncio.run(main())

2. Warm-up Cấp Ứng Dụng (Application Level)

Với ứng dụng production, cần implement warm-up ở nhiều cấp độ — không chỉ connection mà còn model loading và cache initialization:

import asyncio
import time
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Callable
from enum import Enum
import logging

logger = logging.getLogger(__name__)

class WarmupStatus(Enum):
    IDLE = "idle"
    WARMING = "warming"
    READY = "ready"
    STALE = "stale"

@dataclass
class WarmupConfig:
    """Cấu hình chiến lược warm-up"""
    # Thời gian tối thiểu giữa các warm-up (giây)
    min_interval: float = 300  # 5 phút
    
    # Số lượng warm-up requests cho mỗi model
    warmup_requests_per_model: int = 3
    
    # Kích thước prompt warm-up (tokens)
    warmup_prompt_tokens: int = 50
    
    # Timeout cho mỗi warm-up request (giây)
    request_timeout: float = 10.0
    
    # Tự động re-warm khi connection stales
    auto_rewarm_on_stale: bool = True
    
    # Stale threshold (giây không activity)
    stale_threshold: float = 600  # 10 phút

@dataclass
class WarmupMetrics:
    """Metrics theo dõi warm-up"""
    last_warmup_time: Optional[float] = None
    last_request_time: Optional[float] = None
    warmup_count: int = 0
    total_warmup_duration_ms: float = 0.0
    average_warmup_latency_ms: float = 0.0
    stale_count: int = 0
    
    latencies: Dict[str, List[float]] = field(default_factory=dict)
    
    def record_warmup(self, duration_ms: float, latencies: Dict[str, float]):
        self.last_warmup_time = time.time()
        self.warmup_count += 1
        self.total_warmup_duration_ms += duration_ms
        self.average_warmup_latency_ms = (
            self.total_warmup_duration_ms / self.warmup_count
        )
        
        for model, latency in latencies.items():
            if model not in self.latencies:
                self.latencies[model] = []
            self.latencies[model].append(latency)
    
    def record_request(self):
        self.last_request_time = time.time()
    
    def is_stale(self, threshold: float) -> bool:
        if not self.last_request_time:
            return True
        return (time.time() - self.last_request_time) > threshold

class SmartWarmupManager:
    """
    Manager xử lý warm-up thông minh cho HolySheep API
    - Tự động warm-up khi cần thiết
    - Tránh over-warmup gây lãng phí
    - Monitor connection health
    """
    
    def __init__(
        self,
        api_client,  # HolySheep API client instance
        config: WarmupConfig = None
    ):
        self.client = api_client
        self.config = config or WarmupConfig()
        self.metrics = WarmupMetrics()
        self.status = WarmupStatus.IDLE
        self._lock = asyncio.Lock()
        self._warmup_task: Optional[asyncio.Task] = None
        
    async def ensure_warmed(self) -> bool:
        """
        Đảm bảo connection đã được warm-up
        Tự động warm nếu cần thiết
        """
        async with self._lock:
            # Kiểm tra trạng thái hiện tại
            if self.status == WarmupStatus.READY:
                # Kiểm tra có stale không
                if self.config.auto_rewarm_on_stale:
                    if self.metrics.is_stale(self.config.stale_threshold):
                        logger.info("Connection stale, triggering re-warm")
                        self.status = WarmupStatus.STALE
                        self.metrics.stale_count += 1
                    else:
                        # Vẫn OK, chỉ cần verify nhẹ
                        return True
            
            if self.status in [WarmupStatus.WARMING]:
                # Đang trong quá trình warm-up, đợi
                await self._wait_for_warmup()
                return self.status == WarmupStatus.READY
            
            # Cần warm-up
            return await self._do_warmup()
    
    async def _do_warmup(self) -> bool:
        """Thực hiện warm-up process"""
        self.status = WarmupStatus.WARMING
        start_time = time.time()
        
        try:
            # Warm-up sequence với multiple prompts
            warmup_prompts = [
                "Hello, this is a warmup request.",
                "Testing connection and model availability.",
                "Quick verification of API responsiveness."
            ]
            
            models = ["gpt-4.1", "claude-sonnet-4-5", "gemini-2.5-flash"]
            all_latencies = {}
            
            for model in models:
                model_latencies = []
                
                for i, prompt in enumerate(warmup_prompts):
                    request_start = time.time()
                    
                    try:
                        response = await asyncio.wait_for(
                            self.client.chat.completions.create(
                                model=model,
                                messages=[{"role": "user", "content": prompt}],
                                max_tokens=self.config.warmup_prompt_tokens,
                                temperature=0.7
                            ),
                            timeout=self.config.request_timeout
                        )
                        
                        latency_ms = (time.time() - request_start) * 1000
                        model_latencies.append(latency_ms)
                        
                    except asyncio.TimeoutError:
                        logger.warning(
                            f"Warmup timeout for {model}, attempt {i+1}"
                        )
                        model_latencies.append(self.config.request_timeout * 1000)
                
                all_latencies[model] = sum(model_latencies) / len(model_latencies)
            
            duration_ms = (time.time() - start_time) * 1000
            self.metrics.record_warmup(duration_ms, all_latencies)
            self.status = WarmupStatus.READY
            
            logger.info(
                f"Warmup completed in {duration_ms:.2f}ms. "
                f"Latencies: {all_latencies}"
            )
            
            return True
            
        except Exception as e:
            logger.error(f"Warmup failed: {e}")
            self.status = WarmupStatus.IDLE
            return False
    
    async def _wait_for_warmup(self):
        """Đợi cho warm-up hoàn tất"""
        max_wait = 60  # 60 giây
        waited = 0
        
        while self.status == WarmupStatus.WARMING and waited < max_wait:
            await asyncio.sleep(0.5)
            waited += 0.5
    
    async def record_request(self):
        """Ghi nhận request để track activity"""
        self.metrics.record_request()
    
    def get_status(self) -> dict:
        """Lấy trạng thái và metrics hiện tại"""
        return {
            "status": self.status.value,
            "is_ready": self.status == WarmupStatus.READY,
            "is_stale": self.metrics.is_stale(self.config.stale_threshold),
            "metrics": {
                "warmup_count": self.metrics.warmup_count,
                "average_latency_ms": round(self.metrics.average_warmup_latency_ms, 2),
                "last_warmup_time": self.metrics.last_warmup_time,
                "stale_count": self.metrics.stale_count,
                "model_latencies": {
                    k: round(sum(v) / len(v), 2) 
                    for k, v in self.metrics.latencies.items()
                }
            }
        }

Middleware cho FastAPI/Starlette

class WarmupMiddleware: """Middleware tự động warm-up cho request handler""" def __init__(self, app, warmup_manager: SmartWarmupManager): self.app = app self.manager = warmup_manager async def __call__(self, scope, receive, send): if scope["type"] == "http": # Warm-up trước khi xử lý request await self.manager.ensure_warmed() # Ghi nhận request self.manager.record_request() await self.app(scope, receive, send)

Chiến Lược Keep-alive Hiệu Quả

3. Heartbeat và Periodic Health Check

Để duy trì connection alive, cần implement heartbeat system với monitoring thông minh:

import asyncio
import time
from typing import Dict, Optional, Callable
from dataclasses import dataclass
import logging

logger = logging.getLogger(__name__)

@dataclass
class KeepAliveConfig:
    """Cấu hình keep-alive"""
    # Interval heartbeat (giây)
    heartbeat_interval: float = 30.0
    
    # Số heartbeat failures trước khi reconnect
    max_failures: int = 3
    
    # Timeout cho mỗi heartbeat request (giây)
    heartbeat_timeout: float = 5.0
    
    # Thời gian tối đa giữa 2 request thực trước khi force heartbeat (giây)
    force_heartbeat_after: float = 60.0
    
    # Số lượng concurrent heartbeat connections
    concurrent_heartbeats: int = 2

class ConnectionHealthMonitor:
    """
    Monitor và duy trì connection health cho HolySheep API
    - Heartbeat tự động
    - Health scoring
    - Auto-reconnect
    """
    
    def __init__(
        self,
        api_client,
        config: KeepAliveConfig = None
    ):
        self.client = api_client
        self.config = config or KeepAliveConfig()
        
        # Trạng thái
        self._running = False
        self._heartbeat_task: Optional[asyncio.Task] = None
        self._failure_count = 0
        self._last_heartbeat_time: Optional[float] = None
        self._last_successful_request: Optional[float] = None
        
        # Health metrics
        self.health_score = 100.0
        self.heartbeat_history: list = []
        self.reconnect_count = 0
        
        # Callbacks
        self._on_health_degraded: Optional[Callable] = None
        self._on_reconnect_needed: Optional[Callable] = None
    
    def set_health_degraded_callback(self, cb: Callable):
        self._on_health_degraded = cb
    
    def set_reconnect_callback(self, cb: Callable):
        self._on_reconnect_needed = cb
    
    async def start(self):
        """Bắt đầu heartbeat monitor"""
        if self._running:
            return
        
        self._running = True
        self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
        logger.info("Health monitor started")
    
    async def stop(self):
        """Dừng heartbeat monitor"""
        self._running = False
        if self._heartbeat_task:
            self._heartbeat_task.cancel()
            try:
                await self._heartbeat_task
            except asyncio.CancelledError:
                pass
        logger.info("Health monitor stopped")
    
    async def record_request(self, latency_ms: float, success: bool = True):
        """Ghi nhận request để cập nhật health score"""
        self._last_successful_request = time.time()
        
        if success:
            # Tăng health score dựa trên latency
            if latency_ms < 100:
                self.health_score = min(100, self.health_score + 1)
            elif latency_ms < 500:
                pass  # Giữ nguyên
            else:
                self.health_score = max(0, self.health_score - 5)
    
    async def _heartbeat_loop(self):
        """Main heartbeat loop"""
        while self._running:
            try:
                await asyncio.sleep(self.config.heartbeat_interval)
                
                # Kiểm tra xem có cần heartbeat không
                if not self._should_heartbeat():
                    continue
                
                # Thực hiện heartbeat
                success = await self._do_heartbeat()
                
                if success:
                    self._failure_count = 0
                    self._last_heartbeat_time = time.time()
                    self.heartbeat_history.append({
                        "timestamp": time.time(),
                        "success": True,
                        "latency": self.heartbeat_history[-1]["latency"] 
                            if self.heartbeat_history else 0
                    })
                else:
                    self._failure_count += 1
                    self.health_score = max(0, self.health_score - 10)
                    
                    if self._failure_count >= self.config.max_failures:
                        await self._handle_connection_failure()
                
                # Giới hạn history
                if len(self.heartbeat_history) > 100:
                    self.heartbeat_history = self.heartbeat_history[-100:]
                    
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Heartbeat loop error: {e}")
    
    def _should_heartbeat(self) -> bool:
        """Xác định có nên thực hiện heartbeat không"""
        # Luôn heartbeat nếu chưa từng heartbeat
        if not self._last_heartbeat_time:
            return True
        
        # Heartbeat nếu quá lâu không có request
        if self._last_successful_request:
            time_since_request = time.time() - self._last_successful_request
            if time_since_request > self.config.force_heartbeat_after:
                return True
        
        # Heartbeat nếu health score thấp
        if self.health_score < 80:
            return True
        
        return False
    
    async def _do_heartbeat(self) -> bool:
        """Thực hiện heartbeat request"""
        start_time = time.time()
        
        try:
            # Lightweight request để verify connection
            response = await asyncio.wait_for(
                self.client.chat.completions.create(
                    model="gpt-4.1",
                    messages=[{"role": "user", "content": "heartbeat"}],
                    max_tokens=1,
                    temperature=0
                ),
                timeout=self.config.heartbeat_timeout
            )
            
            latency_ms = (time.time() - start_time) * 1000
            
            if latency_ms < 500:
                self.health_score = min(100, self.health_score + 0.5)
            
            logger.debug(f"Heartbeat OK, latency: {latency_ms:.2f}ms")
            return True
            
        except asyncio.TimeoutError:
            logger.warning("Heartbeat timeout")
            return False
        except Exception as e:
            logger.warning(f"Heartbeat failed: {e}")
            return False
    
    async def _handle_connection_failure(self):
        """Xử lý khi connection failure vượt threshold"""
        logger.error("Connection health critical, triggering reconnect")
        
        if self._on_reconnect_needed:
            await self._on_reconnect_needed()
        
        self.reconnect_count += 1
        self._failure_count = 0
        
        # Exponential backoff before reconnect attempt
        await asyncio.sleep(min(30, 2 ** self.reconnect_count))
    
    def get_health_report(self) -> dict:
        """Lấy health report chi tiết"""
        return {
            "health_score": round(self.health_score, 2),
            "status": "healthy" if self.health_score >= 80 
                else "degraded" if self.health_score >= 50 
                else "critical",
            "running": self._running,
            "failure_count": self._failure_count,
            "reconnect_count": self.reconnect_count,
            "last_heartbeat": self._last_heartbeat_time,
            "last_request": self._last_successful_request,
            "heartbeat_history": self.heartbeat_history[-10:] if self.heartbeat_history else []
        }

Integration với main application

class HolySheepConnectionPool: """ Connection pool tích hợp warm-up và keep-alive """ def __init__(self, api_key: str): self.api_key = api_key # Initialize clients import openai self.client = openai.AsyncOpenAI( api_key=api_key, base_url="https://api.holysheep.ai/v1" ) # Managers self.warmup_manager: Optional[SmartWarmupManager] = None self.health_monitor: Optional[ConnectionHealthMonitor] = None # State self._initialized = False async def initialize(self): """Khởi tạo với warm-up và health monitoring""" # Setup warmup manager self.warmup_manager = SmartWarmupManager(self.client) await self.warmup_manager.ensure_warmed() # Setup health monitor self.health_monitor = ConnectionHealthMonitor(self.client) await self.health_monitor.start() self._initialized = True async def request(self, model: str, messages: list, **kwargs): """Wrapper cho API request với automatic warm-up""" if not self._initialized: await self.initialize() # Đảm bảo đã warm await self.warmup_manager.ensure_warmed() # Ghi nhận request self.warmup_manager.record_request() start_time = time.time() try: response = await self.client.chat.completions.create( model=model, messages=messages, **kwargs ) latency_ms = (time.time() - start_time) * 1000 await self.health_monitor.record_request(latency_ms, success=True) return response except Exception as e: await self.health_monitor.record_request(0, success=False) raise async def close(self): """Cleanup resources""" if self.health_monitor: await self.health_monitor.stop() await self.client.close()

Production Deployment: Best Practices

4. Kubernetes-sidecar Pattern

Trong môi trường Kubernetes, tôi recommend sử dụng sidecar pattern để handle warm-up một cách decoupled:

# kubernetes-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: llm-api-gateway
  labels:
    app: llm-api-gateway
spec:
  replicas: 3
  selector:
    matchLabels:
      app: llm-api-gateway
  template:
    metadata:
      labels:
        app: llm-api-gateway
    spec:
      containers:
      # Main application container
      - name: api-server
        image: your-api-server:latest
        ports:
        - containerPort: 8000
        env:
        - name: HOLYSHEEP_API_KEY
          valueFrom:
            secretKeyRef:
              name: holysheep-credentials
              key: api-key
        - name: HOLYSHEEP_BASE_URL
          value: "https://api.holysheep.ai/v1"
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
          limits:
            memory: "1Gi"
            cpu: "1000m"
        readinessProbe:
          httpGet:
            path: /health/ready
            port: 8000
          initialDelaySeconds: 5
          periodSeconds: 5
        livenessProbe:
          httpGet:
            path: /health/live
            port: 8000
          initialDelaySeconds: 15
          periodSeconds: 20
        lifecycle:
          preStop:
            exec:
              command: ["/bin/sh", "-c", "sleep 10"]
      
      # Warmup sidecar container
      - name: warmup-sidecar
        image: your-warmup-sidecar:latest
        env:
        - name: HOLYSHEEP_API_KEY
          valueFrom:
            secretKeyRef:
              name: holysheep-credentials
              key: api-key
        - name: HOLYSHEEP_BASE_URL
          value: "https://api.holysheep.ai/v1"
        - name: WARMUP_INTERVAL
          value: "300"  # 5 phút
        - name: WARMUP_MODELS
          value: "gpt-4.1,claude-sonnet-4-5,gemini-2.5-flash,deepseek-v3.2"
        resources:
          requests:
            memory: "128Mi"
            cpu: "100m"
          limits:
            memory: "256Mi"
            cpu: "500m"
        volumeMounts:
        - name: warmup-state
          mountPath: /var/lib/warmup
      
      volumes:
      - name: warmup-state
        emptyDir: {}
---
apiVersion: v1
kind: Secret
metadata:
  name: holysheep-credentials
type: Opaque
stringData:
  api-key: "YOUR_HOLYSHEEP_API_KEY"
# warmup-sidecar/main.py
#!/usr/bin/env python3
"""
Warmup Sidecar cho Kubernetes
- Chạy periodic warm-up requests
- Giao tiếp với main container qua shared volume/file
- Báo cáo trạng thái qua health endpoint
"""
import asyncio
import os
import json
import time
import logging
from datetime import datetime
from pathlib import Path

import openai

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class WarmupSidecar:
    def __init__(self):
        self.api_key = os.environ["HOLYSHEEP_API_KEY"]
        self.base_url = os.environ.get("HOLYSHEEP_BASE_URL", "https://api.holysheep.ai/v1")
        self.interval = int(os.environ.get("WARMUP_INTERVAL", "300"))
        self.models = os.environ.get("WARMUP_MODELS", "gpt-4.1").split(",")
        self.state_file = Path("/var/lib/warmup/state.json")
        
        self.client = openai.AsyncOpenAI(
            api_key=self.api_key,
            base_url=self.base_url
        )
        
        self.state = {
            "last_warmup": None,
            "warmup_count": 0,
            "latencies": {},
            "errors": [],
            "running": True
        }
    
    async def warmup_model(self, model: str) -> float:
        """Warmup một model và trả về latency"""
        start = time.time()
        
        try:
            response = await self.client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": "warmup"}],
                max_tokens=1,
                timeout=10.0
            )
            
            latency_ms = (time.time() - start) * 1000
            logger.info(f"Warmup {model}: {latency_ms:.2f}ms")
            return latency_ms
            
        except Exception as e:
            logger.error(f"Warmup failed for {model}: {e}")
            self.state["errors"].append({
                "time": time.time(),
                "model": model,
                "error": str(e)
            })
            return -1
    
    async def run_warmup_cycle(self):
        """Chạy một chu kỳ warm-up cho tất cả models"""
        logger.info(f"Starting warmup cycle for {len(self.models)} models")
        
        latencies = {}
        tasks = [self.warmup_model(model) for model in self.models]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        for model, result in zip(self.models, results):
            if isinstance(result, (int, float)):
                latencies[model] = result
            elif isinstance(result, Exception):
                latencies[model] = -1
                logger.error(f"Exception for {model}: {result}")
        
        self.state["last_warmup"] = time.time()
        self.state["warmup_count"] += 1
        self.state["latencies"] = latencies
        
        # Tính trung bình
        valid_latencies = [v for v in latencies.values() if v > 0]
        if valid_latencies:
            avg_latency = sum(valid_latencies) / len(valid_latencies)
            self.state["average_latency"] = avg_latency
            logger.info(f"Warmup cycle complete. Avg latency: {avg_latency:.2f}ms")
        
        await self.save_state()
    
    async def save_state(self):
        """Lưu state vào shared volume"""
        self.state_file.parent.mkdir(parents=True, exist_ok=True)
        with open(self.state_file, "w") as f:
            json.dump(self.state, f, indent=2)
    
    async def load_state(self):
        """Load state từ shared volume"""
        if self.state_file.exists():
            with open(self.state_file) as f:
                self.state.update(json.load(f))
    
    async def run(self):
        """Main loop"""
        await self.load_state()
        
        # Initial warmup
        await self.run_warmup_cycle()
        
        # Periodic warmup
        while self.state["running"]:
            await asyncio.sleep(self.interval)
            
            # Kiểm tra xem main container có healthy không
            # (thông qua readiness probe)
            
            await self.run_warmup_cycle()
        
        await self.client.close()

if __name