精准定位后端瓶颈应使用 $upstream_response_time,而非 $request_time;二者差值大说明问题在 Nginx 或链路层,差值小且均偏高则指向后端业务慢查询、阻塞或资源争用。

直接用 $request_time 单独定位后端业务瓶颈,不精准。它反映的是整条链路耗时,包含客户端网络、Nginx 自身处理、传输开销等干扰项。真正能指向后端业务处理性能的,是 $upstream_response_time —— 它只记录 Nginx 发起请求到收完上游响应的时间,剥离了无关变量。
但 $request_time 并非无用,它的价值在于对比分析:和 $upstream_response_time 一起看,才能快速归因。
关键判断逻辑:看差值,而不是绝对值
-
$request_time - $upstream_response_time显著偏大(如 >200ms)→ 瓶颈不在后端,而在 Nginx 层或中间链路 -
$request_time ≈ $upstream_response_time且两者同时偏高(如都 >800ms)→ 后端服务内部大概率存在慢查询、同步阻塞、GC 暂停或资源争用
例如:
- 用户上传 5MB 图片,
$request_time达 6.2s,$upstream_response_time仅 0.041s → 实际后端毫秒级完成,问题在客户端上传带宽或 Nginx body 缓存等待 - 某
/api/order接口,$request_time和$upstream_response_time均稳定在 1.8s 左右 → 应立刻检查该接口对应的数据库查询、远程调用或计算逻辑
日志配置必须包含这两个字段
确保 log_format 中显式写出:
log_format perf '$remote_addr [$time_local] "$request" '
'$status $body_bytes_sent '
'$request_time $upstream_response_time '
'$upstream_addr "$http_user_agent"';
access_log /var/log/nginx/access.log perf;
⚠️ 注意:$upstream_response_time 在多 upstream 场景下会以逗号分隔(如 0.003, 0.721),取最后一个值才代表本次实际命中的后端耗时。
快速筛查命令示例
-
查找后端真正慢的请求(排除上传/下载干扰):
awk '$(NF-1) > 1 && $NF > 1' /var/log/nginx/access.log | head -10
(假设倒数第二列是
$upstream_response_time,最后一列是$request_time) -
统计某接口的平均后端耗时:
awk '$7 ~ /^\/api\/order/ && $(NF-1) != "-" {sum += $(NF-1); cnt++} END {print "avg:", sum/cnt}' /var/log/nginx/access.log
不复杂但容易忽略











