TCP connections

If both a client and server simultaneously close a connection there is a race condition that may result in the connection hanging and not closing for minutes. Both sides of the connection may simultaneously send a FIN to the other side and both may end up waiting for an ACK or RST until the default TCP timeout; which is typically double MSL (maximum segment life time) or 4 minutes.

Having the client do a read until EOF is signaled before closing avoids the issue.

RFC 793 [Postel 1981] specifies the MSL as 2 minutes. Common implementation values, however, are 30 seconds, 1 minute and 2 minutes.

Description and diagrams of why simultaneous close results in time-wait

TCP state and sequence diagrams showing how and why the simultaneous close results in long timeouts

TCP protocol diagram including simultaneous close

SO_LINGER


From here:

The tcp_close_wait_interval is 4 minutes. This variable defines how long a host would wait in the TIME_WAIT state. This implies that the host which is still up tries to send packets over the TCP connection to the down host. If it doesn't get any replies it moves into this TIME_WAIT state for 4 minutes before it closes the socket.

By default, it could theoretically stay up forever. However, when a socket is created, you could give it the SO_KEEPALIVE option, which would send a keepalive according to the value tcp_keepalive_interval which defaults to 2 hours.

So if SO_KEEPALIVE is set the answer is 2 hours by default, if
not the socket could stay open indefinitely.

Comments

Popular posts from this blog

Oracle JDBC ReadTimeout QueryTimeout

Generically load enum mapping via properties file

ActiveMQ https