fix(loadbalancer): track inflight for shortestResponse (#7973) #7987
Verdict: the accounting is right on the direct path, but the failover path leaks - please extend the fix
The core of this change is correct and the two increments do not double count:
ShortestResponseLoadBalancer.doSelect increments for the normal selection path;DividePlugin.forwardSelected increments only in the candidates.isProbe() branch, which bypasses LoadbalancerUtils and therefore doSelect. That is the same split P2C already relies on (increment inside P2cLoadBalancer.doSelect, plus a separate increment for the half-open probe), so the shape is consistent.releaseShortestResponseInflight using updateAndGet(current -> current > 0 ? current - 1 : 0) is a reasonable floor guard, and the test covers success, error and cancellation plus the already-zero case.Blocking: retries re-select through the load balancer and leak an increment
DefaultRetryStrategy.resend picks the standby upstream through LoadbalancerUtils, so with shortestResponse it now runs ShortestResponseLoadBalancer.doSelect and increments that upstream. Divide's doFinally only holds the initially selected upstream, so:
standby -> standby.inflight++doFinally decrements the original upstreamstandby never gets its decrement back. Each failed-and-retried request leaks +1 on the standby, which permanently inflates succeededAverageElapsed * inflight and eventually drives all traffic away from a healthy upstream. This is exactly the defect #7982 fixes for P2C, and that PR's guard is scoped to P2C only:
if (LoadBalanceEnum.P2C.getName().equals(loadBalance)) {
retryResponse = retryResponse.doFinally(signalType -> upstream.getInflight().decrementAndGet());
}
Please do one of:
1. add the same release for LoadBalanceEnum.SHORTEST_RESPONSE in DefaultRetryStrategy (mirroring #7982, including its RetryStrategyTest case), and note in both PRs that the guard must cover both load balancers; or
2. if you would rather land the retry part separately, say so explicitly in the description and keep this PR's scope to the non-retry path - but then the leak exists in master as soon as this merges, so option 1 is preferred.
Non-blocking
ShortestResponseLoadBalancer still inherits AbstractLoadBalancer.select, which short-circuits for a single upstream and never calls doSelect. A single-upstream selector therefore never counts inflight, so shortestResponse silently degrades to "always pick it" (harmless in that case, but inconsistent with #7980, which added an explicit select override on P2cLoadBalancer for exactly this reason). Consider the same override here for symmetry.assertEquals(100, fast.getInflight().get() + slow.getInflight().get() - 2), relies on the two set(1) baselines. It works, but fast.getInflight().get() + slow.getInflight().get() compared against 2 + 100 would read more obviously.Thanks for the review @Aias00.
Blocking: #7982 isn't on master yet (it was merged into fix/p2c-singleton-inflight), so there was no P2C guard to extend. DefaultRetryStrategy now releases the failover standby's inflight once in doFinally for shortestResponse (success, error and cancellation), and the count can't go below zero. The standby was already incremented during selection, so this path doesn't increment again. P2C is left to #7982; when it lands on master, please extend this same guard to cover both rather than adding a second doFinally. RetryStrategyTest covers a multi-candidate retry and a single standby.
Non-blocking: ShortestResponseLoadBalancer.select now counts inflight for a single-upstream list, same as the P2C override in #7980. The traffic test now compares fast.getInflight().get() + slow.getInflight().get() with 2 + 100.
Branch rebased onto current master. Tests: ShortestResponseLoadBalancerTest 4 passed, DividePluginTest 15 passed, RetryStrategyTest 27 passed; checkstyle and RAT clean.
The inflight accounting is correctly paired. I traced all four paths:
ShortestResponseLoadBalancer.doSelect returns through trackInflight(...) on every branch, so selection reserves exactly once.AbstractLoadBalancer.select returns before doSelect, so the select override increments for that case only — guarded by upstreamList.size() == 1, so there is no double count when doSelect did run.DividePlugin.forwardSelected takes breakeredUpstreamList.get(0) directly without calling the load balancer, so the new SHORTEST_RESPONSE increment there is needed and is not a duplicate (it sits inside the candidates.isProbe() branch, not the normal path).resolveWithAffinity skips selection, so the added increment is again the only reservation.Release side matches: forwardWithCircuitBreaker decrements once in doFinally, and DefaultRetryStrategy releases the standby attempt it selected, with updateAndGet(current -> current > 0 ? current - 1 : 0) preventing the counter from going negative if a signal fires twice.
This is consistent with the model already merged for P2C in #7980, and the SHORTEST_RESPONSE.equals(...) normalisation on the release branch is a nice touch.
LGTM.
[P2] Pair the new selection reservation on the WebSocket path too
The shared shortestResponse balancer now reserves inflight on every selection, but the corresponding release is added only to Divide and HTTP retry paths. WebSocketPlugin also uses this balancer through LoadbalancerUtils.getForExchange; its lifecycle wrapper currently applies only to leastActivity, so shortestResponse reservations are never released there, including after handshake termination.
I reproduced this with this PR's ShortestResponseLoadBalancer and the existing WebSocketPlugin test fixture, with the WebSocket service completing each handshake: three additional completed handshakes increased inflight by three instead of returning to the baseline. This leaves stale counts on cached upstreams, including if the selector later switches to leastActivity.
Please pair the reservation with the WebSocket lifecycle, including failed upgrades and session termination, or keep the reservation scoped to callers that implement the matching release. Add a WebSocket regression test for shortestResponse.
Code review of commit 5a5372c15ff7aa174996f561a3c08514e8893161.
[P2] Pair the new selection reservation on the WebSocket path too
The attached finding was reproduced locally with the PR code and the relevant runtime handler/processor. This is targeted validation, not a full PR test-suite run.
Thanks @Aias00, good catch. Addressed in 94cc5dbcceaa495041b0316674599b13a01efc56.
The WebSocket path now uses the same session lifecycle wrapper (InflightWebSocketHandler) for shortestResponse as for leastActive. Since ShortestResponseLoadBalancer already reserves inflight at selection, the wrapper does not reserve again for it; it only releases that reservation exactly once:
An open session keeps the reservation until it terminates. leastActive behaviour is unchanged.
WebSocketPluginTest now checks that three completed handshakes and a failed handshake return inflight to baseline, and that an open session holds the reservation until cancel/complete/error (11 tests pass, checkstyle clean).
The shortestResponse reservation is paired with release on HTTP, retry and WebSocket lifecycle paths. The earlier WebSocket leak finding is addressed by the inflight lifecycle handler, including termination/cancellation. No remaining actionable finding.
Validation: 72 focused load-balancer/HTTP/Divide tests passed; an additional WebSocket reactor run passed 15 tests (including 4 repeated load-balancer tests). No GitHub check rollup was available at the initial snapshot; required CI remains a merge gate. Apache RAT passed locally. Scope: source review and targeted verification; full integration/e2e suites were not run locally for this review.
Stream Agent analysis
PR #7987 fixes inflight tracking for the shortestResponse load balancer algorithm. The bug was that shortestResponse did not increment inflight on selection, causing a fast upstream to accumulate all requests while its queue grew. The fix adds inflight increments at all selection points (normal selection, single-candidate fast path, half-open probes, sticky-session binding hits, and hash-based picks) and ensures exactly-once release via a guarded decrement that never goes negative. WebSocket upgrades now track the reservation through a state machine so the handshake and the long-lived session share one paired reservation.
Evidence
Recommended next steps
Scope: captured diff and GitHub check metadata only; no local tests were executed.
Task: 044e8695-4ecb-4580-818b-87779b78db94 · Commit: 8f2faf03966af981f89c87deaf10959aef70a6f0
<!-- stream-agent-review:047deceeb2bf58fce03ec712b0ec8ae1378f5701c05d87f2c87ce1d5b2526bda -->
Review verdict: PASS
Complete diff coverage, all CI checks passed, and no concrete blocking defects. The implementation correctly addresses issue #7973 by ensuring shortestResponse tracks outstanding requests at every selection entry point and releases exactly once on all terminal paths (success, error, cancellation).
Publication: APPROVE (EXPLICIT_PASS)
Aias00
markjoin123
Fixes #7973
shortestResponsenow accounts for outstanding requests. Selection incrementsinflight, and Divide decrements it exactly once on success, error, or cancellation, without going negative. A historically fast upstream no longer keeps every request while its queue grows. A half-open probe that skips the balancer incrementsinflightas well, so the release stays paired.Tests:
ShortestResponseLoadBalancerTest: the issue's repro (fast avg 10 vs slow avg 100, no completions between selections) no longer sends all requests to the fast upstream; each selection incrementsinflightonce.DividePluginTest: after success, error and cancel,inflightreturns to its baseline; a zero count stays zero.Make sure that:
./mvnw clean install -Dmaven.javadoc.skip=true.