MultiDb failover retry keeps rescheduling itself after the connection is closed
Bug Report
Current Behavior
When every database is unhealthy, StatefulRedisMultiDbConnectionImpl schedules a failover retry through FailoverRetryState.tryScheduleRetry(). The ScheduledFuture returned by executor.schedule(...) is dropped, and closeAsync() only cancels failbackTask. So nothing stops a pending retry when the connection is closed.
That retry then runs failoverFrom(null, reason) on the closed connection. close() doesn't clear databases, and the stopped health checks keep reporting their last status (UNHEALTHY). So getNextHealthyDatabase() returns null again and another retry gets scheduled. From then on it loops every delayInBetweenFailoverAttempts (12s by default):
- an
AllDatabasesUnhealthyEventis published each time, with an ever-growing attempt count - the closed connection stays reachable from the shared
eventExecutorGroup, so it is never garbage collected
If the outage came from an open circuit breaker rather than health checks, the grace period eventually resets the breaker to CLOSED. The retry then goes on to safeSwitch() against the closed connections.
The constructor has the same problem. If the initial database becomes unhealthy and no other one is healthy, failoverFrom(instance, FORCED) schedules a retry, and then the constructor throws IllegalStateException("No healthy database available"). The caller never gets an object to close, and the retry keeps running on the half-built instance.
Shutting down an application during an outage is a fairly normal thing to do, so I think this deserves a fix.
Input Code
Unit test against main (8baa869fe). It uses the same mocks as StatefulRedisMultiDbConnectionImplUnitTests, plus eventExecutorGroup.schedule(...) stubbed to return a mock ScheduledFuture:
Input Code
@Test
void retryAfterCloseShouldNotReschedule() {
StatefulRedisMultiDbConnectionImpl<StatefulRedisConnection<String, String>, String, String> connection =
new StatefulRedisMultiDbConnectionImpl<>(null, databases, clientResources, StringCodec.UTF8, connectionFactory,
healthStatusManager, null,
MultiDbOptions.builder().failbackSupported(false)
.delayInBetweenFailoverAttempts(Duration.ofMillis(100)).build());
ArgumentCaptor<HealthStatusListener> listener = ArgumentCaptor.forClass(HealthStatusListener.class);
verify(healthStatusManager).registerListener(eq(uri1), listener.capture());
// all databases go down
when(healthCheck1.getStatus()).thenReturn(HealthStatus.UNHEALTHY);
when(healthCheck2.getStatus()).thenReturn(HealthStatus.UNHEALTHY);
listener.getValue().onStatusChange(new HealthStatusChangeEvent(uri1, HealthStatus.HEALTHY, HealthStatus.UNHEALTHY));
ArgumentCaptor<Runnable> retry = ArgumentCaptor.forClass(Runnable.class);
verify(eventExecutorGroup).schedule(retry.capture(), anyLong(), any(TimeUnit.class));
connection.close();
clearInvocations(eventExecutorGroup, eventBus);
// the timer fires after close()
retry.getValue().run();
verify(eventExecutorGroup, never()).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); // fails
verify(eventBus, never()).publish(any(AllDatabasesUnhealthyEvent.class)); // fails
}
Result on main:
org.mockito.exceptions.verification.NeverWantedButInvoked:
eventExecutorGroup.schedule(
<any java.lang.Runnable>,
<any long>,
<any java.util.concurrent.TimeUnit>
);
Never wanted here:
-> at io.lettuce.core.failover.MultiDbReproUnitTests.retryAfterCloseShouldNotReschedule(MultiDbReproUnitTests.java:139)
But invoked here:
-> at io.lettuce.core.failover.StatefulRedisMultiDbConnectionImpl$FailoverRetryState.tryScheduleRetry(StatefulRedisMultiDbConnectionImpl.java:1142) with arguments: [...$Lambda$622@1015a4b9, 100, MILLISECONDS]
Expected behavior/code
After close(), or after the constructor fails, no failover retry runs, and nothing is rescheduled or published.
Environment
- Lettuce version(s): 7.4.0.RELEASE through 7.9.0.RELEASE, and
main(8.0.0-SNAPSHOT) - Redis version: not relevant, reproduced with a unit test
Possible Solution
- Keep the
ScheduledFutureinFailoverRetryStateand cancel it fromcloseAsync(), and also on the constructor's failure path before throwing. - Add a
closedflag that the retry task (andfailoverFrom) checks, so a retry that has already started doesn't reschedule itself. Cancelling alone leaves a small window there.
Additional context
While looking at this I noticed that the constructor's failure path (:188-190) and removeDatabase() (:1079) unregister listeners with fresh this::onHealthStatusChange / this::onCircuitBreakerStateChange references. Those aren't equal to the instances that were registered, so nothing is actually removed. On the constructor path this also keeps the half-built connection subscribed. I can file that separately, or fix it in the same PR if you prefer, since both are cleanup problems in the same class.
I found this with help from an AI assistant while reading the failover code. I reproduced and checked everything above myself on my machine.
If this sounds right to you, I'd like to work on the fix and open a PR with regression tests. Is that OK?
hey @shinseongsu ,
thank you for the analysis. it stands legit. You are more than welcome with a PR on this. Anticipated change around fixing listeners would be pretty small, so i think its ok to cover it in the same one.