Skip to content

feat: Implement Least Request Load Balancing Policy (gRFC A48)#2651

Open
emil10001 wants to merge 9 commits into
grpc:masterfrom
emil10001:feat-least-request
Open

feat: Implement Least Request Load Balancing Policy (gRFC A48)#2651
emil10001 wants to merge 9 commits into
grpc:masterfrom
emil10001:feat-least-request

Conversation

@emil10001

Copy link
Copy Markdown
Member

Implements the "all weights equal" Least Request Load Balancing policy in gRPC-Rust, in compliance with gRFC A48. The Least Request policy improves tail latencies in heterogeneous environments by tracking active request counts per endpoint and directing new requests to the backend with the lowest load.

Detailed Changes:

  1. Core Load Balancing Policy (least_request.rs):

    • Defined LeastRequestLoadBalancingConfig to parse and validate the choiceCount config parameter (default = 2, clamped from 2 to 10).
    • Implemented LeastRequestBuilder registering policy name least_request_experimental.
    • Implemented LeastRequestPolicy managing endpoint-level connections via ChildManager children delegating to pick_first.
    • Maintained a persistent mapping of weak subchannel references to active request counters (subchannel_counters) so that outstanding request metrics survive picker updates and name re-resolutions.
    • Implemented LeastRequestPicker utilizing a random sampling selection algorithm over choice_count subchannels.
  2. Active Request Cancellation Safety:

    • Identified and resolved a request counter leak bug where async task cancellations during dyn_invoke.await dropped the Pick closure without calling it.
    • Implemented a custom, defusable ActiveRequestGuard using an AtomicBool inside LeastRequestPicker::pick. The guard guarantees that the active request count is decremented upon drop if the picker's on_complete callback is never invoked.
  3. Channel & Service Config Integration:

    • Registered the builder with the global LB registry in Channel::new inside channel.rs.
    • Added CallbackRecvStream wrapping the stream in the channel's Invoke implementation to trigger on_complete callbacks when client streams are completed or dropped.
    • Added LeastRequest variant to LbPolicyType enum in service_config.rs.
    • Mapped LbPolicyType::LeastRequest configuration inside ResolverChannelController::update in channel.rs.
  4. Test Additions & Verification:

    • Added comprehensive unit tests in least_request.rs covering configuration parsing/clamping/validation, least request selection, tie-breaking, fewer subchannels than choice count, and cancellation drop-guard safety.
    • Modified the InMemoryResolver in inmemory/mod.rs to dynamically set the LeastRequest load-balancing policy based on target URI path prefixes.
    • Wrote a robust E2E integration test test_in_memory_least_request_load_balancing in inmemory/mod.rs verifying dynamic load balancing across multiple in-memory backends concurrently.

Motivation

Solution

@dfawley dfawley left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the PR! I haven't looked at the tests yet, but here's a first round of review comments.

#[default]
PickFirst,
RoundRobin,
LeastRequest,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a pre-defined list of LB policies limited to just PF and RR. But I think we can do this for now if we put a TODO to remove. cc @nathanielford for when he implements support for the newer field that lets you specify any policy.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think I'd prefer to drop it now. It can be added back if it makes sense down the road.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Huh, it won't build without this being there. I've put the TODO in.

Comment thread grpc/src/inmemory/mod.rs
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment on lines +152 to +154
.state
.picker
.pick(&crate::core::RequestHeaders::default())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We should not be making picks for fake RPCs. If we can't map via the child itself, then we'll need another way to retrieve its active subchannel.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think this has been addressed.

Comment on lines +170 to +172
// Clean up stale counters
self.subchannel_counters
.retain(|weak, _| weak.upgrade().is_some());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this would be better if it reused the known-active subchannels that we got above instead of keeping all the ones that happen to still upgrade.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think I've addressed this.

}
let aggregate_state = self.child_manager.aggregate_states();

