Skip to content

[improve][broker] Keep the Key_Shared consistent hashing ring in arrays - #26863

Merged
merlimat merged 1 commit into
masterfrom
lh-improve-key-shared-selector-footprint
Oct 12, 2026
Merged

merlimat merged 1 commit into
masterfrom
lh-improve-key-shared-selector-footprint

Conversation

@lhotari

@lhotari lhotari commented Oct 12, 2026

Copy link
Copy Markdown
Member

Fixes #26862

Motivation

ConsistentHashingStickyKeyConsumerSelector, the default selector of Key_Shared subscriptions, kept three copies of its hash ring:

  • the ring itself, a TreeMap<Integer, HashRingPointEntry>: a TreeMap.Entry, a boxed Integer and a HashRingPointEntry per ring point;
  • the arrays it publishes for the lookups;
  • with draining hashes tracking, which AUTO_SPLIT mode without out-of-order delivery uses, a ConsumerHashAssignmentsSnapshot: a Range and a HashRangeAssignment per ring point, kept to diff with the next snapshot on every membership change.

With the default 100 ring points per consumer (subscriptionKeySharedConsistentHashingReplicaPoints), that cost about 25 KB of heap per consumer. In #26862, consumers whose connections disappeared without the broker noticing reconnected while the broker kept their old consumers. The broker held 11,971 consumers for a workload of 6,000, and its 512 MB heap ran out: about 297 MB of the 571 MB heap dump was the Key_Shared dispatchers and selectors.

Every membership change also rebuilt the full snapshot and diffed it with the previous one. When all consumers of many subscriptions reconnect at once, this work runs on the I/O threads that also serve the producers.

Modifications

  • Keep the hash ring only in the published arrays: the sorted ring points and the consumer selected at each point. A membership change builds new arrays, in one pass, and publishes them; the published arrays are never modified, as before.
  • Resolve the hash ranges that a membership change moved between consumers by walking the points of the previous and the new ring, instead of building and diffing snapshots. A hash belongs to the consumer of the first point at or after it, so a single pass over both rings' points gives each range whose consumer changed. The result has the same content as the snapshot diff. A change that didn't change the ring returns an empty result without the walk.
  • Keep each consumer's sorted points while it's in the ring, so that removing it doesn't calculate its 100 points again.
  • Keep consumers whose ring point collided with another consumer's in a map by point, created when the first collision happens. A colliding consumer is still selected when the selected one leaves.
  • Build getConsumerKeyHashRanges(), which the subscription stats use, straight from the ring in one pass, and getConsumerHashAssignmentsSnapshot() from the ring on request, instead of keeping a snapshot.
  • Membership changes are serialized with a ReentrantLock; the lookups and the stats read the published ring without locking.

The heap cost becomes 12 bytes per ring point, the ring's two arrays and the consumer's points, about 1.2 KB per consumer with 100 points plus the arrays' headers and a map entry per consumer (computed, not measured).

Heap saving

The selectors' heap drops from about 25 KB to about 1.2 KB per Key_Shared consumer, about 20 times less: for 10,000 Key_Shared consumers, from about 250 MB to about 12 MB. The broker's heap then has room for situations where the consumers' count or their pending messages grow:

  • Consumers that reconnect while the broker still holds their old consumers, as in [Bug] Broker runs out of heap when Key_Shared consumers reconnect after their connections vanish silently #26862: with network/silent-client-disconnect, a 512 MB broker ran out of heap in 2 runs out of 2 on master, with a heap dump of 593 MB. With this change, it didn't in 3 runs out of 3, and the heap dump at the highest heap usage was 306 MB.
  • Slow consumers: network/constrained-consumers limits the broker's traffic to the consumers to 5 Mbit/s, about half of their traffic, for 60 s. On master, the 512 MB broker ran out of heap 14 s after the limit ended, in 2 runs out of 2: the messages dispatched to the slow consumers and not yet acknowledged, 105,000–243,000 of them, on top of the Key_Shared selectors' state. The restart then stalled every producer for 20–40 s. With this change, the broker didn't run out of heap in 2 runs out of 2. With a 4 GB broker, master didn't either.

Verifying this change

  • Make sure that the change passes the CI checks.

This change added tests and can be verified as follows:

  • ConsistentHashingStickyKeyConsumerSelectorTest.testImpactedConsumersMatchAssignmentsDiff makes 4,000 random membership changes, with 1–30 ring points on a hash range of 63, so that points collide often, also among one consumer's own points. After each change, it compares the impacted consumers that the selector returns with the diff of the assignment snapshots before and after, the computation that the selector used before, compares getConsumerKeyHashRanges() with the snapshot's ranges, and checks every hash's lookup against the assignments.
  • New tests for a consumer added twice, a selector without replica points, and a hash range that ends at Integer.MAX_VALUE.
  • The existing tests pass: ConsistentHashingStickyKeyConsumerSelectorTest, ConsumerHashAssignmentsSnapshotTest, PersistentStickyKeyDispatcherMultipleConsumersTest, NonPersistentStickyKeyDispatcherMultipleConsumersTest, KeySharedSubscriptionTest, DrainingHashesTrackerTest and the other selector tests.
  • KeySelectorLookupBenchmark.reconnectAllConsumers is a new benchmark: every consumer of a subscription reconnects, so the selector removes all of them and adds them back. Results on Linux x86_64 (i9-9980HK, with the performance environment of the Pulsar Performance Testing Framework: fixed CPU frequency, no turbo), 2 forks × 5 iterations of 2 s, with the time and the allocation per operation:
