Skip to content

[fix][broker] Avoid load shedding and metadata writes from a former leader - #26253

Open
void-ptr974 wants to merge 2 commits into
apache:masterfrom
void-ptr974:fix/modular-load-manager-leader-guard
Open

[fix][broker] Avoid load shedding and metadata writes from a former leader#26253
void-ptr974 wants to merge 2 commits into
apache:masterfrom
void-ptr974:fix/modular-load-manager-leader-guard

Conversation

@void-ptr974

Copy link
Copy Markdown
Contributor

Motivation

Load-balancer tasks are started only while a broker is the leader. However, cancelling a scheduled task does not stop an invocation that is already in progress. If leadership changes during such an invocation, the former leader can still initiate bundle unloading or persist load-balancing metadata.

Modifications

  • Recheck leadership before initiating bundle unloading.
  • Recheck leadership before writing bundle and broker load data to metadata.
  • Stop the remaining work when leadership has changed.

Verifying this change

This change added tests and can be verified as follows:

  • Added coverage for a follower skipping load shedding.
  • Added coverage for leadership changing after destination selection and before bundle unload.
  • Added coverage for leadership changing after aggregation and before metadata writes.
  • Ran ./gradlew :pulsar-broker:test -PtestGroups=broker -PexcludedTestGroups='' --tests org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerImplTest --console=plain
  • Ran ./gradlew :pulsar-broker:checkstyleMain :pulsar-broker:checkstyleTest --console=plain

Does this pull request potentially affect one of the following parts:

  • Dependencies (add or upgrade a dependency)
  • The public API
  • The schema
  • The default values of configurations
  • The threading model
  • The binary protocol
  • The REST endpoints
  • The admin CLI options
  • The metrics
  • Anything that affects deployment

…eader

Recheck leader state before load-shedding side effects and metadata writes so a task that was already running stops after leadership changes.
@void-ptr974
void-ptr974 force-pushed the fix/modular-load-manager-leader-guard branch from ef5750a to d5e269e Compare July 28, 2026 01:58
pulsar.getAdminClient().namespaces()
.unloadNamespaceBundle(namespaceName, bundleRange, destBroker.get());
if (!isLeader()) {
return;

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.

This return is inside nested forEach lambdas, so it only skips the current foreach.This could be optimized.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 68869bc. Replaced the nested lambdas with regular loops so leadership loss exits the load-shedding operation.

@Dream95

Dream95 commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Leader can still change between the isLeader() check and the actual unload, so this cannot fully prevent a former leader from triggering an unload.

@void-ptr974

Copy link
Copy Markdown
Contributor Author

Thanks. This PR intentionally provides only a best-effort guard and does not address the narrow race between the leadership check and the unload itself. Providing a strong guarantee would require a broader fencing design, which is out of scope for this focused change.


@VisibleForTesting
boolean isLeader() {
return pulsar.getLeaderElectionService() != null && pulsar.getLeaderElectionService().isLeader();

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.

isLeader() only checks the local leader-election state. In LeaderElectionImpl.handleSessionNotification(), the Leading status is not invalidated on ConnectionLost or SessionLost—it is only revalidated after reconnection. Since SessionLost implies this broker’s ephemeral leader node may have already expired, isLeader() can continue returning true even after another broker has become leader.

This results in a significantly wider former‑leader window compared with the narrow check‑to‑unload race described later. The task‑level metadata‑availability check also does not protect against a session loss that occurs after the task has started, and the resource‑quota updator lacks such an entry check.

Could this guard incorrectly remain closed while lastMetadataSessionEvent.isConnected() is false, assuming proper volatile/atomic visibility for that field? Alternatively, leadership should be invalidated in LeaderElectionImpl when the session is lost.

Comment on lines +1242 to +1244
if (!isLeader()) {
return;
}

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.

updateBundleData() is not side-effect-free: before the leadership check runs, it can call deleteBundleDataFromMetadataStore() for inactive bundles. This method is also invoked from the metadata-notification-driven updateAll() path, and cleanupDeadBrokersData() includes a similar asynchronous deletion path for broker time‑average data.

Therefore, adding a leadership check after updateBundleData() does not prevent all metadata mutations by a former leader. An old leader could still delete data after a new leader has written it.

Could we modify updateBundleData() to perform only in‑memory aggregation and move deletions into the guarded write phase? Alternatively, could we apply the same leadership or session guard immediately before each deletion path? A regression test covering inactive‑bundle deletion during leadership loss would also be needed.

Comment on lines +676 to +678
if (!isLeader()) {
return;
}

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.

Returning here bypasses the broker's finalization and the method-level metrics update. This same problem occurs again with the leadership check immediately before unloading.

If a previous bundle for this broker has already been unloaded successfully, unloadBundleCount and recentlyUnloadedBundles are already updated and unloadBundleForBroker is set to true. Losing leadership before processing the next bundle then skips both unloadBrokerCount++ and updateBundleUnloadingMetrics(). This permanently undercounts the broker and leaves the published metrics stale.

Could we use a labeled break or a leadershipLost flag to exit the loops while still performing the finalization and metrics update?

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.

3 participants