How nginx stream module reuse tcp connections?

Francis Daly francis at
Tue Mar 9 15:11:11 UTC 2021

On Sun, Mar 07, 2021 at 09:03:48PM -0500, allenhe wrote:

Hi there,

> So, if there is no error and the downstream/upstream didn't actively close
> the connection,  the nginx won't timeout and close the tcp connection with
> the downstream or with the upstream at all?  is that correct?

I don't think that's what I wrote.

It seems like a reasonable thing to hope exists; if you can point at the
source-or-documentation implements that, then you can expect it to work
that way.

But given that the point of "stream", in the context of tcp, is to sit
in the middle of a connection from the client, and a connection to the
upstream, I would expect that nginx would keep the client connection
open until the client closes it; and would keep the upstream connection
open until upstream closes it, or until the client closes the client
connection. (Unless other config overrides that.)

> and I suppose
> the SO_KEEPALIVE option is turn on by default on connection sockets, right?

That's another of those things that does not need guessing.

$ grep -rl SO_KEEPALIVE src/

I see it used in two files. (And the functions in which it is used,
are called from some other files.)

More usefully: I see it mentioned in the documentation of the stream
listen directive and the stream proxy_socket_keepalive directive; that
latter one is probably what you want here.

> The "session" refers to  the ngx_stream_session_t in the source code, I want
> to know if the tcp load balance (select upstream) is triggered just once per
> "session" just like http does with ngx_http_request_t?

That sounds like a clear question (although I'm not sure the analogy
with http is correct).

Maybe someone who knows the right answer, will be willing to answer.

I would guess that one client tcp connection == one stream session ==
one upstream tcp connection; but I have not tested it to check.


Francis Daly        francis at

More information about the nginx mailing list