Skip to content

[automatic failover] Refactor Circuit Breaker Command Tracking - #3670

Open
atakavci wants to merge 2 commits into
redis:mainfrom
atakavci:failover/captureMetricsEarly
Open

atakavci wants to merge 2 commits into
redis:mainfrom
atakavci:failover/captureMetricsEarly

Conversation

@atakavci

@atakavci atakavci commented Feb 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #3567

Summary

Refactored circuit breaker command tracking to use a wrapper-based approach instead of callback-based tracking, improving consistency and reducing code duplication.

Changes

Core Improvements

  • Introduced CircuitBreakerAwareCommand: New CommandWrapper subclass that tracks circuit breaker results through lifecycle hooks
  • Simplified tracking logic: Replaced callback-based tracking with wrapper-based approach using doBeforeComplete() and doBeforeError() hooks
  • Unified error handling: All command results (success/failure) are now recorded consistently through the wrapper

Modified Components

  • DatabaseCommandTracker:

    • Wraps commands in CircuitBreakerAwareCommand before writing
    • Removed attachRecorder() method and callback-based tracking
    • Records exceptions for each command in batch operations
  • MultiDbOutboundHandler:

    • Simplified to only attach listeners for CircuitBreakerAwareCommand instances
    • Removed recorder() and recordOnCommandComplete() methods
    • Changed from List to Collection for better type flexibility
  • CommandWrapper:

    • Added doBeforeComplete() and doBeforeError() lifecycle hooks
    • Hooks are called before delegating to wrapped command and notifying consumers

Benefits

  • Cleaner separation of concerns
  • Reduced code complexity and duplication
  • More maintainable circuit breaker tracking mechanism
  • Consistent error recording across all command execution paths

Note

Medium Risk
Changes how and when failover circuit-breaker outcomes are recorded (unified wrapper hooks vs split timeout/non-timeout callbacks), affecting automatic failover behavior on command failures.

Overview
Refactors automatic-failover circuit breaker command tracking from scattered CompleteableCommand callbacks into a single CircuitBreakerAwareCommand wrapper around outbound Redis commands.

DatabaseCommandTracker now wraps single and batch writes (unless already wrapped) with the current CircuitBreakerGeneration, removes attachRecorder(), and records write failures once per command in batches. MultiDbOutboundHandler only registers the wrapper itself as a ChannelPromise listener for single commands or Collection batches, dropping the old recorder() / recordOnCommandComplete() split with timeout-specific handling.

CommandWrapper gains doBeforeComplete() and doBeforeError() hooks invoked before delegating completion or failure to the inner command, which the wrapper uses to call generation.recordResult() for successes, errors/cancellations, and failed pipeline writes.

Reviewed by Cursor Bugbot for commit 8820578. Bugbot is set up for automated code reviews on this repo. Configure here.

Copilot AI 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.

Pull request overview

This PR refactors the circuit breaker command tracking mechanism from a callback-based approach to a wrapper-based approach. The refactoring introduces a new CircuitBreakerAwareCommand wrapper class that uses lifecycle hooks (doBeforeComplete and doBeforeError) to track command results. This change aims to address a sporadic test failure in CircuitBreakerMetricsIntegrationTests where circuit breaker failures were being tracked in command future completion handlers instead of on actual command completion.

Changes:

  • Introduced lifecycle hooks in CommandWrapper for tracking before command completion and error handling
  • Created CircuitBreakerAwareCommand wrapper that records all command results through these hooks
  • Simplified MultiDbOutboundHandler to only attach the wrapper as a listener to write promises

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 7 comments.

File Description
src/main/java/io/lettuce/core/protocol/CommandWrapper.java Added doBeforeComplete() and doBeforeError() lifecycle hooks to enable tracking before command completion
src/main/java/io/lettuce/core/failover/DatabaseCommandTracker.java Introduced CircuitBreakerAwareCommand wrapper and modified write methods to wrap commands before delegation
src/main/java/io/lettuce/core/failover/MultiDbOutboundHandler.java Simplified to attach CircuitBreakerAwareCommand as listener; removed old callback-based tracking logic

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +154 to 162
@Override
protected void doBeforeComplete() {
generation.recordResult(null);
}

@Override
protected void doBeforeError(Throwable throwable) {
generation.recordResult(throwable);
}

