TCP connection and TCP keep alive keepalive detection mechanism

Source: Internet
Author: User

The number of TCP connections for a 2-core 4G Linux server in a production environment is often kept hovering between 5-7w, and the number of requests per second is 100-200, so the number of TCP connections is so large. The HTTP protocol for the next client upstream is checked, the Connection header field is keep-alive, and the client does not close the connection immediately after the request has been completed. And the service side of the design is based on the client, the client upstream if connection:keep-alive, the server will not actively shut down the connection. When the client interacts with the server more frequently, such a design is reasonable, can reduce the repeated handshake of TCP. Obviously if you only interact once, there is no need for that. This is the case in our production environment. The client has to release the connection immediately after the request has been completed, on the code:

  public static void Send (Request req) {InputStream input=null;  Bytearrayoutputstream Out=null;  HttpClient client=new defaulthttpclient ();  try{httppost post=new httppost ("Http://ip:port"); Post.setheader ("User-agent", "mozilla/5.0" (Linux; U Android 2.2.1; En-us;  Nexus one build/frg83) applewebkit/533.1 (khtml, like Gecko) version/4.0 Mobile safari/533.1 ");  Post.setheader ("Expect", "100-continue");  Post.setheader ("Client_ip", "IP");    Post.addheader ("Connection", "close");  Httpentity entity=new bytearrayentity (ENCODER.ENCODEXIP (req));  Post.setentity (entity);  HttpResponse Resp=client.execute (POST);  Httpentity content = resp.getentity ();  Input=content.getcontent ();  Out=new Bytearrayoutputstream ();  byte by[]=new byte[1024];  int len=0;  while ((Len=input.read (by))!=-1) {out.write (by, 0, Len);   } System.out.println (New String (Out.tobytearray ()));  }catch (Exception e) {e.printstacktrace ();  return null; }finally{try {out.close (); Input.close (); Client.getconnectionmanAger (). shutdown ();//Active release Connection} catch (IOException e) {e.printstacktrace ();} }  }

The workaround seems to be simple. But the reality is that the client has many versions, and has been running in the hands of customers, change the client to reduce the number of server TCP connections, is a relatively time-consuming activity. There is no way to resolve only from the service side itself, the workaround can only actively shut down the TCP connection from the server side.

Do not worry at first from the program level to see the problem, from the operating system point of view can solve the problem, simple for the Linux kernel added some keep-alive parameters, found can also reduce the number of TCP connections. The operation is simple, add the following parameters to the/etc/sysctl.conf configuration file:

NET.IPV4.TCP_KEEPALIVE_INTVL = 3net.ipv4.tcp_keepalive_probes = 2net.ipv4.tcp_keepalive_time = 6
The last sysctl-p to bring it into effect.

The above parameter means that the client and server idle time reached 6 seconds, the service end every 3 seconds to detect the client survival situation, a total of detection two times, if the client process exits within 6+3*2=12, the server will actively shut down the connection. The service side detects that the client survives by sending a TCP-based keep alive message, and if the client process does not exit, it sends a response message confirming the keep alive. Message in Wireshark:


Just adjust the parameters of those days did not pay attention, later found that such operations will bring a serious waste of bandwidth, previously as long as the response bandwidth of about 1 m, now to about 5M, is the cost Ah, although the company pays.

Because our clients live longer, TCP keep alive keepalive mechanism can recover the number of TCP connections is relatively limited, but every 6 seconds of the message can make the server bandwidth doubled several times, not worth the candle.

Can only from the design aspects of the program, adjust the design of the service side, the original service is not active to close the connection, but based on the status of the client upstream connection decide whether to close, the new design is the server can configure the status of the connection, if the server configured connection: Close, the server takes precedence over configuration information, or, if not configured, the client upstream to determine the connection status.

The server is written in Java, based on the Netty communication framework. Netty Keep Alive Related parameters Only one option configuration, the relevant code is as follows:

    This.bootstrap.setPipelineFactory (New Channelpipelinefactory ()    {public      channelpipeline getpipeline ()        throws Exception      {        Channelpipeline pipeline = new Defaultchannelpipeline ();                Pipeline.addlast ("Codec", new Httpservercodec ());        Pipeline.addlast ("Aggregator", New Httpchunkaggregator (Maxcontentlength));        Pipeline.addlast ("Handler", New Httprequesthandler ());        return pipeline;      }    });    This.bootstrap.setOption ("Allidletime", Integer.valueof (This.idletime));    This.bootstrap.setOption ("Child.keepalive", boolean.valueof (True));    This.bootstrap.setOption ("Child.tcpnodelay", boolean.valueof (True));    This.bootstrap.setOption ("Child.solinger", Integer.valueof ( -1));    This.bootstrap.setOption ("Child.sendbuffersize", integer.valueof (-1));

This.bootstrap.setOption ("Child.keepalive", boolean.valueof (true)); This line of code only configures whether TCP keepalive detection is enabled, if it is enabled, how often it is detected or depends on the operating system itself. Plainly, the same effect as editing sysctl.conf files, because they are all detected from the TCP layer. Netty actively close the connection from the application layer, you can simply add a listener, the code is as follows:

    Channelfuture future = channel.write (response);    if ((! Httpheaders.iskeepalive (response)) | | (!response.containsheader ("Content-length"))) {      Future.addlistener (channelfuturelistener.close);    }
When the channel write operation is complete, the close listener actively close the channel.
The problem is basically solved, later found in fact can also add a layer of nginx agent to solve the problem, nginx through the short connection with the back end of the interaction, and the front end to maintain long connection, but not very clear nginx long connection detection mechanism, but according to the production environment shows the phenomenon, certainly not with the operating system parameters.


TCP keepalive mechanism can parameter this article http://www.blogjava.net/yongboy/archive/2015/04/14/424413.html



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

TCP connection and TCP keep alive keepalive detection mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.