On SO_REUSEADDR and SO_REUSEPORT Socket Options

If you think guaranteeing ordered operations isn’t necessary, you could do some testing using .monotonic or the more extreme .unordered.

On the SO_REUSEADDR socket option; you made me do some research and it turns out you can listen on the same IP:Port combination from multiple threads with that option, but as of Linux 3.9, the recommended option is SO_REUSEPORT since it implements a more efficient way of balancing the accepts among threads and is more secure by preventing socket hijacking. See the announcement article for all the details.

Now I have to go update all my servers. lol

3 Likes

Note: SO_REUSEPORT has different behavior on different systems and is not available on Windows, although Windows’ SO_REUSEADDR behaves practically the same. This SO anser explains it all in great detail.

3 Likes

According the the doc, reuse_address “sets SO_REUSEADDR and SO_REUSEPORT on POSIX. Sets SO_REUSEADDR on Windows, which is roughly equivalent.”. reuse_port is deprecated.

2 Likes

Does REUSE_PORT play a load balancing role? If so, under what scenario will it be load balanced on a machine? (hotreload configuration?)

In the above linked announcement article, SO_REUSEPORT is described to do load balancing and even stateful connections when possible. But I would advise using Zig’s net.Address abstraction layer which will let you specify the reuse_address option and will handle setting the most appropriate socket option depending on the platform.

1 Like

SO_REUSEPORT is not portable.
In linux it allows accept balancing.
To prevent hijacking, if there is already a process that listens the port without setting SO_REUSEPORT, the call is going to fail.
Since the entire TCP connection setup is happening during accept removing servers might drop connections.

1 Like