nginx 剖析 request_time和upstream_response_time的誤區、區別

首先,澄清一個誤區

upstream_response_time必須在upstream配置時才能使用?

答案: 否。

舉例:

 

 

request_time

官網描述:request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client。

指的就是從接受用戶請求的第一個字節到發送完響應數據的時間,即$request_time包括接收客戶端請求數據的時間、後端程序響應的時間、發送響應數據給客戶端的時間(不包含寫日誌的時間)。

官方文檔:http://nginx.org/en/docs/http/ngx_http_log_module.html

upstream_response_time

官網描述:keeps time spent on receiving the response from the upstream server; the time is kept in seconds with millisecond resolution. Times of several responses are separated by commas and colons like addresses in the $upstream_addr variable.。

是指從Nginx向後端建立連接開始到接受完數據然後關閉連接爲止的時間。

從上面的描述可以看出,$request_time肯定比$upstream_response_time值大;尤其是在客戶端採用POST方式提交較大的數據,響應體比較大的時候。在客戶端網絡條件差的時候,$request_time還會被放大。

官方文檔:http://nginx.org/en/docs/http/ngx_http_upstream_module.html

“other” times

除了上述的request_time和upstream_response_time比較常用,在新的Nginx版本中對整個請求各個處理階段的耗時做了近一步的細分:

$upstream_connect_time(1.9.1):

keeps time spent on establishing a connection with the upstream server (1.9.1); the time is kept in seconds with millisecond resolution. In case of SSL, includes time spent on handshake. Times of several connections are separated by commas and colons like addresses in the $upstream_addr variable.

跟後端server建立連接的時間,如果是到後端使用了加密的協議,該時間將包括握手的時間。

$upstream_header_time(1.7.10):

keeps time spent on receiving the response header from the upstream server (1.7.10); the time is kept in seconds with millisecond resolution. Times of several responses are separated by commas and colons like addresses in the $upstream_addr variable.

接收後端server響應頭的時間。

 

另外,Why is request_time much larger than upstream_response_time in nginx access.log? 的也證實了這點:

 

如果把整個過程補充起來的話 應該是:
  [1用戶請求][2建立 Nginx 連接][3發送響應][4接收響應][5關閉  Nginx 連接]

upstream_response_time

  那麼 upstream_response_time 就是: 2+3+4+5 
  但是,一般這裏面可以認爲 [5關閉 Nginx 連接] 的耗時接近 0
  所以 upstream_response_time 實際上就是: 2+3+4 

request_time

  request_time 是:1+2+3+4
  二者之間相差的就是 [1用戶請求] 的時間

問題分析

出現問題原因彙總:

  1. 用戶端網絡狀況較差
  2. 傳遞數據本身較大
  3. 當使用 POST 方式傳參時 Nginx 會先把 request body 緩存起來


  這些耗時都會累積到 [1用戶請求] 頭上去

  這樣就解釋了爲什麼 request_time 有可能會比 upstream_response_time 要大

 

 

總結

因爲用戶端的狀況通常千差萬別 無法控制,所以並不應該被納入到測試和調優的範疇裏面
更值得關注的應該是 upstream_response_time,所以在實際工作中 如果想要關心哪些請求比較慢的話,記得要在配置文件的 log_format 中加入 $upstream_response_time 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章