nginx_http_request_upstream_close
Overview
After a request is served, we need to free resource used by that request, nginx provides two main API(high level) to free downstream and upstream side.
- ngx_http_finalize_request: free request and client connection etc
- ngx_http_upstream_finalize_request: free upstream peer resource etc
Note: not always both APIs called for each request, it depends on config and phase it’s in, call proper API(some time lower level API) to free resource.
How request is finalized
Most normal case: Step1—>Step2—>Step3—>Step4
case1
no upstream is configured(no proxy_pass
): only ngx_http_finalize_request() is needed if request is created
case2
upstream is configured, but error happens before connect with upstream
, only ngx_http_finalize_request() is needed.
case3upstream is configured, connected with upstream, everything is ok, after send body to client, ngx_http_upstream_finalize_request ()is called(OK) firstly which invokes ngx_http_finalize_request() as well. this is the most normal case
case4
upstream is configured, connected with upstream,error happens at upstream side before request is served
, ngx_http_upstream_finalize_request() is called(ERROR) which invokes ngx_http_finalize_request() as well.
case5
upstream is configured, connected with upstream, error happens at downside side before request is served, ngx_http_finalize_request() is called firstly which invokes ngx_http_upstream_finalize_request() as it’s cleanup chain.
In a short word, we should free both side if created, no matter error or ok
, if no error, ngx_http_upstream_finalize_request is called firstly, otherwise, error side calls firstly
Note: some times low level API are called depends on what phase it’s in and what resource is created