I have an implementation of an HTTP server in C#. Using ab I discovered a weird performance issue. Each request took 5 ms with Keep-Alive Off but 40 ms with Keep-Alive on!
The testpage is generated into a single byte[] which get sent as reply using a single socket.Send call.
The cause is as far as I can tell Nagle's algorithm used in the TCP stack.
So far I am using the NoDelay property in the end of every HTTP request served.
socket.NoDelay = true;
socket.NoDelay = false;
Which does solve the problem for now. But I have no documentation to backup my discovery.
This was tested on a linux/mono system.
Is there a standard way of flushing the TCP connection?
This answer is addressing the same issue. The difference here is that I am looking to only temporarily disabling the algorithm.
If you need to force data to be sent immediately, however, flushing the buffer will send any data which has not yet been sent. Note that when you close a socket, it automatically flushes any remaning data, so there's no need to flush before you close.
One way or another, if you don't close a socket, your program will leak a file descriptor. Programs can usually only open a limited number of file descriptors, so if this happens a lot, it may turn into a problem.
The TCPNODELAY option specifies whether the server disables the delay of sending successive small packets on the network. Change the value from the default of YES only under one of these conditions: You are directed to change the option by your service representative.
I tested this with Wireshark. Unfortunately,
socket.NoDelay = true;
socket.NoDelay = false;
has no effect. Similarly,
socket.NoDelay = true;
socket.Send(new byte[0]);
socket.NoDelay = false;
also has no effect. From observed behaviour, it appears that the NoDelay
property only affects the next call to Send
with a non-empty buffer. In other words, you have to send some actual data before NoDelay
will have any effect.
Therefore, I conclude that there is no way to explicitly flush the socket if you don’t want to send any extra data.
However, since you are writing an HTTP server, you may be able to use a few tricks:
Transfer-Encoding: chunked
, you can send the end-of-stream marker (the "\r\n0\r\n\r\n"
) with NoDelay = true
.NoDelay = true
just before sending the last chunk.Content-Encoding: gzip
, you can set NoDelay = true
just before closing the gzip stream; the gzip stream will send some last bits before actually finishing and closing.I’m certainly going to add the above to my HTTP server now :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With