Skip to content

[fix][broker] Recover bucket delayed delivery tracker asynchronously to avoid blocking dispatcher threads - #26105

Merged
merlimat merged 3 commits into
apache:masterfrom
void-ptr974:fix/bucket-delayed-tracker-recovery
Oct 18, 2026
Merged

merlimat merged 3 commits into
apache:masterfrom
void-ptr974:fix/bucket-delayed-tracker-recovery

Conversation

@void-ptr974

@void-ptr974 void-ptr974 commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #26103

Motivation

When a dispatcher reads its first delayed message, it creates its delayed delivery tracker inline, while holding the dispatcher lock. The bucket tracker recovers its bucket snapshots in its constructor and waits for that recovery for up to 300 seconds:

AbstractBaseDispatcher.filterEntriesForConsumer()
  -> PersistentDispatcherMultipleConsumers.trackDelayedDelivery()   // synchronized (this)
  -> BucketDelayedDeliveryTrackerFactory.newTracker(this)
  -> new BucketDelayedDeliveryTracker(...)
  -> recoverBucketSnapshot()
  -> FutureUtil.waitForAll(futures.values()).get(AsyncOperationTimeoutSeconds * 5, TimeUnit.SECONDS)

If reading the snapshots from BookKeeper or the metadata store is slow, the subscription stalls. The broker-topic-workers thread stalls with it, along with every other topic and subscription served by that thread.

