Skip to content

[improve][broker] Skip indexed in-memory delayed messages on reconnect - #27643

Open
AuroraTwinkle wants to merge 4 commits into
apache:masterfrom
AuroraTwinkle:improve/broker-delayed-read-skip
Open

AuroraTwinkle wants to merge 4 commits into
apache:masterfrom
AuroraTwinkle:improve/broker-delayed-read-skip

Conversation

@AuroraTwinkle

@AuroraTwinkle AuroraTwinkle commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #23912

Motivation

Reconnecting the last consumer clears the in-memory delayed-message index and rereads its backlog. In the regression scenario, a cold-cache reconnect reads nine entries from BookKeeper even though eight are already indexed for delayed delivery.

Modifications

Reuse the index across reconnects and maintain position bitmaps for skipping indexed entries during normal reads. Positions handed to replay remain hidden from the rewound normal cursor until it catches up. Reset these replay markers on the next rewind so unacknowledged messages can be delivered again.

Route the Shared and Key_Shared rewind paths through the same helper, preserving the furthest pre-rewind read position before fixed-delay lookahead can pause delivery. Prune acknowledged or expired positions before rewinding; clear the indexes on seek, backlog clear and close.

When delayed delivery is disabled, drain indexed messages through bounded replay batches without waiting for their former deadlines. Keep the normal-read skip predicate active during the handoff, including when the policy changes after a consumer registers or after the cursor has already passed the indexed messages.

Index access is serialized on the tracker for ledger-thread lookups. Both pending delayed positions and temporary replay markers are included in the memory estimate.

Verifying this change

Shared and Key_Shared storage-read regressions fail on master with nine entries read and pass with one. Five additional cases reproduce the reconnect duplicates, policy-change duplicates and late Key_Shared rewind issue on the previous PR revision. Coverage also checks another reconnect before acknowledgment, unacked-message counts, replay-marker cleanup, fixed-delay lookahead, seek, expiry, backlog clear and unload.

Local validation: 177 related tests passed with retries disabled, no failures and no skipped tests. Full sanityCheck passed.

JMH lookup and add/drain benchmarks cover 1,000 and 100,000 positions on Linux x86_64 / JDK 21, including pending delays and positions already handed to replay during a rewind. These measure index operations, excluding storage reads and broker dispatch.

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

  • Dependencies
  • 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

@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 cold-cache reread on reconnect, and for the tracker-level and end-to-end tests and the JMH numbers.

Keeping the in-memory index across a reconnect changes one invariant the dispatcher used to rely on: before this change the tracker was empty after the rewind, so every retained delayed entry was read exactly once by the normal read. Now an entry can be handed to the replay read by getScheduledMessages while the rewound cursor is still behind it, and once it is drained the skip predicate no longer hides it from the normal read. That makes delayed messages that became due while the subscription had no consumers likely to be dispatched twice after reconnect (details inline). The current tests use 1-hour delays, so no indexed entry ever becomes due in them; a test where one becomes due while disconnected and is left unacked would pin this.

Two smaller points are inline: the Key_Shared no-consumer rewind bypasses the new rewind-position guard, and disabling the policy after a consumer has registered can also duplicate retained entries.

Lock ordering looks fine to me: the timer releases timeoutLock before taking the dispatcher monitor, and the predicate takes only the tracker monitor. The memory-accounting deltas in getScheduledMessages and removeMessagesUpTo also balance, including the -1 and Long.MAX_VALUE boundaries.

@AuroraTwinkle

Copy link
Copy Markdown
Contributor Author

Thanks for tackling the cold-cache reread on reconnect, and for the tracker-level and end-to-end tests and the JMH numbers.

Keeping the in-memory index across a reconnect changes one invariant the dispatcher used to rely on: before this change the tracker was empty after the rewind, so every retained delayed entry was read exactly once by the normal read. Now an entry can be handed to the replay read by getScheduledMessages while the rewound cursor is still behind it, and once it is drained the skip predicate no longer hides it from the normal read. That makes delayed messages that became due while the subscription had no consumers likely to be dispatched twice after reconnect (details inline). The current tests use 1-hour delays, so no indexed entry ever becomes due in them; a test where one becomes due while disconnected and is left unacked would pin this.

Two smaller points are inline: the Key_Shared no-consumer rewind bypasses the new rewind-position guard, and disabling the policy after a consumer has registered can also duplicate retained entries.

