CodePark/ questions / Sockets, ports & proxies
START PRACTICINGPRACTICE
Backend question · OS, networking & Linux › Sockets, ports & proxies

What are ephemeral ports, and how can a busy service run out of them? What error appears, and how do you fix it?

An ephemeral port is a temporary local port that the kernel gives a client when it connects without choosing a port. The kernel picks it from a range. On Linux, the default net.ipv4.ip_local_port_range is 32768 to 60999. That is about 28,000 ports.

How they run out: the four-tuple (source IP, source port, destination IP, destination port) must be unique. So every connection to the same destination IP and port needs its own local port. Imagine a service that opens a new connection for every outbound request to one upstream, like a single database proxy or API:

  • Each request uses one local port.
  • After a connection closes, its port stays in TIME_WAIT state for 60 seconds and can't be reused.
  • At about 470 new connections per second, the whole range is used up.

New connections then fail with EADDRNOTAVAIL ("cannot assign requested address").

The fix: stop opening and closing connections all the time. Use HTTP keep-alive agents and connection pools, so connections get reused.

These options give more room, but they don't remove the cause:

  • widening the port range
  • enabling tcp_tw_reuse
  • spreading traffic over more destination IPs
  • Ephemeral ports come from ip_local_port_range, which has about 28,000 ports by default.
  • Each connection to the same destination needs a different local port.
  • TIME_WAIT keeps a port busy for 60 seconds after the connection closes.
  • Running out of ports gives the EADDRNOTAVAIL error.
  • Fix it with keep-alive and connection pooling.