deployment.yaml
一、AI 大模型推理服务上线第一天一切正常。第二天GPU 节点宕机服务中断 30 分钟。第三天流量峰值到来响应延迟从 200ms 飙升到 5 秒。这时候才意识到AI 推理服务的高可用设计不是部署两个副本就能解决。它需要系统性的架构设计覆盖负载均衡、容错、弹性伸缩、故障恢复多个层面。那些看似稳定的推理服务背后都有一套精心设计的高可用架构。二、AI 推理服务高可用的分层架构AI 推理服务的高可用架构可以分为四层接入层、推理层、模型层、基础设施层。每一层都有其可用性挑战和解决方案。graph TB A[客户端] -- B[接入层br/负载均衡 API网关] B -- C[推理层br/多个推理实例] C -- D[模型层br/模型仓库 版本管理] C -- E[基础设施层br/GPU 存储 网络] B -- B1[健康检查br/故障自动摘除] B -- B2[限流降级br/保护后端] B -- B3[重试策略br/幂等性保证] C -- C1[实例冗余br/多副本部署] C -- C2[无状态设计br/快速扩容] C -- C3[熔断机制br/避免雪崩] D -- D1[模型热加载br/减少停机时间] D -- D2[版本回滚br/快速恢复] D -- D3[模型缓存br/加速加载] E -- E1[GPU冗余br/多可用区部署] E -- E2[存储高可用br/分布式存储] E -- E3[网络冗余br/多线路接入] style B fill:#e1f5fe style C fill:#fff3e0 style D fill:#e8f5e9 style E fill:#f3e5f5接入层是高可用架构的第一道防线。它包括负载均衡器如 Nginx、HAProxy、云负载均衡器和 API 网关如 Kong、APISIX。核心功能包括健康检查定期探测后端推理实例的健康状态自动摘除故障节点。负载均衡策略轮询、最少连接、哈希会话保持等。限流降级保护后端服务不被流量冲垮。重试策略后端实例故障时自动重试但需要保证幂等性。推理层是核心。多个推理实例部署在不同可用区避免单点故障。推理实例应该设计为无状态模型加载在内存请求处理不依赖本地状态方便快速扩容和故障恢复。模型层管理模型的存储、版本、加载。模型仓库如 Hugging Face Hub、私有模型仓库需要高可用模型加载需要支持热加载不重启服务更新模型模型版本管理需要支持快速回滚。基础设施层提供计算、存储、网络资源。GPU 资源的冗余多 GPU、多可用区、存储的高可用分布式存储、多副本、网络冗余多线路、多运营商是高可用的基石。三、生产级高可用架构的实现以下是一个基于 Kubernetes 的 AI 推理服务高可用部署方案推理服务的 Kubernetes 部署配置# deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: llm-inference namespace: ai-services spec: replicas: 3 # 多副本 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 # 保证服务不中断 selector: matchLabels: app: llm-inference template: metadata: labels: app: llm-inference spec: affinity: podAntiAffinity: # 反亲和性副本部署在不同节点 requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: app operator: In values: - llm-inference topologyKey: kubernetes.io/hostname containers: - name: vllm image: vllm/vllm-openai:latest resources: limits: nvidia.com/gpu: 1 # 每个副本使用 1 个 GPU env: - name: MODEL value: meta-llama/Meta-Llama-3-8B-Instruct - name: TENSOR_PARALLEL_SIZE value: 1 ports: - containerPort: 8000 livenessProbe: # 存活探针 httpGet: path: /health port: 8000 initialDelaySeconds: 60 periodSeconds: 10 timeoutSeconds: 5 readinessProbe: # 就绪探针 httpGet: path: /health port: 8000 initialDelaySeconds: 30 periodSeconds: 5 timeoutSeconds: 3 lifecycle: # 优雅关闭 preStop: exec: command: [/bin/sh, -c, sleep 15]负载均衡器配置Nginxupstream llm_inference { least_conn; # 最少连接策略 server llm-inference-1:8000 max_fails3 fail_timeout30s; server llm-inference-2:8000 max_fails3 fail_timeout30s; server llm-inference-3:8000 max_fails3 fail_timeout30s; } server { listen 80; location /v1/chat/completions { proxy_pass http://llm_inference; # 健康检查 proxy_next_upstream error timeout http_500 http_502 http_503; proxy_next_upstream_tries 2; proxy_next_upstream_timeout 10s; # 超时设置 proxy_connect_timeout 5s; proxy_read_timeout 300s; # 生成长文本需要更长时间 # 重试策略需要后端支持幂等 proxy_set_header X-Request-Id $request_id; } }弹性伸缩配置KEDA Prometheus# scaledobject.yaml apiVersion: keda.sh/v1alpha1 kind: ScaledObject metadata: name: llm-inference-scaler spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: llm-inference minReplicaCount: 2 maxReplicaCount: 10 triggers: - type: prometheus metadata: serverAddress: http://prometheus:9090 metricName: inference_requests_per_second threshold: 10 # 每个副本处理 10 QPS query: | sum(rate(inference_requests_total[1m]))四、容错机制与故障恢复策略高可用架构的核心不是避免故障而是容忍故障。容错机制包括1. 熔断机制Circuit Breaker当推理服务故障率超过阈值时自动切断请求避免雪崩。import time from functools import wraps class CircuitBreaker: def __init__(self, failure_threshold5, recovery_timeout30): self.failure_threshold failure_threshold self.recovery_timeout recovery_timeout self.failure_count 0 self.last_failure_time None self.state CLOSED # CLOSED, OPEN, HALF_OPEN def __call__(self, func): wraps(func) def wrapper(*args, **kwargs): if self.state OPEN: if time.time() - self.last_failure_time self.recovery_timeout: self.state HALF_OPEN else: raise Exception(Circuit breaker is OPEN) try: result func(*args, **kwargs) if self.state HALF_OPEN: self.state CLOSED self.failure_count 0 return result except Exception as e: self.failure_count 1 self.last_failure_time time.time() if self.failure_count self.failure_threshold: self.state OPEN raise e return wrapper # 使用示例 CircuitBreaker(failure_threshold3, recovery_timeout60) def call_inference_api(prompt): response requests.post(http://llm-inference/v1/chat/completions, json{prompt: prompt}) response.raise_for_status() return response.json()2. 重试策略与幂等性重试是提高可用性的简单有效手段但需要保证幂等性相同请求多次执行结果一致。import backoff # pip install backoff backoff.on_exception( backoff.expo, (requests.RequestException,), max_tries3, max_time30 ) def call_inference_with_retry(prompt, request_id): 带重试的推理调用使用 request_id 保证幂等 headers {X-Request-Id: request_id} response requests.post( http://llm-inference/v1/chat/completions, json{prompt: prompt}, headersheaders ) response.raise_for_status() return response.json()3. 降级策略当推理服务不可用时降级到备用方案如规则引擎、缓存响应、简化模型。def inference_with_fallback(prompt): try: # 主模型70B 大模型 return call_large_model(prompt) except Exception as e: log.warning(f大模型调用失败降级到小模型: {e}) try: # 备用模型7B 小模型 return call_small_model(prompt) except Exception as e2: log.error(f小模型也失败返回缓存响应: {e2}) # 最终降级返回缓存的最相似响应 return get_cached_response(prompt)4. 多可用区部署与故障转移将推理服务部署在多个可用区Availability Zone当一个可用区故障时自动切换到另一个可用区。# 多可用区部署示例AWS apiVersion: apps/v1 kind: Deployment metadata: name: llm-inference-az1 spec: replicas: 2 template: spec: nodeSelector: topology.kubernetes.io/zone: us-east-1a --- apiVersion: apps/v1 kind: Deployment metadata: name: llm-inference-az2 spec: replicas: 2 template: spec: nodeSelector: topology.kubernetes.io/zone: us-east-1b五、高可用架构的代价与权衡高可用架构不是免费的午餐它有一系列代价代价一资源成本显著增加多副本部署意味着多倍资源消耗。3 个推理副本需要 3 张 GPU卡成本直接翻倍。弹性伸缩可以部分缓解这个问题但也需要额外的运维成本。代价二系统复杂度指数级上升引入负载均衡、健康检查、熔断、重试、降级等机制后系统复杂度显著增加。排查问题需要跨多个组件关联分析对团队技能要求更高。代价三一致性挑战多个推理副本意味着模型版本可能不一致滚动更新时。A/B 测试和灰度发布需要精细的流量控制避免用户看到不一致的结果。权衡策略根据业务重要性决定可用性目标核心业务如支付追求 99.99% 可用性非核心业务如推荐可以容忍更低可用性。使用托管服务降低运维成本云厂商的 AI 推理服务如 AWS Bedrock、Azure OpenAI已经内置高可用可以优先考虑。建立混沌工程文化定期主动注入故障如杀掉推理实例、断开网络验证高可用机制的有效性。独立开发者的实用主义建议从单副本 监控开始早期产品不需要复杂的高可用架构单副本 完善监控 快速恢复机制足矣。优先保证数据高可用模型可以重新加载但用户数据不能丢失。优先保证数据存储的高可用。建立运行手册Runbook记录常见故障的处理步骤缩短故障恢复时间。定期演练每季度进行一次故障演练如模拟 GPU 节点宕机验证高可用架构的有效性。高可用架构不是一次性的功能而是持续的工程实践。它需要在资源成本、系统复杂度、可用性目标之间找到动态平衡。毕竟AI 产品的长期价值不仅在于模型有多强更在于服务有多可靠。