diff --git a/network/v2/init.go b/network/v2/init.go index 0b807d4..3cbcd27 100644 --- a/network/v2/init.go +++ b/network/v2/init.go @@ -55,6 +55,14 @@ const ( // tcpLingerTimeout defines a number of seconds to wait for sending // unacknowledged data. tcpLingerTimeout = 1 + + // tcpNotSentLowat limits the amount of unsent data queued in the + // kernel write buffer per socket. When the unsent data drops below + // this threshold, the socket becomes writable again. This reduces + // per-connection memory usage and bufferbloat by applying + // back-pressure to the relay loop instead of piling up data in + // kernel buffers. + tcpNotSentLowat = 128 * 1024 ) var ( diff --git a/network/v2/sockopts.go b/network/v2/sockopts.go index c1eafc1..933c76f 100644 --- a/network/v2/sockopts.go +++ b/network/v2/sockopts.go @@ -25,6 +25,7 @@ func setCommonSocketOptions(conn *net.TCPConn, keepAliveConfig net.KeepAliveConf setCongestionControl(rawConn) setTCPUserTimeout(rawConn, keepAliveConfig) + setNotSentLowat(rawConn) return nil } diff --git a/network/v2/sockopts_lowat.go b/network/v2/sockopts_lowat.go new file mode 100644 index 0000000..23ff936 --- /dev/null +++ b/network/v2/sockopts_lowat.go @@ -0,0 +1,20 @@ +//go:build linux || darwin + +package network + +import ( + "syscall" + + "golang.org/x/sys/unix" +) + +// setNotSentLowat sets TCP_NOTSENT_LOWAT which limits the amount of +// unsent data queued in the kernel write buffer. Once unsent data drops +// below this threshold the socket becomes writable again, applying +// back-pressure to the relay loop instead of piling up data in kernel +// buffers. This reduces per-connection memory and bufferbloat. +func setNotSentLowat(conn syscall.RawConn) { + conn.Control(func(fd uintptr) { //nolint: errcheck + unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_NOTSENT_LOWAT, tcpNotSentLowat) //nolint: errcheck + }) +} diff --git a/network/v2/sockopts_lowat_stub.go b/network/v2/sockopts_lowat_stub.go new file mode 100644 index 0000000..c77aa25 --- /dev/null +++ b/network/v2/sockopts_lowat_stub.go @@ -0,0 +1,7 @@ +//go:build !linux && !darwin + +package network + +import "syscall" + +func setNotSentLowat(conn syscall.RawConn) {}