如何为 liveness 探针添加自定义阈值?

解读

在国内云原生面试中,面试官问“liveness 探针自定义阈值”并不是想听你背 Kubernetes 的 initialDelaySeconds 参数,而是考察候选人能否把 FastAPI 的健康检查逻辑与 K8s 探针语义打通:

  1. 让 /healthz 或 /live 接口返回的 HTTP 状态码真正反映应用“是否还活得有意义”;
  2. 把“阈值”做成可配置、可观测、可热更新的业务指标,而不是写死在代码里;
  3. 用异步、非阻塞的方式做探测,避免把健康检查本身拖成性能瓶颈。
    一句话:要让 K8s 的 livenessProbe 只负责“拨号”,真正的“阈值决策”必须在 FastAPI 侧完成,并且可灰度、可告警、可回滚。

知识点

  1. Starlette 的 BaseHTTPMiddleware 与 Request/Response 循环,用于无侵入挂载健康检查。
  2. Pydantic BaseSettings + 环境变量/配置中心,实现阈值热更新。
  3. asyncio.Event / aiocache 做轻量级状态机,避免每次探针都撞数据库或 Redis。
  4. prometheus_client 或 opentelemetry-metrics 暴露自定义指标,供 Prometheus 二次告警。
  5. K8s 侧 livenessProbe.httpGet.path=/live 与 readinessProbe 分离语义,避免重启风暴。
  6. 国内常见合规要求:金融场景下 liveness 必须 ≤1s RT,失败率阈值建议 0.5% 以内,否则触发限流或熔断。

答案

下面给出可直接落地的生产级代码骨架,演示“自定义阈值”如何与 FastAPI 结合:

# main.py
import asyncio, time, os
from typing import Literal
from fastapi import FastAPI, status
from pydantic import BaseSettings, Field
from aiocache import Cache
from prometheus_client import Counter, Histogram

class Config(BaseSettings):
    # 阈值全部走环境变量,方便 K8s ConfigMap 热更新
    LIVE_MAX_LATENCY: float = Field(0.2, description="单次探测 P99  latency 阈值,秒")
    LIVE_MAX_FAIL_RATE: float = Field(0.01, description="5 分钟内失败率阈值")
    LIVE_MIN_SAMPLE: int = Field(10, description="最小样本数,防止刚启动就误判")

config = Config()

app = FastAPI(title="Demo", version="1.0.0")
cache = Cache(Cache.MEMORY)  # 也可换成 Redis

# 指标
live_latency = Histogram("live_probe_latency_seconds", "Latency of live probe")
live_fail = Counter("live_probe_fail_total", "Total failed live probe")

# 模拟外部依赖
async def check_db() -> bool:
    await asyncio.sleep(0.05)  # 模拟 IO
    return True

# 核心逻辑:带滑动窗口的失败率计算
async def live_core() -> Literal[True, False]:
    start = time.perf_counter()
    try:
        ok = await check_db()
    except Exception:
        ok = False
    cost = time.perf_counter() - start
    live_latency.observe(cost)
    if not ok or cost > config.LIVE_MAX_LATENCY:
        live_fail.inc()
        return False
    return True

# 每 5 分钟滚动一次窗口,缓存命中避免每次都算
async def fail_rate() -> float:
    key = "live_fail_rate"
    cached = await cache.get(key)
    if cached is not None:
        return cached
    total = await cache.get("live_total") or 0
    fails = await cache.get("live_fails") or 0
    if total < config.LIVE_MIN_SAMPLE:
        rate = 0.0
    else:
        rate = fails / total
    await cache.set(key, rate, ttl=30)  # 30s 缓存
    return rate

# 探针入口
@app.get("/live")
async def liveness():
    total = await cache.increment("live_total", 1)
    healthy = await live_core()
    if not healthy:
        await cache.increment("live_fails", 1)
    # 决策:只要失败率或单次延迟超标,就返回 503,K8s 会重启 Pod
    if (await fail_rate()) > config.LIVE_MAX_FAIL_RATE:
        return status.HTTP_503_SERVICE_UNAVAILABLE
    return status.HTTP_204_NO_CONTENT

部署时,K8s YAML 片段:

livenessProbe:
  httpGet:
    path: /live
    port: 8000
  initialDelaySeconds: 10
  periodSeconds: 5
  timeoutSeconds: 1
  failureThreshold: 3

通过 ConfigMap 注入环境变量即可调整阈值,无需重启 Pod。Prometheus 抓取 live_probe_fail_total 与 live_probe_latency_seconds 后,可在 Grafana 配置告警:连续 3 分钟失败率 >1% 或 P99>200ms 就@值班。

拓展思考

  1. 多集群灰度:把阈值配置下沉到 Nacos/Apollo,结合标签 cluster=sh1 做 A/B,观察新版本是否把失败率抬高。
  2. 探针链式依赖:如果依赖 3 个下游,可用 asyncio.gather(*coros, return_exceptions=True) 并行探测,任一失败率超标即整体 503,避免“木桶效应”。
  3. 冷启动优化:FastAPI 启动时预建连接池,把首次 /live 延迟降到 50ms 以内,否则 K8s 可能因 initialDelaySeconds 过短一直重启。
  4. 合规审计:国内银行要求健康检查日志保留 6 个月,可在 live_core() 里同步写一条带 trace_id 的 JSON 日志到 Kafka,供 ELK 后续溯源。