[model-gateway] optimize worker registry and reduce lock contention in grpc client fetch#15336
[model-gateway] optimize worker registry and reduce lock contention in grpc client fetch#15336
Conversation
Summary of ChangesHello @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 Highlights
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
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.
| 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(()) | ||
| } |
There was a problem hiding this comment.
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.
be27e44 to
465d1c9
Compare
…n grpc client fetch (sgl-project#15336)
…n grpc client fetch (sgl-project#15336)
…n grpc client fetch (sgl-project#15336)
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>>>:OnceCell::get()is just a pointer read after initializationThis 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_modelto returnArc<[Arc<dyn Worker>]>for true O(1) readsPreviously 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:
Callers that just iterate (.iter(), .is_empty(), .len()) work unchanged via Deref. Only callers that need owned Vec call .to_vec() explicitly.
Checklist