Skip to content

[model-gateway] optimize worker registry and reduce lock contention in grpc client fetch#15336

Merged
slin1237 merged 1 commit intomainfrom
metric-n/14
Dec 17, 2025
Merged

[model-gateway] optimize worker registry and reduce lock contention in grpc client fetch#15336
slin1237 merged 1 commit intomainfrom
metric-n/14

Conversation

@slin1237
Copy link
Copy Markdown
Collaborator

Replace gRPC client RwLock with OnceCell for lock-free access

The grpc_client field was using Arc<RwLock<Option<Arc<GrpcClient>>>> which required acquiring a tokio RwLock on every single request just to get the cached client reference.

Changed to Arc<OnceCell<Arc<GrpcClient>>>:

  • First request initializes the client (one-time lock)
  • All subsequent requests are completely lock-free
  • OnceCell::get() is just a pointer read after initialization

This eliminates the main source of contention under high concurrency for the gRPC router path where get_grpc_client() is called per-request.

Change get_by_model to return Arc<[Arc<dyn Worker>]> for true O(1) reads

Previously get_by_model returned Vec<Arc> which required calling .to_vec() on the immutable snapshot - O(n) Arc clones on every call.

Now returns Arc<[Arc]> directly - just an atomic refcount bump.
This is the fastest possible read path with zero contention:

  • No locks acquired
  • No memory allocation
  • No cloning of worker references
  • Single atomic increment

Callers that just iterate (.iter(), .is_empty(), .len()) work unchanged via Deref. Only callers that need owned Vec call .to_vec() explicitly.

Checklist

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @slin1237, 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 performance and reduces lock contention within the model gateway by optimizing critical data access patterns. It focuses on two main areas: making gRPC client access lock-free after initial setup and improving the efficiency of worker lookups in the registry. By leveraging Rust's OnceCell and immutable Arc snapshots, the changes aim to provide faster, contention-free access to shared resources, particularly under high concurrency, leading to a more responsive and scalable system.

Highlights

  • gRPC Client Optimization: Replaced Arc<RwLock<Option<Arc<GrpcClient>>>> with Arc<OnceCell<Arc<GrpcClient>>> for the gRPC client field. This change eliminates the need for acquiring a tokio::RwLock on every request, making subsequent client accesses lock-free after the initial lazy initialization.
  • Worker Registry Read Performance: Modified WorkerRegistry::get_by_model to return Arc<[Arc<dyn Worker>]> instead of Vec<Arc<dyn Worker>>. This provides true O(1) lock-free reads for worker lists associated with a model, as it only involves an atomic refcount bump rather than O(n) Arc clones or memory allocations.
  • Copy-on-Write for Worker Registry Updates: Implemented copy-on-write semantics for add_worker and remove_worker operations in the WorkerRegistry's model index. This ensures that read operations remain lock-free by creating new immutable snapshots of worker lists upon modification.
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
Copy Markdown
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 excellent performance optimizations by reducing lock contention in two key areas. First, it replaces RwLock with OnceCell for gRPC client caching, which provides lock-free access after the initial creation. Second, it refactors the WorkerRegistry to use immutable Arc<[T]> snapshots for model-to-worker mappings, enabling O(1) lock-free reads. The implementation is clean, idiomatic, and demonstrates a strong understanding of concurrent programming patterns in Rust. The copy-on-write strategy for registry updates is a suitable trade-off for the expected read-heavy workload. I have one suggestion to improve the documentation of a behavioral change.

Comment on lines 758 to 766
async fn reset_grpc_client(&self) -> WorkerResult<()> {
match self.metadata.connection_mode {
ConnectionMode::Http => Ok(()),
ConnectionMode::Grpc { .. } => {
let mut client_guard = self.grpc_client.write().await;
if client_guard.is_some() {
tracing::info!("Resetting gRPC client for worker: {}", self.metadata.url);
*client_guard = None;
}
Ok(())
}
}
// OnceCell doesn't support resetting. This is intentional for lock-free performance.
// If a connection fails, the worker should be removed and re-added.
tracing::debug!(
"reset_grpc_client called for {} (no-op with OnceCell)",
self.metadata.url
);
Ok(())
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

This change to make reset_grpc_client a no-op is a significant behavioral change. While the code comment explains the rationale well, it would be beneficial to also document this change in the pull request description. This ensures that other developers are aware that the strategy for handling failed gRPC connections has shifted from resetting the client to removing and re-adding the worker, which is a key design decision.

The grpc_client field was using Arc<RwLock<Option<Arc<GrpcClient>>>>
which required acquiring a tokio RwLock on every single request just
to get the cached client reference.

Changed to Arc<OnceCell<Arc<GrpcClient>>>:
- First request initializes the client (one-time lock)
- All subsequent requests are completely lock-free
- OnceCell::get() is just a pointer read after initialization

This eliminates the main source of contention under high concurrency
for the gRPC router path where get_grpc_client() is called per-request.

Change get_by_model to return Arc<[Arc<dyn Worker>]> for true O(1) reads

Previously get_by_model returned Vec<Arc<dyn Worker>> which required
calling .to_vec() on the immutable snapshot - O(n) Arc clones on every call.

Now returns Arc<[Arc<dyn Worker>]> directly - just an atomic refcount bump.
This is the fastest possible read path with zero contention:
- No locks acquired
- No memory allocation
- No cloning of worker references
- Single atomic increment

Callers that just iterate (.iter(), .is_empty(), .len()) work unchanged
via Deref. Only callers that need owned Vec call .to_vec() explicitly.
@slin1237 slin1237 merged commit 53e1519 into main Dec 17, 2025
59 checks passed
@slin1237 slin1237 deleted the metric-n/14 branch December 17, 2025 18:49
Prozac614 pushed a commit to Prozac614/sglang that referenced this pull request Dec 23, 2025
jiaming1130 pushed a commit to zhuyijie88/sglang that referenced this pull request Dec 25, 2025
YChange01 pushed a commit to YChange01/sglang that referenced this pull request Jan 13, 2026
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.

1 participant