Skip to content

Instantly share code, notes, and snippets.

@nh2
Last active November 18, 2020 07:06
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nh2/9def4bcf32891a336485 to your computer and use it in GitHub Desktop.
Save nh2/9def4bcf32891a336485 to your computer and use it in GitHub Desktop.
Understanding TCP_NODELAY

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 set TCP_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 toggling TCP_NODELAY; the condition "if there is unconfirmed data still in the pipe" makes it not apply to the first packet).

And finally, useful to know:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment