FastAPI 上线的另一面:容器化、并发与回滚的全链路调优

zhichao Lv3

七月我们把两个 FastAPI 服务从“实验室”推到生产,踩过的坑一次性写清楚:如何包 Docker、怎么压测并发、如何在 Kubernetes 里优雅地滚动升级,以及出问题时如何两分钟内回滚。


1. 基础算力与容器基线

  • 基础镜像:python:3.11-slim
  • 包管理:uv(替代 pip/poetry,构建速度更快)
  • Web 服务:uvicorn[standard]

Dockerfile 核心:

1
2
3
4
5
6
7
8
FROM python:3.11-slim
ENV UVICORN_WORKERS=4 \
UVICORN_TIMEOUT=65
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN pip install uv && uv sync --frozen
COPY . .
CMD ["uv", "run", "uvicorn", "app.main:api", "--host", "0.0.0.0", "--port", "8000"]

重点:

  1. uv sync 锁定依赖,避免部署环境与本地不一致;
  2. 工作进程数用 min(核心数, 4),优先使用协程(--workers 只是多进程);
  3. timeout 留出给上游网关的余量(网关 60s → 服务 65s)。

2. 并发模型与压测

压测工具选 oha + k6

1
oha -n 2000 -c 200 https://api.example.com/predict

结果:

配置 P95 延迟 CPU 备注
单实例 / 2 核 / 512MB 420ms 85% 容量不足
单实例 / 4 核 / 1GB 210ms 68% 可接受
AutoScale (2→5) 170ms 55% 峰值平滑

瓶颈定位:模型推理阶段 CPU 绑定。解决方案:把推理逻辑移到独立的 Service,FastAPI 只做路由和限流,降低 tail latency。


3. 限流与熔断

  • 使用 slowapi 做 IP 限流,策略:100 req/min
  • 引入 asyncio.Semaphore 控制模型调用的并发上限;
  • 配置 Envoy 网关的熔断:max_concurrent_requests=200,超过直接返回 503。

示例:

1
2
3
4
5
6
7
8
9
10
from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)

@api.post("/predict")
@limiter.limit("100/minute")
async def predict(payload: Payload):
async with semaphore:
return await run_model(payload)

4. Kubernetes 发布与回滚

  • 控制器:Deployment + HPA
  • 镜像标签:使用 Git SHA,确保可追溯
  • 发布策略:RollingUpdatemaxUnavailable=0maxSurge=1

Helm values 片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
image:
repository: registry.example.com/fastapi-service
tag: "1.4.0-8c1f1af"

deployment:
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1

hpa:
minReplicas: 2
maxReplicas: 6
cpu: 65

如果上线后 5 分钟内某个指标(P95 > 300ms 或 错误率 > 2%)被 Prometheus Alertmanager 报警,就执行:

1
kubectl rollout undo deploy/fastapi-service

保持前一个版本的 Pod 仍留存 1 个副本,便于快速对比。


5. 观察与演练

  • 指标:请求量、延迟、并发、限流次数、熔断次数;
  • 日志:结构化 JSON,字段包含 trace_id、user_id、model_version;
  • 链路追踪:OpenTelemetry → Jaeger,用于定位跨服务瓶颈;
  • Chaos Drill:每月一次在预发环境注入延迟和故障,验证熔断/回滚链路。

FastAPI 本身没什么神秘,但上线需要的是“系统思维”:从镜像、并发、网关、监控、回滚全链条把控。做完这轮后,新项目直接复制 Helm Chart + 仓库模板即可开跑。

  • Title: FastAPI 上线的另一面:容器化、并发与回滚的全链路调优
  • Author: zhichao
  • Created at : 2024-07-18 14:30:00
  • Updated at : 2025-10-07 22:57:42
  • Link: https://chozzc.me/2024/07/18/2024-07-tech-fastapi-deploy-tuning/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
FastAPI 上线的另一面:容器化、并发与回滚的全链路调优