Repository navigation
Fix memory leak in MetricsHandler when scaling is enabled - #357
boutetnico wants to merge 2 commits into
Conversation
|
Thanks for submitting a PR! Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface. Pull requests that are abandoned in draft may be closed due to inactivity. |
|
Thanks for digging into this one @boutetnico. Reading through the PR and refreshing my memory on this area of the code, I wonder if we can actually simplify this entire feature and fix the issue at the same time. If we use the key to generate the event name itself, the event will be unique enough that we don't need to keep a map of listeners since we can just call protected function gatherMetricsFromSubscribers(Application $application, string $type, array $options = []): PromiseInterface
{
$this->metrics[$key = Str::random(10)] = []; // Namespace the metrics using the key
$deferred = $this->listenForMetrics($key);
$this->requestMetricsFromSubscribers($application, $key, $type, $options);
return timeout($deferred->promise(), 10)->then(
function ($metrics) use ($listener) {
$this->pubSubProvider->stopListening($key); // The call to stopListening removes all listeners for this key
return $metrics;
},
function () use ($listener) {
$this->pubSubProvider->stopListening($key);
return $this->metrics[$key];
},
)->then(fn ($metrics) => $this->mergeSubscriberMetrics($metrics, $type));
}
protected function listenForMetrics(string $key): Deferred
{
$deferred = new Deferred;
$this->pubSubProvider->on("metrics-retrieved-{$key}", function ($payload) use ($key, $deferred) {
$this->metrics[$key][] = $payload['payload']; // Append the metrics for each publisher for the given key
if ($this->subscribers !== null && count($this->metrics[$key]) === $this->subscribers) {
$deferred->resolve($this->metrics[$key]);
unset($this->metrics[$key]); // Clean up the metrics array
}
});
return $deferred;
}
public function publish(Application $application, string $key, string $type, array $options = []): void
{
$this->pubSubProvider->publish([
'type' => "metrics-retrieved-{$key}", // Publish using the correct unique key
'key' => $key,
'application' => serialize($application),
'payload' => $this->get($application, $type, $options),
]);
}Am I missing something here or do you think it could work this way? |
|
Converting to draft while feedback is addressed @boutetnico ... mark as ready for review when you want me to take a look please. 🙏 |
|
Thanks for the feedback @joedixon! I refactored the implementation to match your approach. Changes
About
|
|
Hey @boutetnico thanks for the updates. I took what you had and took the opportunity to clean things up a bit in a new PR Would you be able to take it for a spin and make sure things behave as you would expect in that you get the correct metrics when requested and memory is stable? I need to add some more tests, but would love a manual test against your benchmarks to make sure we're still in a good spot if you have a minute 🙏 |
|
Closing in favor of #359. |
Fixes #331.
Problem
When
REVERB_SCALING_ENABLED=true, theMetricsHandler::gatherMetricsFromSubscribers()method registers a new event listener via$this->pubSubProvider->on('metrics-retrieved', ...)for every API request to/connections,/channels, or/channels/{channel}/usersendpoints. These listeners are never removed, causing unbounded memory growth and CPU degradation.Solution
This PR adds proper listener cleanup by:
off()method toPubSubProviderinterface - Allows removing previously registered event listenersRedisPubSubProvider- Usesspl_object_id()to map original callbacks to their wrapper closures, enabling proper removal viaremoveListener()removeListener()toRedisClient- Delegates to the underlying Clue Redis client'sremoveListener()methodMetricsHandler- Callsoff()in both success and timeout callbacks to ensure listeners are always removed. Also resets$metricsand$subscribersstate at the start of each gather to prevent stale data accumulationNote: This adds a new method to the
PubSubProviderinterface. Custom implementations will need to implement theoff()method.Test Results
Tested with 3 Reverb instances (horizontal scaling via Redis pub/sub) under sustained load at ~20 requests/second for 1 hour.
The memory leak causes ~3.2 KB leaked per API call, but the real issue is CPU degradation: each accumulated listener fires on every Redis message, causing the event loop to become unresponsive.
How to Reproduce / Test
1. Start Reverb with scaling enabled
Ensure Redis is running and your
.envhas:Start Reverb:
2. Run the load test script
Save this as
test-memory-leak.jsand run with:You can find your app credentials in
config/reverb.phpor your.envfile.3. Monitor memory usage
In another terminal:
Expected Results
Without this fix: Memory grows steadily and CPU usage climbs. After ~15-20 minutes under moderate load, servers become unresponsive.
With this fix: Memory and CPU remain stable indefinitely.
Changes
src/Protocols/Pusher/MetricsHandler.php- Clean up listeners after metrics retrievalsrc/Servers/Reverb/Contracts/PubSubProvider.php- Addoff()to interfacesrc/Servers/Reverb/Publishing/RedisClient.php- AddremoveListener()methodsrc/Servers/Reverb/Publishing/RedisPubSubProvider.php- Implementoff()with listener trackingtests/Unit/MetricsHandlerTest.php- Integration test verifying MetricsHandler callsoff()tests/Unit/RedisPubSubProviderListenerLeakTest.php- Unit test verifying listener removal in RedisPubSubProvider