Skip to content

[type: bug] fix(loadbalancer): count outstanding requests in leastActive - #7986

Merged
Aias00 merged 1 commit into
apache:masterfrom
hanzhe-one:fix/least-active-outstanding-requests
Oct 23, 2026
Merged

Aias00 merged 1 commit into
apache:masterfrom
hanzhe-one:fix/least-active-outstanding-requests

Conversation

@hanzhe-one

Copy link
Copy Markdown
Contributor

Fixes #7972

Problem

LeastActiveLoadBalance kept a private countMap keyed by domain. The counter was incremented on every selection and never decremented, and each entry started at Long.MIN_VALUE. Two consequences:

  • Completed requests kept influencing the choice. The comparison was cumulative selections, not concurrent active requests, so an upstream that had served more requests stayed "busier" forever regardless of how much work it currently had.
  • A newly added upstream received a catch-up burst. A fresh domain started at 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 over a,b,c) returns 50 on current master.

Changes

shenyu-loadbalancer

  • LeastActiveLoadBalance now reads Upstream#getInflight() — the same counter the p2c balancer 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. The countMap, its recycling pass and the ActiveCount class 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 different group/version were tracked separately by the old map, and the per-Upstream inflight counter preserves that by construction (Upstream instances are per-identity in UpstreamCacheManager).

shenyu-plugin-divide

  • DividePlugin reserves the selected upstream for leastActive and releases it in doFinally, so success, error and cancellation all release the accounting. The half-open probe path reuses the same counter for p2c already and needs no extra reservation here.

shenyu-plugin-httpclient

  • DefaultRetryStrategy#resend does the same for a failover attempt, so a retried request is not invisible to the balancer while it runs.

Observable behavior changes

  • leastActive now 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.
  • Upstreams that call LeastActiveLoadBalance but do not maintain inflight (websocket, dubbo/grpc gray routing, and any external caller of LoadBalanceData) see every upstream at the same baseline (1, the Upstream default) 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 of shenyu-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

  • Websocket and dubbo/grpc gray routing still call the balancer without maintaining inflight; they now fall back to weight instead of the previous cumulative-selection behavior. Extending the counter to those paths is a separate change.
  • No integration/e2e coverage was added; the regression is fully expressed in the unit tests above.

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 Aias00 left a comment

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.

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:

  1. maintain inflight in the websocket and dubbo paths as well (reserve before forward, release in doFinally), so the name keeps meaning what it says; or
  2. keep this PR scoped to divide and file a tracking issue that names those two plugins explicitly, and mention it in RELEASE-NOTES.md under 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()) matches LoadBalanceEnum.LEAST_ACTIVITY.getName() = "leastActive", and the guard sits after the null check, so it also covers the half-open probe branch (where doSelect never runs).
  • Reserve happens in exactly one place (the plugin, not doSelect), so no double count; the release is doFinally, so success, error and cancellation are all covered - the cancellation test that asserts 3 -> 2 proves it.
  • Retry: DefaultRetryStrategy increments the retried upstream for leastActive and releases it in doFinally, which pairs correctly with divide releasing only the original. This is the same shape as #7982 and does not conflict with it.
  • LeastActiveLoadBalance.ActiveCount has no other reference in the repository, so deleting it does not break tests elsewhere.
  • testWeightBreaksTiesAmongLeastActiveUpstreams correctly derives 10 vs 100 effective weight from warmup; the 400-iteration bound is safe against the ~9% expected share.

Nits

  • testInflightCountIsReadNotReserved is the most valuable test here; consider also asserting that doSelect on a single-element list stays untouched, since AbstractLoadBalancer.select short-circuits and never reaches doSelect (same caveat as #7980/#7987).
  • The sameWeight update keeps the i > 0 guard from ShortestResponseLoadBalancer, which avoids the false sameWeight = false on the first index. Good - no action needed.

@Aias00
Aias00 merged commit dc59d7d into apache:master Oct 23, 2026
31 of 32 checks passed
@Aias00

Aias00 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

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.

dmsolr pushed a commit that referenced this pull request Oct 23, 2026
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.
dmsolr pushed a commit that referenced this pull request Oct 25, 2026
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).
dmsolr pushed a commit that referenced this pull request Oct 25, 2026
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.
@Aias00 Aias00 added this to the 2.7.2 milestone Nov 13, 2026
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.

[BUG] leastActive counts lifetime selections instead of active requests and overloads newly added upstreams

2 participants