Benchmark Consumers master This change
reconnectAllConsumers 1 26.8 µs, 37 KB 19.0 µs, 19 KB
reconnectAllConsumers 10 1,773 µs, 1.44 MB 601 µs, 0.38 MB
reconnectAllConsumers 50 29,233 µs, 21.9 MB 6,611 µs, 3.8 MB
changeMembership 2 114 µs, 106 KB 35 µs, 35 KB
changeMembership 50 805 µs, 802 KB 192 µs, 125 KB
select 50 108 ns 104 ns

The network-condition scenarios of the Pulsar Performance Testing Framework in #26859, on iot-telemetry-small: 6,000 Key_Shared consumers in 600 subscriptions on one broker, with the performance environment on, master and this change on the same base. The image with this change also had two fixes for a broker that loses its metadata session, one of them #26861, which act only when the session is lost, which doesn't happen in these scenarios:

Scenario master This change
network/silent-client-disconnect, broker heap 512 MB OutOfMemoryError 15 s after the consumers' silent disconnection, in 2 runs out of 2; heap dump 593 MB No OutOfMemoryError in 3 runs; the heap dump at the highest heap usage was 306 MB
The same, broker heap 768 MB 3 Key_Shared ordering violations in each of 2 runs none in 2 runs
The same, broker heap 4 GB none in 1 run none in 1 run
network/consumer-reconnect-storm, a reset during the warmup and one 30 s into the measurement, publish latency max 1.46 s, 2.20 s 0.75 s, 0.54 s
The consumers' connections reset once, 30 s into the measurement, publish latency max 3.71 s, 3.15 s 2.70 s, 1.94 s, 1.83 s, 2.31 s
network/constrained-consumers, broker heap 512 MB OutOfMemoryError in 2 runs out of 2 No OutOfMemoryError in 2 runs

About the reconnect storm: a broker profile of the reset with this change showed that the selector's share of the stall is small. The broker used 9–10 cores for about 3 s, half of them the JIT recompiling the dispatch paths, while the host's 16 hardware threads were 14–15 busy with the broker and the 200 reconnecting clients on the same host. The pulsar-io threads also blocked on the log appender's lock for the 18,000 INFO lines of the subscriptions, but the same runs with the broker's log level at WARN stalled as long (2.03 s and 1.39 s), so the logging isn't what limits it. This change mitigates the storm without fixing it.

About the ordering violations: with a 512 MB heap, one of the three runs with this change had 3 ordering violations, and with 768 MB, master had them in both runs. They come from an existing problem of Key_Shared dispatching while the old consumers stay registered after their connections vanished, which this change makes rarer by leaving more heap, not one this change introduces: a read in flight when the keep-alive removes an old consumer can dispatch a newer entry of a moved hash before the removed consumer's older pending entry. It will be reported and fixed separately.

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

If the box was checked, please highlight the changes

  • 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

ConsistentHashingStickyKeyConsumerSelector kept its hash ring three times: a TreeMap with an entry,
a boxed Integer and a HashRingPointEntry per ring point, the published lookup arrays, and with
draining hashes tracking a ConsumerHashAssignmentsSnapshot with two objects per ring point. That
cost about 25 KB of heap per Key_Shared consumer with the default 100 ring points, and every
membership change rebuilt and diffed the full snapshot.

- Keep the ring only in the published arrays, rebuilt in one pass on a membership change.
- Resolve the hash ranges that moved between consumers by walking the previous and the new ring's
  points together, instead of building and diffing snapshots.
- Keep each consumer's sorted points while it's in the ring, and colliding consumers in a map by
  point, created at the first collision.
- Build the stats' hash ranges and the assignments snapshot from the ring on request.

The heap cost becomes about 1.2 KB per consumer with 100 ring points.

Fixes #26862

Assisted-by: Claude Code (claude-opus-5-5)
@merlimat
merlimat merged commit 4662d56 into master Oct 12, 2026
44 checks passed
@merlimat
merlimat deleted the lh-improve-key-shared-selector-footprint branch October 12, 2026 19:14
lhotari added a commit that referenced this pull request Oct 12, 2026
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] Broker runs out of heap when Key_Shared consumers reconnect after their connections vanish silently

3 participants