fastapi给每个请求做耗时和内存分配分析的中间件例子:
class ProfilingMiddleware(BaseHTTPMiddleware):
"""Automatic per-request profiling middleware using pyinstrument.
Only active when DEBUG=true. Profiles every request and saves an HTML
flamegraph to PROFILING_DIR when the request exceeds
PROFILING_THRESHOLD_SECONDS. Files are named {request_id}.html so they
can be correlated with logs. /tmp is cleaned up automatically by the OS.
"""
@override
async def dispatch(self, request: Request, call_next: Callable) -> Response:
"""Profile every request; save enriched JSON if duration exceeds threshold."""
if not PYINSTRUMENT_AVAILABLE:
return await call_next(request)
# Start all three profilers
tracemalloc.start()
cpu_start = time.process_time()
profiler = Profiler(async_mode="enabled")
with profiler:
response = await call_next(request)
# Capture metrics immediately after the request
cpu_ms = round((time.process_time() - cpu_start) * 1000, 2)
mem_current_kb, mem_peak_kb = (v // 1024 for v in tracemalloc.get_traced_memory())
snapshot = tracemalloc.take_snapshot()
tracemalloc.stop()
wall_ms = round((profiler.last_session.duration if profiler.last_session else 0.0) * 1000, 2)
if wall_ms / 1000 >= settings.PROFILING_THRESHOLD_SECONDS:
raw_id = correlation_id.get() or "unknown"
if len(raw_id) == 32 and "-" not in raw_id:
raw_id = f"{raw_id[:8]}-{raw_id[8:12]}-{raw_id[12:16]}-{raw_id[16:20]}-{raw_id[20:]}"
settings.PROFILING_DIR.mkdir(parents=True, exist_ok=True)
filepath = settings.PROFILING_DIR / f"{raw_id}.json"
# Top 20 memory allocators — exclude profiler and stdlib noise
_excluded = ("tracemalloc", "pyinstrument", "<frozen", "logging/__init__")
top_allocs = [
{
"file": str(stat.traceback[0].filename).replace(str(__file__).rsplit("/", 3)[0] + "/", ""),
"line": stat.traceback[0].lineno,
"size_kb": round(stat.size / 1024, 2),
"count": stat.count,
}
for stat in snapshot.statistics("lineno")
if not any(ex in str(stat.traceback[0].filename) for ex in _excluded)
]
call_tree = json.loads(profiler.output(renderer=JSONRenderer()))
report = {
"request_id": raw_id,
"endpoint": f"{request.method} {request.url.path}",
"wall_time_ms": wall_ms,
"cpu_time_ms": cpu_ms,
"io_wait_ms": round(wall_ms - cpu_ms, 2),
"memory_peak_kb": mem_peak_kb,
"memory_allocated_kb": mem_current_kb,
"top_memory_allocators": top_allocs,
"call_tree": call_tree,
}
filepath.write_text(json.dumps(report, indent=2))
logger.debug(
"slow_request_profile_saved",
path=request.url.path,
method=request.method,
wall_time_ms=wall_ms,
cpu_time_ms=cpu_ms,
memory_peak_kb=mem_peak_kb,
io_wait_ms=round(wall_ms - cpu_ms, 2),
profile_file=str(filepath),
)
return response
这是一个请求级性能分析中间件:它会给每个请求做耗时和内存分配分析;如果请求总耗时超过阈值,就把这次请求的性能报告保存成 JSON 文件,方便后续排查慢接口。
它主要做四件事
| 步骤 | 代码作用 | 目的 |
|---|---|---|
| 启动分析 | tracemalloc.start()、记录 cpu_start、启动 Profiler | 开始采集 CPU、耗时、内存分配信息 |
| 执行请求 | response = await call_next(request) | 让请求继续进入后面的中间件和路由 |
| 采集指标 | 计算 wall_ms、cpu_ms、内存峰值、调用树 | 判断这次请求慢在哪里、占了多少内存 |
| 超阈值保存 | 写入 PROFILING_DIR/{request_id}.json | 只保留慢请求的详细分析结果 |
执行流程
请求进入 ProfilingMiddleware
↓
如果 pyinstrument 不可用:直接放行
↓
启动 tracemalloc 内存追踪
↓
记录 CPU 时间起点
↓
启动 pyinstrument Profiler
↓
await call_next(request)
↓
后面的中间件 / 路由 / 业务逻辑执行
↓
停止分析并计算指标
↓
如果请求耗时超过阈值
↓
保存 JSON 性能报告
↓
返回 response
几个关键字段是什么意思
wall_time_ms
wall_ms = round((profiler.last_session.duration if profiler.last_session else 0.0) * 1000, 2)
表示墙钟耗时,也就是这次请求从开始到结束实际过了多久。
它包含:
- CPU 计算时间
- 等待数据库返回的时间
- 等待网络请求的时间
await期间挂起等待的时间
cpu_time_ms
cpu_ms = round((time.process_time() - cpu_start) * 1000, 2)
表示这个进程实际消耗了多少 CPU 时间。
如果 CPU 时间很小,但墙钟时间很大,通常说明请求大部分时间在等待,比如等数据库、等外部 API、等锁、等 I/O。
io_wait_ms
"io_wait_ms": round(wall_ms - cpu_ms, 2)
这里是粗略估算:
等待时间 ≈ 总耗时 - CPU 时间
它不一定严格等于真实 I/O 等待,因为还可能包含调度、锁等待、异步任务切换等因素,但可以用来初步判断:
是计算慢,还是等待慢。
memory_peak_kb / memory_allocated_kb
来自:
mem_current_kb, mem_peak_kb = (v // 1024 for v in tracemalloc.get_traced_memory())
memory_peak_kb:这次请求追踪到的 Python 内存分配峰值memory_allocated_kb:快照时仍被追踪的当前内存分配量
注意:tracemalloc 主要追踪 Python 层内存分配,不完全等于操作系统进程 RSS 内存,也不一定能完整覆盖 C 扩展或第三方库底层分配的内存。
top_memory_allocators
来自:
snapshot.statistics("lineno")
它会列出哪些文件、哪些行分配了较多内存,并排掉一些噪音,比如:
"tracemalloc"
"pyinstrument"
"<frozen"
"logging/__init__"
用途是定位:
这次慢请求里,哪些代码行可能创建了大量对象或大列表/大字符串/大响应体。
call_tree
call_tree = json.loads(profiler.output(renderer=JSONRenderer()))
这是 pyinstrument 生成的调用树,用来看:
- 哪个函数耗时最多
- 耗时集中在哪条调用链
- 是业务函数慢、数据库访问慢,还是序列化/模型调用等环节慢
它和日志里的 request_id 有什么关系
这段代码:
raw_id = correlation_id.get() or "unknown"
说明它想从当前日志上下文里取一个请求关联 ID。
后面:
filepath = settings.PROFILING_DIR / f"{raw_id}.json"
表示性能报告文件名使用这个 ID。
这样做的意义是:
如果你在某条日志里看到某个 request_id 很慢,就可以去 PROFILING_DIR 找同名的 .json 文件,查看这次请求的详细耗时和内存分配。
不过它和类注释有一点不一致:注释里说保存 HTML flamegraph,但实际代码保存的是 JSON 文件。
需要注意的问题
-
注释和实际输出不一致
注释写的是 HTML flamegraph,但代码实际写的是.json。 -
如果
pyinstrument不可用,内存追踪不会启动
这里直接:return await call_next(request)所以不会执行后面的
tracemalloc.start()。 -
异常时可能不会停止分析
如果await call_next(request)抛异常,后面的:tracemalloc.stop()可能不会执行。更稳妥的写法通常应该用
try/finally保证停止追踪。 -
io_wait_ms是粗略估算
wall_time - cpu_time只能作为参考,不能直接断言全部是数据库或网络 I/O。 -
不适合默认开在生产环境
这类逐请求 profiling 有额外开销,尤其tracemalloc和 profiler 都会影响性能。更适合在 DEBUG、压测、定位慢接口时开启。
一句话概括:
这个中间件会给每个请求做性能和内存分析;只有慢请求才保存详细 JSON 报告,用来和日志里的 request_id 对应起来排查慢接口。
952




被折叠的 条评论
为什么被折叠?



