I believe the following is the best way to work with Nagle's algorithm / TCP_NODELAY
/ TCP_CORK
.
It is described in this RedHat manual and the verdict is:
- Set
TCP_NODELAY = 1
, always. - If you can batch data for sending by creating a buffer manually, or using
writev()
, prefer that. - If you cannot (e.g. "when using different libraries that provides abstractions for layers" from the above manual):
- Set
TCP_CORK = 1
, then write the data, then setTCP_CORK = 0
. - This builds a packet in kernel space and then flushes it out.
- This is similar to the idea of toggling
TCP_NODELAY
on-then-off-again for each thing to send, but it is better, since it also works for the first packet in a connection (see Wikipedia why it wouldn't work with togglingTCP_NODELAY
; the condition "if there is unconfirmed data still in the pipe" makes it not apply to the first packet).
- Set
And finally, useful to know:
- This is what nginx does: https://t37.net/nginx-optimization-understanding-sendfile-tcp_nodelay-and-tcp_nopush.html - section
Let’s mix everything together
.