if aggregate_state == ConnectivityState::Ready {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Optional: maybe let picker = if ... and send the update commonly between the if/else.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The logic around this was changed, updated behavior looks reasonable to me based on other feedback.

Comment on lines +184 to +191
let picker = self
.child_manager
.children()
.find(|cs| cs.state.connectivity_state == aggregate_state)
.map(|cs| cs.state.picker.clone())
.unwrap_or_else(|| {
Arc::new(crate::client::load_balancing::QueuingPicker) as Arc<dyn Picker>
});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What picker is coming out of this? Is it just the first child whose state is the same as the aggregate state? We should round-robin over all of those children that match instead. You should ideally share the existing RoundRobin picker for this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This has been updated to handle an empty state, a case where there's only 1, and a case where we use the existing RoundRobin picker. It could possibly be simplified further to drop the case where there's only 1.

@emil10001

Copy link
Copy Markdown
Member Author

/gemini review

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

Copy link
Copy Markdown

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 new "least request" load balancing policy (least_request.rs) to the gRPC client, integrates it into the channel controller and service configuration, and adds comprehensive unit and integration tests. The code review feedback identifies several critical improvement opportunities: a bug where configuration updates (such as choice_count) are not propagated to the active picker because update_picker returns early when child states are unchanged; an issue where parent attributes are discarded when sharding resolver updates for child policies; and a recommendation to sample distinct subchannels (without replacement) to maximize the effectiveness of the "power of two choices" algorithm.

Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
Comment thread grpc/src/client/load_balancing/least_request.rs
Comment thread grpc/src/client/load_balancing/least_request.rs Outdated
emil10001 added 2 commits June 2, 2026 15:41
Implements the "all weights equal" Least Request Load Balancing policy in
gRPC-Rust, in compliance with gRFC A48. The Least Request policy improves tail
latencies in heterogeneous environments by tracking active request counts per
endpoint and directing new requests to the backend with the lowest load.

Detailed Changes:

1. Core Load Balancing Policy (`least_request.rs`):
   - Defined `LeastRequestLoadBalancingConfig` to parse and validate the
     `choiceCount` config parameter (default = 2, clamped from 2 to 10).
   - Implemented `LeastRequestBuilder` registering policy name
     `least_request_experimental`.
   - Implemented `LeastRequestPolicy` managing endpoint-level connections
     via `ChildManager` children delegating to `pick_first`.
   - Maintained a persistent mapping of weak subchannel references to active
     request counters (`subchannel_counters`) so that outstanding request
     metrics survive picker updates and name re-resolutions.
   - Implemented `LeastRequestPicker` utilizing a random sampling selection
     algorithm over `choice_count` subchannels.

2. Active Request Cancellation Safety:
   - Identified and resolved a request counter leak bug where async task
     cancellations during `dyn_invoke.await` dropped the `Pick` closure
     without calling it.
   - Implemented a custom, defusable `ActiveRequestGuard` using an `AtomicBool`
     inside `LeastRequestPicker::pick`. The guard guarantees that the active
     request count is decremented upon drop if the picker's `on_complete`
     callback is never invoked.

3. Channel & Service Config Integration:
   - Registered the builder with the global LB registry in `Channel::new`
     inside `channel.rs`.
   - Added `CallbackRecvStream` wrapping the stream in the channel's
     `Invoke` implementation to trigger `on_complete` callbacks when client
     streams are completed or dropped.
   - Added `LeastRequest` variant to `LbPolicyType` enum in `service_config.rs`.
   - Mapped `LbPolicyType::LeastRequest` configuration inside
     `ResolverChannelController::update` in `channel.rs`.

4. Test Additions & Verification:
   - Added comprehensive unit tests in `least_request.rs` covering configuration
     parsing/clamping/validation, least request selection, tie-breaking,
     fewer subchannels than choice count, and cancellation drop-guard safety.
   - Modified the `InMemoryResolver` in `inmemory/mod.rs` to dynamically set
     the `LeastRequest` load-balancing policy based on target URI path prefixes.
   - Wrote a robust E2E integration test `test_in_memory_least_request_load_balancing`
     in `inmemory/mod.rs` verifying dynamic load balancing across multiple
     in-memory backends concurrently.
@emil10001 emil10001 force-pushed the master branch 2 times, most recently from 7a5c94e to c16927a Compare June 26, 2026 17:54
@emil10001

Copy link
Copy Markdown
Member Author

Ok, I believe all of the comments have been addressed, and there aren't any more merge conflicts. However, testing is currently failing for some apparently unrelated reason, it's complaining about TLS, which I don't have in my PR. There also appear to be some CI failures around unresolved dependencies which are also unrelated to my PR.

@emil10001 emil10001 requested a review from dfawley June 27, 2026 00:12
Comment on lines +73 to +78
impl<T> Child<T> {
pub fn subchannels(&self) -> impl Iterator<Item = Arc<dyn Subchannel>> + '_ {
self.subchannels.iter().filter_map(|weak| weak.upgrade())
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Sorry, I should have caught this sooner.

Please see the updates to the least-request gRFC in A61:

https://github.com/grpc/proposal/blob/master/A61-IPv4-IPv6-dualstack-backends.md#wrr-in-javago (and the subsequent section about least-request specifically)

We should not be looking at the subchannels of the children at all. We should store the request counts for the endpoint instead.

Comment on lines +403 to +405
if state.active.swap(false, Ordering::Relaxed) {
state.counter.fetch_sub(1, Ordering::Relaxed);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is redundant logic. The drop for state already does this. So you can just do either:

Suggested change
if state.active.swap(false, Ordering::Relaxed) {
state.counter.fetch_sub(1, Ordering::Relaxed);
}
let _ = state;

Which captures state in the closure and its drop will be run automatically when the closure finishes.

Or:

Suggested change
if state.active.swap(false, Ordering::Relaxed) {
state.counter.fetch_sub(1, Ordering::Relaxed);
}
drop(state);

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.

2 participants