Skip to content

fix(loadbalancer): track inflight for shortestResponse (#7973) - #7987

Merged
Aias00 merged 3 commits into
apache:masterfrom
markjoin123:cursor/shortest-response-inflight-7973-3715
Nov 13, 2026
Merged

Aias00 merged 3 commits into
apache:masterfrom
markjoin123:cursor/shortest-response-inflight-7973-3715

Conversation

@markjoin123

Copy link
Copy Markdown
Contributor

Fixes #7973

shortestResponse now accounts for outstanding requests. Selection increments inflight, 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 increments inflight as 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 increments inflight once.
  • DividePluginTest: after success, error and cancel, inflight returns to its baseline; a zero count stays zero.
  • Checkstyle and Apache RAT pass on the affected modules.

Make sure that:

  • You have read the contribution guidelines.
  • You submit test cases (unit or integration tests) that back your changes.
  • Your local test passed ./mvnw clean install -Dmaven.javadoc.skip=true.

@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 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:

  • request fails -> failover selects standby -> standby.inflight++
  • the response terminates -> doFinally decrements the original upstream

standby 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.
  • The new test's last assertion, 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.

@cursor
cursor Bot force-pushed the cursor/shortest-response-inflight-7973-3715 branch from e623b24 to b130d14 Compare October 23, 2026 05:18
@markjoin123

Copy link
Copy Markdown
Contributor Author

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.

@cursor
cursor Bot force-pushed the cursor/shortest-response-inflight-7973-3715 branch from b130d14 to 5a5372c Compare October 26, 2026 09:22
Aias00
Aias00 previously approved these changes Oct 26, 2026

@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.

The inflight accounting is correctly paired. I traced all four paths:

  • Normal selection (>1 candidate): ShortestResponseLoadBalancer.doSelect returns through trackInflight(...) on every branch, so selection reserves exactly once.
  • Single candidate: 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.
  • Half-open probe: 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).
  • Sticky affinity hit: 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.

@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.

Code review of commit 5a5372c.

[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.

@markjoin123

Copy link
Copy Markdown
Contributor Author

Thanks @Aias00, good catch. Addressed in 94cc5db.

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:

  • when the handshake completes or fails without a session being started, or
  • when the session ends (normal completion, failure, or cancellation).

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).

Aias00
Aias00 previously approved these changes Oct 30, 2026

@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.

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.

ShortestResponse increments inflight when an upstream is selected, and
Divide releases that count once on success, error, or cancellation
without going negative. A historically fast upstream no longer keeps
every request while its queue grows.

Fixes apache#7973
Failover re-selects the standby through the load balancer, which increments
its inflight. With a Divide attempt owner, that reservation moves to the
standby and is released with the attempt: immediately on failure, or when
the response body finishes on success. Without an owner, the retry completion
releases the standby once, the same way P2C does.
Selection already reserved the upstream. Release that reservation when the
session ends, or when the handshake finishes without starting a session.
@cursor
cursor Bot force-pushed the cursor/shortest-response-inflight-7973-3715 branch from 94cc5db to 8f2faf0 Compare November 11, 2026 01:04

@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.

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

  • Full diff (35,635 chars) read across all pages until has_more=false at offset 35635.
  • CI passed: policy (7987), discover, and issue-spec-policy all completed successfully.
  • Key fix verified: ShortestResponseLoadBalancer.select() now increments inflight for single candidate (line 45), DividePlugin adds reserveProbe() for half-open probes and increments for binding hits, releaseShortestResponseInflight() uses updateAndGet to prevent negative counts (line 552), WebSocketPlugin uses AtomicInteger state machine for exactly-once release.

Recommended next steps

Scope: captured diff and GitHub check metadata only; no local tests were executed.

Task: 044e8695-4ecb-4580-818b-87779b78db94 · Commit: 8f2faf03966af981f89c87deaf10959aef70a6f0

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 Aias00 added this to the 2.7.3 milestone Nov 13, 2026
@Aias00
Aias00 merged commit aacca7e into apache:master Nov 13, 2026
42 checks passed
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] shortestResponse does not track inflight requests and ignores growing queue depth

2 participants