Lock ordering looks fine to me: the timer releases timeoutLock before taking the dispatcher monitor, and the predicate takes only the tracker monitor. The memory-accounting deltas in getScheduledMessages and removeMessagesUpTo also balance, including the -1 and Long.MAX_VALUE boundaries.

@lhotari All three findings are addressed in 3e00fc8. All 177 related tests pass with retries disabled, and sanityCheck passes. Could you approve the workflows for the latest commit and take another look? Thanks!

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

Recommend changes at 3e00fc8. The follow-up fixes the three reported sequences as tested: an entry due before reconnect, the late Key_Shared rewind, and disabling delayed delivery before or after catch-up. All 39 focused tests passed. A remaining race can still dispatch a delayed entry twice if it becomes due while a rewound normal read is in flight.

}
delayedDeliveryRewindPosition = null;
if (delayedDeliveryTracker.orElse(null) instanceof InMemoryDelayedDeliveryTracker tracker) {
tracker.endRewind();

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.

Keep replay-skip markers until the in-flight normal read finishes

A Shared subscription reconnects with an unacknowledged immediate entry A followed by a retained delayed tail entry X; the pre-rewind position is X.next(). A normal read fetches A and queues a continuation at X. X then becomes due, and replay starts before the continuation checks the skip predicate. Another read pass runs before that check, for example from a consumer flow request. That pass can remove the skip marker even though the normal read can still fetch X. The replacement consumer can receive X from both normal dispatch and replay without another reconnect or negative acknowledgment, provided the first copy has not been acknowledged.

The normal read publishes X as the cursor position but also saves X as its own continuation position (OpReadEntry.java:159–168,259–275). Replay can run despite a pending normal read (dispatcher:409–452) and atomically advances the shared position to X.next() when replaying X (ManagedCursorImpl.java:2021–2032). The next pass calls shouldPauseDeliveryForDelayTracker() before checking pending replay, and endRewind() clears the live skip marker using only that shared position. The already-scheduled normal continuation resumes from its own saved X and calls the predicate again (OpReadEntry.java:259–275, ManagedLedgerImpl.java:3229–3242).

Do not retire replay-skip markers based on the shared cursor position while a normal read can still consult them. Check for catch-up at a normal-read completion boundary or require both catch-up and no in-flight normal read before clearing. Add a controlled-clock regression that holds the normal continuation at X, lets replay advance the cursor, then releases the continuation and asserts one delivery.

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 7bb76c7. Replay-skip markers are now cleared only after the cursor catches up and no normal read is pending.

Added controlled-clock regressions for Shared and Key_Shared that pause the normal continuation, let replay advance the cursor, trigger another read pass, and then resume the continuation. Both reproduce duplicate delivery on 3e00fc8 and pass with this fix.

All 179 related tests and sanityCheck pass, with test retries disabled. Could you take another look?

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

LGTM. Thanks for the quick turnaround. All three points from the previous round look addressed:

  • Drained positions now go into a separate replay-marker index while a rewind is in progress (InMemoryDelayedDeliveryTracker.java:270-279), the normal-read predicate stays active while delayedDeliveryRewindPosition is set even when the delayed count is zero, and the markers are dropped only after the cursor has caught up and no normal read is pending (PersistentDispatcherMultipleConsumers.java:1748-1757). A new rewind clears them first, so an unacked replayed entry is read again after another reconnect. testDueWhileDisconnectedIsDeliveredOnce and testDueDuringRewoundNormalReadIsDeliveredOnce cover the path that the 1-hour delays never reached before.
  • The Key_Shared empty-consumer path goes through rewindCursor() and keeps the furthest pre-rewind position (PersistentStickyKeyDispatcherMultipleConsumers.java:416-419).
  • With the policy disabled, indexed entries are handed to replay through drainAllMessages, so they reuse the same skip and marker handoff instead of being read twice.

One optional, minor point inline on ordering when the policy is disabled.

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

LGTM. Thanks for adding the note. The new javadoc on drainAllMessages (InMemoryDelayedDeliveryTracker.java:247-249) matches what getMessages does, so the ordering trade-off is now documented.

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.

[Enhancement] Optimize delayed message delivery by reducing unnecessary reads to storage in InMemoryDelayedDeliveryTracker

3 participants