Copilot AI Feb 18, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical issue: The new implementation changes the tracking behavior in a way that conflicts with existing tests. The CircuitBreakerAwareCommand records ALL successes (line 156) and ALL errors (line 161), but the existing tests expect that only timeout exceptions are recorded by DatabaseCommandTracker while successes and non-timeout exceptions are recorded by MultiDbOutboundHandler. This change appears to cause double-recording when combined with MultiDbOutboundHandler, or the tests need to be updated to reflect the new behavior. The PR description does not mention this behavioral change, and the tests are not included in the diff, suggesting they may not have been updated or verified to pass with these changes.

Copilot uses AI. Check for mistakes.
Comment on lines 136 to 138
} catch (Exception e) {
// TODO: here not sure we should record exception for each command or just once for the batch
circuitBreaker.getGeneration().recordResult(e);
commands.forEach(c -> circuitBreaker.getGeneration().recordResult(e));
throw e;

Copilot AI Feb 18, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical bug: Potential triple recording of failures for batch write exceptions. When writeMany throws an exception, line 137 records the exception once for each command. Then, each command will also be completed exceptionally (presumably), which will trigger doBeforeError (line 160-161) recording the exception again. Additionally, if the write promise fails, operationComplete (line 165-168) will record it a third time. This results in each batch write failure being recorded 2-3 times per command.

Copilot uses AI. Check for mistakes.
Comment on lines 102 to 104
} catch (Exception e) {
circuitBreaker.getGeneration().recordResult(e);
throw e;

Copilot AI Feb 18, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical bug: Potential triple recording of write exceptions. When writeOne throws an exception, line 103 records it. Then, the command will also be completed exceptionally (presumably), which will trigger doBeforeError (line 160-161) recording the exception again. Additionally, if the write promise fails, operationComplete (line 165-168) will record it a third time. This results in each write failure being recorded 2-3 times.

Copilot uses AI. Check for mistakes.
}

