服务调用超时异常处理
在机器学习模型监控系统中,服务调用超时是常见的运行时异常。当模型推理服务响应超过预设阈值时,需立即触发告警并执行降级策略。
监控指标配置
# Prometheus监控配置
- metric: http_request_duration_seconds
- labels: {service="model-inference", job="ml-model"}
- histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{service="model-inference"}[5m])) by (le))
- threshold: 2.0s
告警规则配置
# Alertmanager告警配置
ALERT ModelInferenceTimeout
IF http_request_duration_seconds > 2.0
FOR 2m
ANNOTATIONS {
summary = "模型推理服务超时,响应时间超过2秒"
description = "服务调用超时,当前延迟:{{ $value }}s"
}
复现步骤
- 模拟服务端延迟:
curl -w "time: %{time_total}s" http://model-service:8080/predict - 观察Prometheus指标变化
- 查看告警状态:
curl http://alertmanager:9093/api/v1/alerts
降级策略实现
# 服务降级代码示例
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, max=4))
def predict_with_timeout(data):
try:
return model.predict(data)
except TimeoutError:
# 回退到缓存结果或默认值
return fallback_result
告警响应流程
- 1分钟内自动重试
- 超过2分钟触发告警
- 30分钟后执行服务降级

讨论