Modifications

  • DelayedDeliveryTrackerFactory gains a newTrackerAsync() method. By default it wraps newTracker(), so the in-memory factory and custom factories keep working unchanged.
  • BucketDelayedDeliveryTrackerFactory.newTrackerAsync() creates the tracker without recovery, then recovers the bucket snapshots asynchronously with the same 300 s timeout. On any failure or timeout it closes the bucket tracker and falls back to the in-memory tracker, as the synchronous path already did.
  • PersistentDispatcherMultipleConsumers:
    • While the tracker is being created, delayed messages wait in a pending map and dispatch is paused. Once the tracker is ready, the pending messages move into it, and those whose delivery time has already passed are replayed.
    • A factory that completes inline, like the in-memory one, installs the tracker within the same call, and no extra read is scheduled.
    • If the tracker cannot be created, the messages stay pending and dispatch stays paused, and the creation is retried with a backoff of 1 s up to 1 min. Delivering the messages early, or disabling delayed delivery for the dispatcher, would ignore their delay.
    • A dispatcher that has been closed doesn't start a creation. close() completes a pending creation, and a tracker that is created later is closed.
    • clearDelayedMessages() waits for a pending creation before it clears the tracker.
    • If the tracker throws while it takes the pending messages, the remaining messages are replayed, and the creation still completes and dispatch resumes.
    • The stats reads stay lock-free ([fix][broker] Remove lock contention in delayed delivery stats read paths #25990): the pending map is a ConcurrentHashMap, guarded by the dispatcher lock for writes.
    • The creation logs at DEBUG. It logs a WARN when the creation fails, or when it is still pending after 30 s.
  • DelayedDeliveryTracker.DISABLE.clear() returns a completed future instead of null.

Verifying this change

New tests:

  • PersistentDispatcherMultipleConsumersTest: async tracker creation covering pending messages, elapsed messages, a tracker that throws, close, a closed dispatcher, clearDelayedMessages(), and a failed creation that is retried.
  • DelayedDeliveryTrackerFactoryTest: async bucket creation, fallback after a recovery failure, and a broker-path test. In that test a delayed message waits for a bucket snapshot recovery that is held back, the dispatcher lock stays free meanwhile, and the message is delivered once the recovery completes.

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

@void-ptr974
void-ptr974 force-pushed the fix/bucket-delayed-tracker-recovery branch from a8e8932 to b497567 Compare June 28, 2026 15:48

@lhotari lhotari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for tackling the blocking recovery in the delayed delivery path. Moving recovery off the dispatcher thread is the right direction.

I found no blocking wait left on the async path. Delayed messages are held in the pending map and handed to the tracker once it is ready. Close and clearDelayedMessages() both complete the create future.

A few things need another look:

  • A failed creation installs DelayedDeliveryTracker.DISABLE for the life of the dispatcher.
  • The two close tests verify close() on a plain mock, but the code calls closeAsync().
  • A trackDelayedDelivery call after close() leaves a completed create future set.
  • The install step is not exception safe.

For context, #26401 changes the same deletion loop in recoverBucketSnapshot. Whichever PR lands second will need a manual merge there. #26420 makes cursor reset call clearDelayedMessages(), which now waits for a pending creation.

- Drop the PersistentDispatcherMultipleConsumersClassic changes and tests:
  the classic dispatcher was removed in apache#26687.
- Re-port the async snapshot recovery onto the BucketContext / index code
  from apache#26251, keeping the recovery synchronized on the tracker.
- Keep the dispatcher's delayed-delivery stats reads lock-free (apache#25990).
- A failed tracker creation keeps the delayed messages pending and dispatch
  paused, and retries with a backoff, instead of installing
  DelayedDeliveryTracker.DISABLE for the life of the dispatcher.
- A closed dispatcher doesn't start a tracker creation.
- Handing the pending messages to the new tracker is exception safe: the
  creation still completes, the remaining messages are replayed and
  dispatch resumes.
- The bucket factory falls back to the in-memory tracker on any async
  recovery failure.
- Tracker creation logs at DEBUG; only failures and a creation still
  pending after 30 s log a WARN.
- Tests verify closeAsync(), cover the closed dispatcher, elapsed messages,
  a throwing tracker and the retry, check that the dispatcher lock is free
  during recovery, and restore the shared broker's topic map.
@merlimat

Copy link
Copy Markdown
Contributor

Thanks @void-ptr974 for the fix. I've picked this up to get it merged, and pushed a merge of master (no rebase) to the branch. It also addresses @lhotari's review:

  • Failed creation: DISABLE is no longer installed. The delayed messages stay pending, dispatch stays paused, and the creation is retried with a backoff of 1 s up to 1 min, so nothing is delivered early. A tracker factory that returns null is treated as a failure and logged.
  • Closed dispatcher: trackDelayedDelivery doesn't start a creation once the dispatcher is closed. The create future is always cleared before it completes, so clearDelayedMessages() can no longer recurse on a completed future.
  • Install step: it is exception safe now. If the tracker throws, the remaining pending messages are replayed, the future still completes, and dispatch resumes. Scheduling the 30 s pending log tolerates RejectedExecutionException.
  • Close tests: they verify closeAsync().
  • Broker-path test: while recovery is held back, the test checks that the dispatcher lock can be taken, and it restores the topic map afterwards.

Other changes from the merge:

Locally, PersistentDispatcherMultipleConsumersTest, DelayedDeliveryTrackerFactoryTest and BucketDelayedDeliveryTrackerTest pass (68 tests), and checkstyle passes too. I've also updated the description.

#26401 changes the same recovery loop, so whichever of the two lands second will need a manual merge there.

…ated inline

A factory that completes newTrackerAsync() inline, such as the in-memory
one, never paused the dispatch: the read that found the delayed message is
still in progress. Only resume the dispatch with readMoreEntriesAsync()
when the creation completed later, or on a retry.

testGetMessagesToReplayNowChecksDelayedTrackerOnce (added by apache#26954)
stubbed only newTracker(), so its factory mock returned no tracker from
newTrackerAsync(). It now stubs newTrackerAsync().
@merlimat
merlimat merged commit c9a95df into apache:master Oct 18, 2026
44 checks passed
lhotari pushed a commit that referenced this pull request Oct 18, 2026
…to avoid blocking dispatcher threads (#26105)

Co-authored-by: Matteo Merli <[email protected]>
(cherry picked from commit c9a95df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Bucket delayed delivery recovery can block dispatcher threads

3 participants