Skip to content

Commit aacca7e

Browse files
authored
fix(loadbalancer): track inflight for shortestResponse (#7973) (#7987)
* fix(loadbalancer): track inflight for shortestResponse (#7973) 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 #7973 * fix(loadbalancer): release shortestResponse inflight on retry 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. * fix(websocket): release shortestResponse inflight with the session Selection already reserved the upstream. Release that reservation when the session ends, or when the handshake finishes without starting a session.
1 parent 00cb35a commit aacca7e

9 files changed

Lines changed: 369 additions & 29 deletions

File tree

‎shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/ShortestResponseLoadBalancer.java‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import org.apache.shenyu.spi.Join;
2323

2424
import java.util.List;
25+
import java.util.Objects;
2526
import java.util.concurrent.ThreadLocalRandom;
2627
import java.util.concurrent.atomic.AtomicLong;
2728

@@ -35,6 +36,17 @@
3536
@Join
3637
public class ShortestResponseLoadBalancer extends AbstractLoadBalancer {
3738

39+
@Override
40+
public Upstream select(final List<Upstream> upstreamList, final LoadBalanceData data) {
41+
Upstream picked = super.select(upstreamList, data);
42+
// A single candidate returns before doSelect, so the inflight increment there is skipped
43+
// while Divide still releases it. Count the selection here. See #7980.
44+
if (Objects.nonNull(picked) && upstreamList.size() == 1) {
45+
picked.getInflight().incrementAndGet();
46+
}
47+
return picked;
48+
}
49+
3850
@Override
3951
protected Upstream doSelect(final List<Upstream> upstreamList, final LoadBalanceData data) {
4052
int length = upstreamList.size();
@@ -71,18 +83,23 @@ protected Upstream doSelect(final List<Upstream> upstreamList, final LoadBalance
7183
}
7284

7385
if (shortestCount == 1) {
74-
return upstreamList.get(shortestIndexes[0]);
86+
return trackInflight(upstreamList.get(shortestIndexes[0]));
7587
}
7688
if (!sameWeight && totalWeight > 0) {
7789
long offsetWeight = ThreadLocalRandom.current().nextLong(totalWeight);
7890
for (int i = 0; i < shortestCount; i++) {
7991
int shortestIndex = shortestIndexes[i];
8092
offsetWeight -= weights[shortestIndex];
8193
if (offsetWeight < 0) {
82-
return upstreamList.get(shortestIndex);
94+
return trackInflight(upstreamList.get(shortestIndex));
8395
}
8496
}
8597
}
86-
return upstreamList.get(shortestIndexes[ThreadLocalRandom.current().nextInt(shortestCount)]);
98+
return trackInflight(upstreamList.get(shortestIndexes[ThreadLocalRandom.current().nextInt(shortestCount)]));
99+
}
100+
101+
private Upstream trackInflight(final Upstream upstream) {
102+
upstream.getInflight().incrementAndGet();
103+
return upstream;
87104
}
88105
}

‎shenyu-loadbalancer/src/test/java/org/apache/shenyu/loadbalancer/spi/ShortestResponseLoadBalancerTest.java‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,38 @@ public void testSelectByResponse() {
8484
Assertions.assertEquals(loop, select1 + select2);
8585

8686
}
87+
88+
@Test
89+
public void growingInflightShiftsTrafficAwayFromHistoricallyFastUpstream() {
90+
Upstream fast = Upstream.builder().url("a").weight(1).build();
91+
Upstream slow = Upstream.builder().url("b").weight(1).build();
92+
fast.getSucceeded().set(1);
93+
fast.getSucceededElapsed().set(10);
94+
slow.getSucceeded().set(1);
95+
slow.getSucceededElapsed().set(100);
96+
fast.getInflight().set(1);
97+
slow.getInflight().set(1);
98+
ShortestResponseLoadBalancer balancer = new ShortestResponseLoadBalancer();
99+
int fastHits = 0;
100+
List<Upstream> upstreams = List.of(fast, slow);
101+
LoadBalanceData data = new LoadBalanceData();
102+
for (int i = 0; i < 100; i++) {
103+
if (balancer.select(upstreams, data) == fast) {
104+
fastHits++;
105+
}
106+
}
107+
Assertions.assertTrue(fastHits < 100);
108+
Assertions.assertTrue(fast.getInflight().get() > 1);
109+
Assertions.assertTrue(slow.getInflight().get() > 1);
110+
Assertions.assertEquals(2 + 100, fast.getInflight().get() + slow.getInflight().get());
111+
}
112+
113+
@Test
114+
public void singletonSelectionIncrementsInflightOnce() {
115+
Upstream upstream = Upstream.builder().url("only").weight(1).build();
116+
long before = upstream.getInflight().get();
117+
Upstream picked = new ShortestResponseLoadBalancer().select(List.of(upstream), new LoadBalanceData());
118+
Assertions.assertSame(upstream, picked);
119+
Assertions.assertEquals(before + 1, upstream.getInflight().get());
120+
}
87121
}

‎shenyu-plugin/shenyu-plugin-httpclient/src/main/java/org/apache/shenyu/plugin/httpclient/DefaultRetryStrategy.java‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,11 @@ private Mono<R> resend(final ServerWebExchange exchange,
206206
// Least active compares outstanding requests but does not reserve on select.
207207
upstream.getInflight().incrementAndGet();
208208
reserved = true;
209-
} else if (LoadBalanceEnum.P2C.getName().equals(loadBalance)) {
210-
// P2C selection already incremented the retry target.
209+
} else if (LoadBalanceEnum.P2C.getName().equals(loadBalance)
210+
|| LoadBalanceEnum.SHORTEST_RESPONSE.getName().equals(loadBalance)) {
211+
// P2C and shortestResponse selection already incremented the retry target.
212+
// Do not increment again. An owner releases that reservation with the attempt;
213+
// without one, the completion callback below releases it once.
211214
reserved = true;
212215
}
213216
if (ownerPresent) {

‎shenyu-plugin/shenyu-plugin-httpclient/src/test/java/org/apache/shenyu/plugin/httpclient/RetryStrategyTest.java‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,98 @@ void testLegacyRetryAccountingIsPreservedWithoutAnOwner() {
492492
assertEquals(1, standby.getInflight().get());
493493
}
494494

495+
@Test
496+
void testFailoverReleasesShortestResponseInflight() {
497+
AbstractHttpClientPlugin<String> plugin = mock(AbstractHttpClientPlugin.class);
498+
ServerWebExchange exchange = createFailoverExchange("http://localhost:8080/test?mode=retry");
499+
exchange.getAttributes().put(Constants.LOAD_BALANCE, "shortestResponse");
500+
exchange.getAttributes().put(Constants.DIVIDE_SELECTOR_ID, "selector-7973-retry");
501+
Upstream failed = Upstream.builder().url("localhost:8080").build();
502+
Upstream standbyA = Upstream.builder().protocol("http://").url("localhost:8081").build();
503+
Upstream standbyB = Upstream.builder().protocol("http://").url("localhost:8082").build();
504+
UpstreamCacheManager cacheManager = mock(UpstreamCacheManager.class);
505+
when(cacheManager.findUpstreamListBySelectorId("selector-7973-retry")).thenReturn(Arrays.asList(failed, standbyA, standbyB));
506+
when(plugin.getCachedRequestBody(exchange)).thenReturn(Flux.empty());
507+
final long baselineA = standbyA.getInflight().get();
508+
final long baselineB = standbyB.getInflight().get();
509+
AtomicLong inflightDuringResend = new AtomicLong();
510+
when(plugin.doRequest(eq(exchange), eq("GET"), any(URI.class), any())).thenReturn(Mono.defer(() -> {
511+
inflightDuringResend.set(standbyA.getInflight().get() + standbyB.getInflight().get());
512+
return Mono.just("success");
513+
}));
514+
515+
try (MockedStatic<UpstreamCacheManager> cacheMock = mockStatic(UpstreamCacheManager.class)) {
516+
cacheMock.when(UpstreamCacheManager::getInstance).thenReturn(cacheManager);
517+
StepVerifier.create(new DefaultRetryStrategy<>(plugin).execute(Mono.error(new TimeoutException("upstream failed")),
518+
exchange, Duration.ofSeconds(5), 2))
519+
.expectNext("success")
520+
.verifyComplete();
521+
}
522+
// no Divide owner: doSelect increments the chosen standby, and retry completion releases it once
523+
assertEquals(baselineA + baselineB + 1, inflightDuringResend.get());
524+
assertEquals(baselineA, standbyA.getInflight().get());
525+
assertEquals(baselineB, standbyB.getInflight().get());
526+
}
527+
528+
@Test
529+
void testFailoverReleasesShortestResponseInflightOnSingletonRetry() {
530+
AbstractHttpClientPlugin<String> plugin = mock(AbstractHttpClientPlugin.class);
531+
ServerWebExchange exchange = createFailoverExchange("http://localhost:8080/test?mode=retry");
532+
exchange.getAttributes().put(Constants.LOAD_BALANCE, "shortestResponse");
533+
exchange.getAttributes().put(Constants.DIVIDE_SELECTOR_ID, "selector-7973-retry-single");
534+
Upstream failed = Upstream.builder().url("localhost:8080").build();
535+
Upstream onlyStandby = Upstream.builder().protocol("http://").url("localhost:8083").build();
536+
UpstreamCacheManager cacheManager = mock(UpstreamCacheManager.class);
537+
when(cacheManager.findUpstreamListBySelectorId("selector-7973-retry-single")).thenReturn(Arrays.asList(failed, onlyStandby));
538+
when(plugin.getCachedRequestBody(exchange)).thenReturn(Flux.empty());
539+
final long baseline = onlyStandby.getInflight().get();
540+
AtomicLong inflightDuringResend = new AtomicLong();
541+
when(plugin.doRequest(eq(exchange), eq("GET"), any(URI.class), any())).thenReturn(Mono.defer(() -> {
542+
inflightDuringResend.set(onlyStandby.getInflight().get());
543+
return Mono.just("success");
544+
}));
545+
546+
try (MockedStatic<UpstreamCacheManager> cacheMock = mockStatic(UpstreamCacheManager.class)) {
547+
cacheMock.when(UpstreamCacheManager::getInstance).thenReturn(cacheManager);
548+
StepVerifier.create(new DefaultRetryStrategy<>(plugin).execute(Mono.error(new TimeoutException("upstream failed")),
549+
exchange, Duration.ofSeconds(5), 2))
550+
.expectNext("success")
551+
.verifyComplete();
552+
}
553+
assertEquals(baseline + 1, inflightDuringResend.get());
554+
assertEquals(baseline, onlyStandby.getInflight().get());
555+
}
556+
557+
@Test
558+
void testFailoverKeepsShortestResponseOwnedUntilTerminalRelease() {
559+
AbstractHttpClientPlugin<String> plugin = mock(AbstractHttpClientPlugin.class);
560+
ServerWebExchange exchange = createFailoverExchange("http://localhost:8080/test?mode=retry");
561+
exchange.getAttributes().put(Constants.LOAD_BALANCE, "shortestResponse");
562+
exchange.getAttributes().put(Constants.DIVIDE_SELECTOR_ID, "selector-7973-owned");
563+
Upstream failed = Upstream.builder().url("localhost:8080").build();
564+
Upstream onlyStandby = Upstream.builder().protocol("http://").url("localhost:8083").build();
565+
UpstreamCacheManager cacheManager = mock(UpstreamCacheManager.class);
566+
when(cacheManager.findUpstreamListBySelectorId("selector-7973-owned")).thenReturn(Arrays.asList(failed, onlyStandby));
567+
when(plugin.getCachedRequestBody(exchange)).thenReturn(Flux.empty());
568+
when(plugin.doRequest(eq(exchange), eq("GET"), any(URI.class), any())).thenReturn(Mono.just("success"));
569+
final long baseline = onlyStandby.getInflight().get();
570+
final UpstreamAttemptOwner owner = armAttemptOwner(exchange);
571+
572+
try (MockedStatic<UpstreamCacheManager> cacheMock = mockStatic(UpstreamCacheManager.class)) {
573+
cacheMock.when(UpstreamCacheManager::getInstance).thenReturn(cacheManager);
574+
StepVerifier.create(new DefaultRetryStrategy<>(plugin).execute(Mono.error(new TimeoutException("upstream failed")),
575+
exchange, Duration.ofSeconds(5), 1))
576+
.expectNext("success")
577+
.verifyComplete();
578+
}
579+
// Divide owns the succeeded attempt until the response body is done (#8158)
580+
assertSame(onlyStandby, owner.current());
581+
assertEquals(baseline + 1, onlyStandby.getInflight().get());
582+
terminalRelease(owner);
583+
assertEquals(baseline, onlyStandby.getInflight().get());
584+
assertNull(owner.current());
585+
}
586+
495587
@Test
496588
void testFailoverWithMissingUpstreamList() {
497589
AbstractHttpClientPlugin<String> httpClientPlugin = mock(AbstractHttpClientPlugin.class);

‎shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/DividePlugin.java‎

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -207,11 +207,7 @@ private Mono<Void> forwardSelected(final ServerWebExchange exchange, final Sheny
207207
boolean p2cReserved = false;
208208
if (candidates.isProbe()) {
209209
upstream = breakeredUpstreamList.get(0);
210-
p2cReserved = P2C.equals(ruleHandle.getLoadBalance());
211-
if (p2cReserved) {
212-
upstream.getInflight().incrementAndGet();
213-
upstream.setLastPicked(System.currentTimeMillis());
214-
}
210+
p2cReserved = reserveProbe(ruleHandle, upstream);
215211
} else if (CollectionUtils.isNotEmpty(specifyDomains)) {
216212
// an explicit specify-domain request is an operations override and never affinity-bound
217213
String requested = specifyDomains.get(0);
@@ -279,6 +275,26 @@ private Mono<Void> forwardSelected(final ServerWebExchange exchange, final Sheny
279275
attemptOwner, candidates.isProbe());
280276
}
281277

278+
/**
279+
* A half-open probe skips the load balancer, so reserve here for the algorithms that
280+
* otherwise count the selection.
281+
*
282+
* @param ruleHandle the divide rule handle
283+
* @param upstream the probe target
284+
* @return true when the probe reserved a P2C attempt
285+
*/
286+
private boolean reserveProbe(final DivideRuleHandle ruleHandle, final Upstream upstream) {
287+
if (P2C.equals(ruleHandle.getLoadBalance())) {
288+
upstream.getInflight().incrementAndGet();
289+
upstream.setLastPicked(System.currentTimeMillis());
290+
return true;
291+
}
292+
if (SHORTEST_RESPONSE.equals(ruleHandle.getLoadBalance())) {
293+
upstream.getInflight().incrementAndGet();
294+
}
295+
return false;
296+
}
297+
282298
private void rejectCanary(final ServerWebExchange exchange) {
283299
CanaryContext context = exchange.getAttribute(Constants.SHENYU_CANARY_CONTEXT);
284300
if (Objects.nonNull(context)) {
@@ -357,6 +373,10 @@ private UpstreamAttemptOwner installAttemptOwner(final ServerWebExchange exchang
357373
attemptOwner = new UpstreamAttemptOwner(serving -> serving.getInflight().decrementAndGet());
358374
} else if (P2C.equals(ruleHandle.getLoadBalance()) && p2cReserved) {
359375
attemptOwner = new UpstreamAttemptOwner(this::responseTrigger);
376+
} else if (SHORTEST_RESPONSE.equals(ruleHandle.getLoadBalance())) {
377+
// Selection, a half-open probe, or a binding hit already reserved this attempt.
378+
// Failover moves the owner; the terminal release runs once when the body is done (#7973, #8158).
379+
attemptOwner = new UpstreamAttemptOwner(this::releaseShortestResponseInflight);
360380
} else {
361381
attemptOwner = null;
362382
}
@@ -371,21 +391,20 @@ private Mono<Void> forwardWithCircuitBreaker(final ServerWebExchange exchange, f
371391
final DivideRuleHandle ruleHandle, final String breakerKey, final Upstream upstream,
372392
final UpstreamAttemptOwner attemptOwner, final boolean probe) {
373393
Mono<Void> response = Mono.defer(() -> chain.execute(exchange));
374-
if (ruleHandle.getLoadBalance().equals(LEAST_ACTIVE) || ruleHandle.getLoadBalance().equals(P2C)) {
375-
// the owner names whichever attempt is serving; failover moves it, and this terminal
376-
// release runs when the response body is done, errors or is cancelled (#8158)
377-
if (Objects.nonNull(attemptOwner)) {
378-
response = response.doFinally(signalType -> attemptOwner.releaseCurrent());
379-
}
380-
} else if (ruleHandle.getLoadBalance().equals(SHORTEST_RESPONSE)) {
394+
if (SHORTEST_RESPONSE.equals(ruleHandle.getLoadBalance())) {
381395
long beginTime = System.currentTimeMillis();
382396
response = response.doOnSuccess(e -> successResponseTrigger(upstream, beginTime));
383-
} else if (ruleHandle.getLoadBalance().equals(ADAPTIVE)) {
397+
} else if (ADAPTIVE.equals(ruleHandle.getLoadBalance())) {
384398
// the attempt's own start time feeds the adaptive scoring, so overlapping
385399
// attempts never share a timestamp the way the p2c lag attribution does
386400
long beginTime = System.currentTimeMillis();
387401
response = response.doFinally(signalType -> adaptiveFeedback(upstream, exchange, beginTime, signalType));
388402
}
403+
if (Objects.nonNull(attemptOwner)) {
404+
// the owner names whichever attempt is serving; failover moves it, and this terminal
405+
// release runs when the response body is done, errors or is cancelled (#8158)
406+
response = response.doFinally(signalType -> attemptOwner.releaseCurrent());
407+
}
389408
return probe ? response : UpstreamCircuitBreaker.recordOutcome(response, breakerKey);
390409
}
391410

@@ -447,6 +466,9 @@ private Upstream resolveWithAffinity(final ServerWebExchange exchange, final Rul
447466
// attempt: the same accounting must apply or the count drifts down
448467
bound.getInflight().incrementAndGet();
449468
bound.setLastPicked(System.currentTimeMillis());
469+
} else if (SHORTEST_RESPONSE.equals(ruleHandle.getLoadBalance())) {
470+
// A binding hit skips selection, which is where shortestResponse reserves inflight.
471+
bound.getInflight().incrementAndGet();
450472
}
451473
return bound;
452474
}
@@ -488,6 +510,9 @@ private Upstream resolveWithDeterministicKey(final ServerWebExchange exchange, f
488510
// attempt: the same accounting must apply or the count drifts down
489511
upstream.getInflight().incrementAndGet();
490512
upstream.setLastPicked(System.currentTimeMillis());
513+
} else if (Objects.nonNull(upstream) && SHORTEST_RESPONSE.equals(ruleHandle.getLoadBalance())) {
514+
// The hash pick skips shortestResponse selection, which is where inflight is reserved.
515+
upstream.getInflight().incrementAndGet();
491516
}
492517
return upstream;
493518
}
@@ -524,6 +549,10 @@ private void successResponseTrigger(final Upstream upstream, final long beginTim
524549
upstream.getSucceeded().incrementAndGet();
525550
}
526551

552+
private void releaseShortestResponseInflight(final Upstream upstream) {
553+
upstream.getInflight().updateAndGet(current -> current > 0 ? current - 1 : 0);
554+
}
555+
527556
/**
528557
* A positive requestMaxSize must also cover chunked / unknown-length bodies: the
529558
* Content-Length header is absent (-1) there, so the limit is enforced on the actual

‎shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/test/java/org/apache/shenyu/plugin/divide/DividePluginTest.java‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,43 @@ public void leastActiveInflightShouldBeReleasedOnCancellation() {
479479
}
480480
}
481481

482+
@Test
483+
public void shortestResponseInflightReturnsToBaselineOnTerminalSignals() {
484+
DivideRuleHandle ruleHandle = DividePluginDataHandler.CACHED_HANDLE.get()
485+
.obtainHandle(CacheKeyUtils.INST.getKey(ruleData));
486+
ruleHandle.setLoadBalance("shortestResponse");
487+
Upstream upstream = Upstream.builder().url("http://upstream").build();
488+
try (MockedStatic<LoadbalancerUtils> loadbalancerUtils = mockStatic(LoadbalancerUtils.class)) {
489+
loadbalancerUtils.when(() -> LoadbalancerUtils.getForExchange(any(), anyString(), any()))
490+
.thenReturn(upstream);
491+
492+
upstream.getInflight().set(2);
493+
when(chain.execute(exchange)).thenReturn(Mono.empty());
494+
StepVerifier.create(dividePlugin.doExecute(exchange, chain, selectorData, ruleData)).verifyComplete();
495+
assertEquals(1, upstream.getInflight().get());
496+
assertEquals(1, upstream.getSucceeded().get());
497+
498+
upstream.getInflight().set(2);
499+
when(chain.execute(exchange)).thenReturn(Mono.error(new IllegalStateException("boom")));
500+
StepVerifier.create(dividePlugin.doExecute(exchange, chain, selectorData, ruleData))
501+
.verifyError(IllegalStateException.class);
502+
assertEquals(1, upstream.getInflight().get());
503+
assertEquals(1, upstream.getSucceeded().get());
504+
505+
upstream.getInflight().set(2);
506+
when(chain.execute(exchange)).thenReturn(Mono.never());
507+
Disposable subscription = dividePlugin.doExecute(exchange, chain, selectorData, ruleData).subscribe();
508+
subscription.dispose();
509+
assertEquals(1, upstream.getInflight().get());
510+
assertEquals(1, upstream.getSucceeded().get());
511+
512+
upstream.getInflight().set(0);
513+
when(chain.execute(exchange)).thenReturn(Mono.empty());
514+
StepVerifier.create(dividePlugin.doExecute(exchange, chain, selectorData, ruleData)).verifyComplete();
515+
assertEquals(0, upstream.getInflight().get());
516+
}
517+
}
518+
482519
@Test
483520
public void successResponseTriggerTest() throws Exception {
484521
dividePlugin = DividePlugin.class.newInstance();

0 commit comments

Comments
 (0)