Skip to content

fix: add SO_REUSEADDR to find_free_port to handle TIME_WAIT state #4573

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

qykong
Copy link

@qykong qykong commented Jun 12, 2025

PR type

  • Bug Fix
  • New Feature
  • Document Updates
  • More Models or Datasets Support

PR information

The find_free_port() function exhibits inconsistent behavior when trying to bind to recently used ports. Specifically:

  • After killing a swift deploy --port 8001 process on port 8001, find_free_port(8001) sometimes returns 8002 (I actually believe it would be better to throw an exception if a port was explicitly specified)
  • Re-running the same function immediately after may then return 8001

When a process using a TCP port is terminated, the port enters TCP's TIME_WAIT state for 30-120 seconds (OS-dependent). During this period, socket.bind() fails even though the port is effectively available. Adding SO_REUSEADDR socket option to allow binding to ports in TIME_WAIT state. In fact, this is what has been done within uvicorn as well before launching the server: https://github.com/encode/uvicorn/blob/5e33d430f13622c8363fe74d97963ab37f3df3c2/uvicorn/config.py#L513

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant