Search code examples
linuxsocketsclienttime-wait

how many ways to reduce the number of TIME_WAIT as soon as possible in client


If we must connect the db (redis)every time we need to write to or read from the db .After some operates then close the connection . Because the connect is frequently (assume the case must connect and then close) .As a result ,Too many TIME_WAIT state socket stay in kernel. some thing like :

`netstat -vatnl | grep 6379

tcp        0      0 127.0.0.1:6379              0.0.0.0:*                   LISTEN         
tcp        0      0 127.0.0.1:36476             127.0.0.1:6379              TIME_WAIT   
tcp        0      0 127.0.0.1:37193             127.0.0.1:6379            ESTABLISHED 
tcp        0      0 127.0.0.1:36480             127.0.0.1:6379              TIME_WAIT   
tcp        0      0 127.0.0.1:36479             127.0.0.1:6379              TIME_WAIT   
tcp        0      0 127.0.0.1:36472             127.0.0.1:6379              TIME_WAIT   
tcp        0      0 127.0.0.1:36457             127.0.0.1:6379              TIME_WAIT   
tcp        0      0 127.0.0.1:36460             127.0.0.1:6379              TIME_WAIT   
tcp        0      0 127.0.0.1:36481             127.0.0.1:6379              TIME_WAIT `
  1. Can we reuse the port in client ? such call bind() before connect() with the sock opt SO_REUSEPORT
  2. sysctl -w net.ipv4.tcp_timestamps=1 sysctl -w net.ipv4.tcp_tw_recycle=1<
    This way indeed help a lot .But I can still see many TIME_WAIT state
  3. Set socket opt SO_LINGER l_onoff=0 ; l_liger=1 or some other ways?

Solution

  • TIME_WAITs are part of tcp protocol tear-down processes. They ensure that packets of old-connection aren't accepted as part of new-connection. So unless there are 1000s of them should leave them as it is.

    Having said that as source/dest are localhost there shouldn't be a situation where packets of old-connection can be considered as new-connection's. Among your proposed solutions 1 can be used. Solutions 2 & 3 may have wider implications, so please check before applying them.