Gen_tcp listener crashes and reuseaddr

On https://elixir-lang.org/getting-started/mix-otp/task-and-gen-tcp.html

It says

    # 4. `reuseaddr: true` - allows us to reuse the address if the listener crashes

Does this mean if the listener crashes the socket is not closed? And if the socket is not closed, isn’t this a FD leak? Or does BEAM automatically reuse the previous socket?

No, when a process dies, any sockets it owns are automatically closed. In this case a new listener socket is opened when the supervisor starts a new listener process.

Without the reuseaddr flag, the OS would not allow the new listener socket to be created for some time (TCP TIME_WAIT timer) after the previous socket was closed. This would lead to a restart loop of the listener process that would likely escalate up the supervision hierarchy and possibly crash the application.

1 Like

That makes a lot of sense, thank you.