Skip to content

KAFKA-20398: Fix memory leak by removing StreamsThreadMetricsDelegatingReporter from metrics registry on thread - #21989

Merged
lucasbru merged 1 commit into
apache:4.2from
sstremler:KAFKA-20398-remove-metrics-reporter-from-registry-on-shutdown-in-v4.2
Apr 8, 2026
Merged

lucasbru merged 1 commit into
apache:4.2from
sstremler:KAFKA-20398-remove-metrics-reporter-from-registry-on-shutdown-in-v4.2

Conversation

@sstremler

Copy link
Copy Markdown
Contributor

When a stream thread in Kafka Streams crashes,
StreamsUncaughtExceptionHandler can be configured to replace the
crashed thread with a new one. Each time a new stream thread is created,
it adds a new StreamsThreadMetricsDelegatingReporter to it. However,
when the old thread shuts down, its reporter is never removed from the
registry implying "unbounded" memory growth.

This bug was introduced via #17021

This PR ensures that the existing
StreamsThreadMetricsDelegatingReporter is removed when a thread is
shutting down.

Reviewers: Matthias J. Sax matthias@confluent.io, Bill Bejeck
bbejeck@apache.org

…ngReporter from metrics registry on thread shutdown

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

Fixes an unbounded-memory-growth issue in Kafka Streams where StreamsThreadMetricsDelegatingReporter instances accumulated in the shared metrics registry when stream threads were replaced after crashes, by ensuring the per-thread reporter is removed during thread shutdown.

Changes:

  • Persist the per-thread StreamsThreadMetricsDelegatingReporter on StreamThread and remove it from the Metrics registry during shutdown.
  • Update StreamThread construction sites to pass the new reporter reference.
  • Add a regression test asserting the reporter is removed after shutdown.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java Stores the thread metrics reporter and removes it from the metrics registry in completeShutdown; adds package-private access to streamsMetrics for test verification.
streams/src/test/java/org/apache/kafka/streams/processor/internals/StreamThreadTest.java Adjusts constructor calls for the new parameter and adds a test validating reporter removal on shutdown.

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

@lucasbru
lucasbru merged commit ac44bba into apache:4.2 Apr 8, 2026
17 checks passed
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