Repository navigation
[type: bug] fix(loadbalancer): count outstanding requests in leastActive - #7986
Conversation
LeastActiveLoadBalance kept a private per-domain counter that was only ever incremented on selection. It compared lifetime selections rather than concurrent active requests, so completed requests kept skewing the choice and a newly added upstream received a catch-up burst until its counter matched the others; weight and warmup could not protect it. Read the active request count from Upstream#getInflight() instead, which the divide plugin maintains for p2c. The gateway now reserves the selected upstream for leastActive and releases it on success, error and cancellation, in both the first attempt and the failover retry path. Upstreams that share the lowest count are picked by weight, warmup included, which is also what protects a new node. The per-domain count map, its recycling pass and the UpstreamIdentity leastActiveKey are gone: identity-based accounting kept two upstreams with the same address but different group/version apart, and the inflight counter does that by construction. Fixes apache#7972
Aias00
left a comment
There was a problem hiding this comment.
Verdict: the right direction - one blocking design question, otherwise clean
Replacing the per-domain ActiveCount map with the shared Upstream.inflight counter is a genuine improvement: it deletes ~110 lines of bookkeeping, removes the never-decremented counter (the old code only ever increase()d, so "least active" was really "least picked since startup"), removes the 60s recycle sweep, and makes leastActive comparable with P2C and shortestResponse, which already read the same counter. The doSelect rewrite mirrors ShortestResponseLoadBalancer.doSelect (least count, weight/warmup tie-break, random among equals) and is correct, and the test rewrite is much stronger than the reflective countMap poking it replaces.
Blocking question: leastActive now silently degrades to weighted-random outside the divide plugin
getInflight() is only maintained by DividePlugin (plus DefaultRetryStrategy for the retry attempt). LoadbalancerUtils is also used by:
shenyu-plugin-websocket(WebSocketPlugin)shenyu-plugin-apache-dubbo(ApacheDubboProxyService,ApacheDubboGrayLoadBalance)
With this change, for those plugins every upstream stays at inflight = 0, so leastCount == length, sameWeight is true and the choice becomes plain weighted-random. The old counter at least accumulated per selection there, so this is a behaviour regression for websocket/dubbo users who selected leastActive.
The class javadoc does state the tradeoff ("A caller that does not maintain it sees every upstream at the same baseline and the choice falls back to weight"), which is why I am not hard-blocking on the code itself. But please do one of:
- maintain
inflightin the websocket and dubbo paths as well (reserve before forward, release indoFinally), so the name keeps meaning what it says; or - keep this PR scoped to divide and file a tracking issue that names those two plugins explicitly, and mention it in
RELEASE-NOTES.mdunder behaviour changes.
Silently changing the algorithm for two plugins is the kind of thing that shows up later as an unexplained traffic-distribution change.
Checked and fine
LEAST_ACTIVE.equals(ruleHandle.getLoadBalance())matchesLoadBalanceEnum.LEAST_ACTIVITY.getName()="leastActive", and the guard sits after the null check, so it also covers the half-open probe branch (wheredoSelectnever runs).- Reserve happens in exactly one place (the plugin, not
doSelect), so no double count; the release isdoFinally, so success, error and cancellation are all covered - the cancellation test that asserts3 -> 2proves it. - Retry:
DefaultRetryStrategyincrements the retried upstream forleastActiveand releases it indoFinally, which pairs correctly with divide releasing only the original. This is the same shape as #7982 and does not conflict with it. LeastActiveLoadBalance.ActiveCounthas no other reference in the repository, so deleting it does not break tests elsewhere.testWeightBreaksTiesAmongLeastActiveUpstreamscorrectly derives 10 vs 100 effective weight from warmup; the 400-iteration bound is safe against the ~9% expected share.
Nits
testInflightCountIsReadNotReservedis the most valuable test here; consider also asserting thatdoSelecton a single-element list stays untouched, sinceAbstractLoadBalancer.selectshort-circuits and never reachesdoSelect(same caveat as #7980/#7987).- The
sameWeightupdate keeps thei > 0guard fromShortestResponseLoadBalancer, which avoids the falsesameWeight = falseon the first index. Good - no action needed.
|
Merged. The websocket / apache-dubbo degradation I mentioned in the review is now tracked in #8004 so it does not get lost — no action needed on this PR. |
Resolve the UpstreamCacheManager conflict between the read-only healthy upstream snapshot model (this branch) and master's legacy gray / canary routing feature (#7986 area). Resolution keeps both intents: - findAllUpstreamListBySelectorId now returns the published read-only snapshot (task.getHealthySnapshot) instead of a per-request new ArrayList copy, so the canary path is zero-copy too. - findUpstreamListBySelectorId keeps master's gray-exclusive narrowing (stream/filter/collect) on top of that snapshot. Safe because every consumer only reads: UpstreamLabelUtils.filter and the fixed CircuitBreakerCandidates.filter both return new lists and never mutate the supplied list. Snapshot publication in UpstreamCheckTask still covers all healthyUpstream mutators (putToMap / removeFromMap / triggerRemoveAll) under the lock, so the snapshot stays authoritative. Verified: ./mvnw -pl shenyu-loadbalancer,shenyu-plugin-divide -am test -> BUILD SUCCESS, including DivideCanaryRoutingTest (11) and DivideUpstreamDataHandlerTest (23) from master, plus the snapshot and circuit-breaker regression tests.
Resolve semantic conflict in DefaultRetryStrategy.resend(): keep the P2C inflight release (#7975/#7982) and master's leastActive reserve/release (#7986) as mutually exclusive branches keyed on the load-balance algorithm. RetryStrategyTest retains all three failover tests (two P2C + one leastActive).
Sync to current master to resolve the stable shenyu-integrated-test-http CI failure (CachePluginTest.testMemoryModle/testRedisModle). Root cause: this branch predated #8079, whose pre-fix CachedResponse.capture() refused to store any response carrying a Vary header, so the cached endpoint was never reused and both requests hit the backend. #8079 keys Vary responses on the selecting request headers instead. Also pulls in the divide/loadbalancer work (#8076, #7172, #7986, #8005, #7821, #8033, #8090). #7172 removeStaleUpstreams reconciles via removeFromMap/triggerRemoveOne, which republish the immutable healthy snapshot under the same lock, so the read-only snapshot model stays correct with no stale retained instances.
Fixes #7972
Problem
LeastActiveLoadBalancekept a privatecountMapkeyed by domain. The counter was incremented on every selection and never decremented, and each entry started atLong.MIN_VALUE. Two consequences:Long.MIN_VALUE, so every subsequent request went to it until its counter caught up with the existing upstreams.getWeight/warmup were never consulted on this path.The reproduction from the issue (100 selections over
a,b, then 50 overa,b,c) returns50on current master.Changes
shenyu-loadbalancerLeastActiveLoadBalancenow readsUpstream#getInflight()— the same counter thep2cbalancer already uses — instead of a private per-domain map. The least active upstream wins; when several share the lowest count they are chosen by weight, warmup included. ThecountMap, its recycling pass and theActiveCountclass are removed.UpstreamIdentity.leastActiveKey()is removed, since only the deleted map used it. Identity-based accounting also had a subtle divergence: two upstreams with the same address but differentgroup/versionwere tracked separately by the old map, and the per-Upstreaminflight counter preserves that by construction (Upstreaminstances are per-identity inUpstreamCacheManager).shenyu-plugin-divideDividePluginreserves the selected upstream forleastActiveand releases it indoFinally, so success, error and cancellation all release the accounting. The half-open probe path reuses the same counter forp2calready and needs no extra reservation here.shenyu-plugin-httpclientDefaultRetryStrategy#resenddoes the same for a failover attempt, so a retried request is not invisible to the balancer while it runs.Observable behavior changes
leastActivenow distributes by active requests and weight. Traffic proportions between equally idle upstreams follow weight/warmup instead of strict round-robin alternation. That is the documented contract of least-active, but it is a visible change for a selector that relied on the old alternation.LeastActiveLoadBalancebut do not maintaininflight(websocket, dubbo/grpc gray routing, and any external caller ofLoadBalanceData) see every upstream at the same baseline (1, theUpstreamdefault) and fall back to weight. They were previously receiving the cumulative-selection behavior, which was not useful for them either; making those paths maintain the counter is out of scope here and tracked separately.UpstreamIdentity.leastActiveKey()is removed from the public surface ofshenyu-loadbalancer. It was added with the old implementation and has no other caller in the repository.Validation
./mvnw -pl shenyu-loadbalancer install— 70 tests, 0 failures../mvnw -pl shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide test— 66 tests, 0 failures../mvnw -pl shenyu-plugin/shenyu-plugin-httpclient test -Dtest=RetryStrategyTest— 25 tests, 0 failures../mvnw -pl shenyu-loadbalancer,shenyu-plugin/shenyu-plugin-httpclient,shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide checkstyle:check— passes.Regression tests were verified against the unmodified code:
LeastActiveLoadBalanceTest— 5 of the 7 tests fail on current master, including the issue's reproduction (the new upstream was selected 50 out of 50 times) and a long-running request whose earlier completed selections mask it (expected pro.jd.com but was baidu.com). They pass with the fix.DividePluginTest#leastActiveInflightShouldBeReleasedOnCancellation— fails on current master (expected 3 but was 2), passes with the fix.RetryStrategyTest#testFailoverReservesAndReleasesLeastActiveAccounting— fails on current master (expected 2 but was 1), passes with the fix.Not covered here
inflight; they now fall back to weight instead of the previous cumulative-selection behavior. Extending the counter to those paths is a separate change.