nginx request_time 與 upstream_request_time深入解析

背景: 某接口日誌status 499超時,request_time記錄到時間爲5s,upstream_request_time爲 (-)空。

解析:  客戶端提交請求超時時間爲5s,也就能解釋request_time全部記錄的都是5s,upstream_request_time爲(-)。說明nginx與php交互超時無返回。

第一張圖記錄的是nginx日誌,第二張是後端打印的日誌,時間相差5S,也就是php處理時間超過了5S。

 

1、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 。

指的就是從接受用戶請求的第一個字節到發送完響應數據的時間,即包括接收請求數據時間、程序響應時間、輸出響應數據時間。

2、upstream_response_time

官網描述:keeps times of responses obtained from upstream servers; times are kept in seconds with a milliseconds resolution. Several response times are separated by commas and colons like addresses in the $upstream_addr variable

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

從上面的描述可以看出,$request_time肯定大於等於$upstream_response_time,特別是使用POST方式傳遞參數時,因爲Nginx會把request body緩存住,接受完畢後纔會把數據一起發給後端。所以如果用戶網絡較差,或者傳遞數據較大時,$request_time會比$upstream_response_time大很多。。

根據引貼對官網描述的翻譯:
upstream_response_time:從 Nginx 建立連接 到 接收完數據並關閉連接
request_time:從 接受用戶請求的第一個字節 到 發送完響應數據

如果把整個過程補充起來的話 應該是:
[1用戶請求][2建立 Nginx 連接][3發送響應][4接收響應][5關閉  Nginx 連接]
那麼 upstream_response_time 就是 2+3+4+5 
但是 一般這裏面可以認爲 [5關閉 Nginx 連接] 的耗時接近 0
所以 upstream_response_time 實際上就是 2+3+4 
而 request_time 是 1+2+3+4
二者之間相差的就是 [1用戶請求] 的時間

如果用戶端網絡狀況較差 或者傳遞數據本身較大 
再考慮到 當使用 POST 方式傳參時 Nginx 會先把 request body 緩存起來
而這些耗時都會累積到 [1用戶請求] 頭上去
這樣就解釋了
爲什麼 request_time 有可能會比 upstream_response_time 要大

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

------------------------------------------------------------------------------------

proxy_ignore_client_abort on;

fastcgi_ignore_client_abort  on;

 

默認 proxy_ignore_client_abort 是關閉的,此時在請求過程中如果客戶端端主動關閉請求或者客戶端網絡斷掉,那麼 Nginx 會記錄 499,同時 request_time 是 「後端已經處理」的時間,而 upstream_response_time 爲 “-“ (已驗證)。

如果使用了 proxy_ignore_client_abort on ;

那麼客戶端主動斷掉連接之後,Nginx 會等待後端處理完(或者超時),然後 記錄 「後端的返回信息」 到日誌。所以,如果後端 返回 200, 就記錄 200 ;如果後端放回 5XX ,那麼就記錄 5XX 。

如果超時(默認60s,可以用 proxy_read_timeout 設置),Nginx 會主動斷開連接,記錄 504。

 

 

 

 

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