/**
* Callback method called after successful completion and before notifying downstream consumers.

Copilot AI Feb 18, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JavaDoc comment is incorrect. It says "after successful completion and before notifying downstream consumers", but the method is called BEFORE the wrapped command is completed (line 69), not after. The comment should say "before successful completion of the wrapped command and before notifying downstream consumers".

Suggested change
* Callback method called after successful completion and before notifying downstream consumers.
* Callback method called before successful completion of the wrapped command and before notifying downstream
* consumers.

Copilot uses AI. Check for mistakes.
}

/**
* Callback method called after error completion and before notifying downstream consumers.

Copilot AI Feb 18, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JavaDoc comment is incorrect. It says "after error completion and before notifying downstream consumers", but the method is called BEFORE the wrapped command is completed exceptionally (line 145 for completeExceptionally, line 129 for cancel), not after. The comment should say "before error completion of the wrapped command and before notifying downstream consumers".

Suggested change
* Callback method called after error completion and before notifying downstream consumers.
* Callback method called before error completion of the wrapped command and before notifying downstream consumers.

Copilot uses AI. Check for mistakes.
Comment on lines +164 to +170
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
generation.recordResult(future.cause());
}
}

Copilot AI Feb 18, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical bug: This implementation can lead to double recording of failures. When a write operation fails, both operationComplete() (line 165-168) and doBeforeError() (line 160-161) will record the same failure to the circuit breaker generation. The operationComplete() method should be removed, or the doBeforeError() should check if the error is being recorded due to a write failure to avoid duplicate recording.

Suggested change
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
generation.recordResult(future.cause());
}
}

Copilot uses AI. Check for mistakes.
for (Object cmd : collection) {
if (cmd instanceof CircuitBreakerAwareCommand<?, ?, ?>) {
// we want to use the generation that is active at the time of write.
// Using a lamda which acces directly to circuitBreaker.getGeneration() here would delay capturing the

Copilot AI Feb 18, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Spelling error: "acces" should be "access", and "lamda" should be "lambda".

Suggested change
// Using a lamda which acces directly to circuitBreaker.getGeneration() here would delay capturing the
// Using a lambda which access directly to circuitBreaker.getGeneration() here would delay capturing the

Copilot uses AI. Check for mistakes.

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

@atakavci
I see it as a simplified and more predictable way of tracking command completion.

From my point of view, this approach is better, and guaranitee command result is tracked in CB before notifying of command completion

@atakavci

Copy link
Copy Markdown
Collaborator Author

@atakavci I see it as a simplified and more predictable way of tracking command completion.

From my point of view, this approach is better, and guaranitee command result is tracked in CB before notifying of command completion

@ggivo there is a downside of this approach that is contradicting with fundamentals of async API; the wrapper command is not the one API returns, it remains completely hidden/internal. In case the async command itself is somehow directly managed, CircuitBreakerAware is left out of equation. And there is no elegant way to improve that,, at least i couldn't see one.

- early capture circuit breaker metrics with CircuitBreakerAwareCommand
@a-TODO-rov
a-TODO-rov force-pushed the failover/captureMetricsEarly branch from 9a0b474 to 409319f Compare March 2, 2026 11:18

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

if (!future.isSuccess()) {
generation.recordResult(future.cause());
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Double recording of circuit breaker errors on write failure

High Severity

When a channel write fails, the circuit breaker records the error twice. MultiDbOutboundHandler registers the CircuitBreakerAwareCommand as a promise listener, so operationComplete fires and calls generation.recordResult(cause). Then DefaultEndpoint's AtMostOnceWriteListener calls command.completeExceptionally(cause), which triggers doBeforeError on the same wrapper and calls generation.recordResult(throwable) again. The old code avoided this by only attaching the completion callback on write success, never on write failure.

Additional Locations (2)

Fix in Cursor Fix in Web

a-TODO-rov added a commit that referenced this pull request Nov 19, 2026
* Disable flaky CircuitBreakerMetricsIntegrationTests.shouldTrackSuccessfulCommands

The circuit breaker counts a successful command in a completion callback on
the event loop, which can run after the synchronous call has already returned,
so the test sometimes reads a success count of 0. It failed in 7 of 246 CI test
jobs since Nov 10, on unrelated branches and Redis versions.

The race is tracked in #3567 and fixed in the client by #3670. Re-enable the
test once #3670 is merged.

* Give the health check timeout test a wider margin on slow runners

shouldConfigureHealthCheckIntervalAndTimeout waited only customTimeout + 50 ms
(150 ms) for the delayed health check to time out and mark the database
UNHEALTHY. On a slow runner the scheduling delay pushed it past that limit; it
failed on Redis 8.8 and 8.10 in the same main run on Nov 11. Wait up to
customTimeout + 1000 ms. The delayed check never completes on its own, so the
test still proves that the configured timeout is what marks it failed.

* Use a 1 s health check timeout in HealthCheckIntegrationTests

Eight tests used a 10 ms health check timeout. During connect() the client
waits at most (timeout + delay) x probes, here 11 ms, for the first health
result of each database and counts a missing result as a failed database. On a
slow runner that made shouldTriggerFailoverOnUnhealthyStatus fail with
"Initialization failed due to initialization policy: available=0, failed=1,
pending=1": the default MAJORITY_AVAILABLE policy needs both of its two
databases.

None of these tests tests the timeout, and the test strategy answers at once,
so a shared 1 s HEALTH_CHECK_TIMEOUT_MS does not slow passing tests.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

There are 3 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 8820578. Configure here.

if (!future.isSuccess()) {
generation.recordResult(future.cause());
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrapper misses inner command completion

High Severity

CircuitBreakerAwareCommand records results only when its own lifecycle hooks run, but the public command and CommandExpiryWriter complete the inner AsyncCommand. Timeouts therefore never reach the circuit breaker, and a later pipeline complete() on the wrapper can record a success instead.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8820578. Configure here.

CircuitBreakerAwareCommand.class);
if (circuitBreakerAwareCommand == null) {
command = new CircuitBreakerAwareCommand<>(command, circuitBreaker.getGeneration());
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale generation reused on rewrite

High Severity

When CommandWrapper.unwrap already finds a CircuitBreakerAwareCommand, the command is not re-wrapped with the current endpoint generation. Failover handover therefore keeps the original database's generation, so the target circuit breaker never records those results.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8820578. Configure here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feature A new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[automatic failover] Sporadic test failure observed in CircuitBreakerMetricsIntegrationTests

4 participants