opt(lb): optimize the performance of weighted_random load balancer #569
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Motivation
Volo provides a weighted random load balancer with CDF (cumulative distribution function) or as known as prefix sum method. But after reviewing the code, I found some optimize point to make volo having better performance:
pick_one
method is consuming random weight by iterating each instance from first to last, which needs O(n) time. But the prefix sum is an ordered slice, so we could using binary search to find upper bound of random weight which only need O(log n) time.Iterator
ofInstancePicker
, each time the upstream call failed, we need to copy a new slice and then perform weighted random sampling without replacement. But since each instance is without replacement, it will act as unweighted random sampling, but always need O(n) to calculate the prefix sum of weight. Since we are weighted random picked in the first round, we could just using RoundRobin with random picked start position which only need O(1) time and zero memory allocation.