Skip to content

Conversation

@chenkaiyue
Copy link

Description

fix this issue sgl-project/sglang#13395

This PR adds a retry mechanism for automatic port binding during client initialization in RealClient::setup_internal(). When multiple clients start simultaneously on the same host, they may encounter port conflicts or metadata registration failures. This change improves reliability by automatically retrying with different ports.

Problem

In high-concurrency scenarios (e.g., multiple workers starting at the same time), the current implementation may fail to create a client due to:

  1. Port binding race conditions: Multiple processes may try to bind the same auto-assigned port
  2. Metadata registration conflicts: Even if port binding succeeds locally, metadata server registration may fail if another client has already registered with the same hostname:port
  3. Stale metadata after unclean shutdown: When a Mooncake client exits (crashes or terminates unexpectedly), it does not unregister its port from the metadata service. Upon restart, the client may be assigned the same port that is still registered in the metadata service from the previous session, causing registration failure due to duplicate hostname:port entries.

The original code would fail immediately without any retry, causing service startup failures in distributed deployments.

Solution

  • Separate handling for user-specified vs auto-assigned ports:

    • If user explicitly specifies a port (e.g., hostname:8080), the behavior remains unchanged (no retry)
    • If port is auto-assigned, implement retry logic with up to 20 attempts
  • Retry mechanism:

    • On each retry, release the current port and acquire a new one
    • Attempt to create the client with the new port
    • Log warnings for each failed attempt and success info on completion
  • Code restructuring:

    • Moved device_name initialization before the port binding logic for cleaner code flow
    • Added clear separation between user-specified port path and auto-binding path

Changes

  • mooncake-store/src/real_client.cpp: Modified setup_internal() function

Type of Change

  • Types
    • [√] Bug fix
    • [√ ] New feature
      • [√ ] Transfer Engine
      • [√ ] Mooncake Store
      • Mooncake EP
      • Integration
      • P2P Store
      • Python Wheel
    • Breaking change
    • CI/CD
    • Documentation update
    • Other

How Has This Been Tested?

Checklist

  • I have performed a self-review of my own code.
  • I have updated the documentation.
  • I have added tests to prove my changes are effective.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @chenkaiyue, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the robustness of the Mooncake client setup process by introducing an intelligent retry mechanism for automatically assigned ports. This change directly addresses common issues like port binding race conditions and metadata registration conflicts that can arise in distributed or high-concurrency environments, ensuring more reliable client initialization and preventing service startup failures.

Highlights

  • Enhanced Client Setup Reliability: Implemented a retry mechanism for automatic port binding during client initialization in RealClient::setup_internal() to mitigate port conflicts and metadata registration failures in high-concurrency scenarios.
  • Differentiated Port Handling: Introduced separate logic for user-specified ports (no retry) and auto-assigned ports (with retry), ensuring that explicit configurations are respected while providing resilience for dynamic assignments.
  • Code Structure Improvement: Refactored the setup_internal() function by moving device_name initialization earlier, leading to a clearer and more logical code flow.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a retry mechanism for automatic port binding during client setup, which is a solid improvement for reliability in high-concurrency environments. The implementation is clear and directly addresses the issues of port conflicts and metadata registration failures. I have a few suggestions to further enhance the robustness and configurability of the new logic:

  1. Make the maximum number of retries configurable via an environment variable.
  2. Use a more descriptive error code when all retry attempts fail.
  3. Introduce a small delay between retries to better handle transient resource contention.

if (!success) {
LOG(ERROR) << "Failed to create client after " << kMaxRetries
<< " retries";
return tl::unexpected(ErrorCode::INVALID_PARAMS);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Returning ErrorCode::INVALID_PARAMS when all retries for auto-port binding fail is misleading. This error code implies that the user provided incorrect parameters, but in this scenario, the port is automatically generated. A failure after multiple retries suggests a persistent environmental issue (e.g., resource exhaustion, network problem). A more appropriate error code would be ErrorCode::INTERNAL_ERROR to indicate a persistent failure to set up the client.

            return tl::unexpected(ErrorCode::INTERNAL_ERROR);

this->local_hostname = local_hostname;
}
// Auto port binding with retry on metadata registration failure
constexpr int kMaxRetries = 20;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The maximum number of retries is hardcoded to 20. While this is a reasonable default, making it configurable via an environment variable (e.g., MC_STORE_CLIENT_SETUP_RETRIES) would provide more flexibility for different deployment environments where more or fewer retries might be appropriate. You can use the GetEnvOr helper from utils.h for this.

Suggested change
constexpr int kMaxRetries = 20;
const int kMaxRetries = GetEnvOr<int>("MC_STORE_CLIENT_SETUP_RETRIES", 20);

// conflict), release port and retry with a different port
LOG(WARNING) << "Failed to create client on port " << port
<< ", retry " << (retry + 1) << "/" << kMaxRetries;
port_binder_.reset();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The retry loop attempts to create a client immediately after a failure. In high-concurrency scenarios where failures might be due to transient resource contention (like port binding races), immediate retries can contribute to the problem. Adding a small delay between retries would make the process more robust by giving the system time to recover. A simple sleep would be beneficial, and an exponential backoff strategy could be even better for more complex scenarios.

            port_binder_.reset();
            std::this_thread::sleep_for(std::chrono::milliseconds(100));

@codecov-commenter
Copy link

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 28.20513% with 28 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
mooncake-store/src/real_client.cpp 28.20% 28 Missing ⚠️

📢 Thoughts on this report? Let us know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants