5

nginx中request_time/upstream_response_time区别

 2 years ago
source link: https://www.jianshu.com/p/7b656fb97302
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2022.03.07 14:10:03字数 1,128阅读 25

一、request_time与upstream_response_time比较

image.png

request_time

指的就是从接受用户请求的第一个字节到发送完响应数据的时间,即$request_time包括接收客户端请求数据的时间、后端程序响应的时间、发送响应数据给客户端的时间(不包含写日志的时间)。

image.png

upstream_response_time

是指从Nginx向后端建立连接开始到接受完数据然后关闭连接为止的时间

一般request_time比upstream_response_time大

如果用户端网络状况较差 或者传递数据本身较大
再考虑到 当使用 POST 方式传参时 Nginx 会先把 request body 缓存起来
而这些耗时都会累积到用户请求上去

这样就解释了:为什么 request_time 有可能会比 upstream_response_time 要大。

因为用户端的状况通常千差万别 无法控制 ,所以并不应该被纳入到测试和调优的范畴里面
更值得关注的应该是 upstream_response_time

所以在实际工作中 如果想要关心哪些请求比较慢的话,记得要在配置文件的 log_format 中加入 $upstream_response_time

upstream_response_time比request_time 大

upstream_response_time由clock_gettime(CLOCK_MONOTONIC_COARSE)计算,默认情况下,它可以过去4毫秒,相反,$ request_time由gettimeofday()计算。 所以最终upstream_response_time可能比response_time更大。

指导:

所以在通过nginx的access_log来分析后端程序接口响应的时候,需要在nginx的log_format中添加$upstream_response_time字段。


二、在新的Nginx版本中对整个请求各个处理阶段的耗时做了近一步的细分

$upstream_connect_time(1.9.1):

跟后端server建立连接的时间,如果是到后端使用了加密的协议,该时间将包括握手的时间。

$upstream_header_time(1.7.10):单位为秒。

接收后端server响应头的时间。

如果把整个过程补充起来的话 应该是:

  1. 建立 Nginx 连接
  2. 关闭 Nginx 连接

upstream_response_time 就是 2+3+4+5 但是 一般这里面可以认为 [5关闭 Nginx 连接] 的耗时接近 0,所以 upstream_response_time 实际上就是 2+3+4 。而 request_time 是 1+2+3+4。二者之间相差的就是 [1用户请求]的时间。

示意图

  • 程序真正的运行时间 = $upstream_header_time - $upstream_connect_time
  • $request_time 中包含了数据返回时间
  • $request_time 中包含了日志打印的时间

nginx日志出现大量超时报警,这个时候发现upstream_header_time正常,但是request_time、$upstream_response_time很大

分析:根据上面的示意图,这个时候便反映出是上游程序执行较慢、或发送数据量大,需要排查执行程序的相关慢日志。

同样是ngxin日志出现大量超时报警,这个时候发现request_time很大,但是upstream_response_time正常

分析:$upstream_response_time正常,说明程序执行完毕且正常返回,那么这个时候需要验证是数据返回过慢还是日志打印出现了阻塞。

原因:

  1. 数据返回慢可以通过抓包分析,通常来说是用户网络原因引起的;
  2. 日志打印出现阻塞,可能是机器io出现了问题,这个一般很容易发现;
  3. 还有可能是nginx配置了相关参数,导致了延迟关闭,这里只要根据问题现象一步一步排查即可。
  4. 也可能返回给客户端是https,大数据加解密耗时

解决方法:

  1. 把你的服务器放在high-speed network高性能网络上,让client能够快速访问
  2. 使用缓存CND、Nginx缓存
  3. 或者将你的服务器靠近用户,多IDC进行对不同区域用户服务。如:中国IDC、韩国IDC
  4. 去掉一些低效率算法,参考: Nagle's algorithm
  5. 调整服务器的TCP堆栈(参考 这篇文章). 然而调整TCP堆栈不会有多大作用,因为内核默认配置已经做了优化调整了。

$upstream_connect_time很大

可能是网络通信出现了问题;

$upstream_header_time很小,但是$upstream_response_time很大

可能是数据回写nginx出现了问题。

文章整理自:
https://blog.csdn.net/zzhongcy/article/details/105819628
https://www.cnblogs.com/dongruiha/p/7007801.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK