Skip to content

Fix memory leak in MetricsHandler when scaling is enabled - #357

Closed
boutetnico wants to merge 2 commits into
laravel:mainfrom
boutetnico:main
Closed

boutetnico wants to merge 2 commits into
laravel:mainfrom
boutetnico:main

Conversation

@boutetnico

Copy link
Copy Markdown
Contributor

Fixes #331.

Problem

When REVERB_SCALING_ENABLED=true, the MetricsHandler::gatherMetricsFromSubscribers() method registers a new event listener via $this->pubSubProvider->on('metrics-retrieved', ...) for every API request to /connections, /channels, or /channels/{channel}/users endpoints. These listeners are never removed, causing unbounded memory growth and CPU degradation.

Solution

This PR adds proper listener cleanup by:

  1. Adding off() method to PubSubProvider interface - Allows removing previously registered event listeners
  2. Implementing listener tracking in RedisPubSubProvider - Uses spl_object_id() to map original callbacks to their wrapper closures, enabling proper removal via removeListener()
  3. Adding removeListener() to RedisClient - Delegates to the underlying Clue Redis client's removeListener() method
  4. Cleaning up listeners in MetricsHandler - Calls off() in both success and timeout callbacks to ensure listeners are always removed. Also resets $metrics and $subscribers state at the start of each gather to prevent stale data accumulation

Note: This adds a new method to the PubSubProvider interface. Custom implementations will need to implement the off() method.

Test Results

Tested with 3 Reverb instances (horizontal scaling via Redis pub/sub) under sustained load at ~20 requests/second for 1 hour.

Metric Without Patch With Patch
Duration 1 hour 1 hour
Successful calls 17,692 92,925
Memory 87 → 143 MiB (+56 MiB) 85-88 MiB (stable)
CPU 100% (maxed out) ~3%
Errors 38,916 timeouts 0
Throughput Collapsed to 5/s Steady 25/s

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 .env has:

REVERB_SCALING_ENABLED=true

Start Reverb:

php artisan reverb:start

2. Run the load test script

Save this as test-memory-leak.js and run with:

REVERB_APP_ID=your-app-id \
REVERB_APP_KEY=your-app-key \
REVERB_APP_SECRET=your-app-secret \
node test-memory-leak.js

You can find your app credentials in config/reverb.php or your .env file.

#!/usr/bin/env node
/**
 * Reverb Memory Leak Test
 * Hammers the /connections API to test for listener accumulation
 */

const crypto = require('crypto');
const http = require('http');
const https = require('https');

const CONFIG = {
  apiUrl: process.env.API_URL || 'http://localhost:8080',
  appId: process.env.REVERB_APP_ID,
  appKey: process.env.REVERB_APP_KEY,
  appSecret: process.env.REVERB_APP_SECRET,
  parallelRequests: parseInt(process.env.PARALLEL || '10'),
  intervalMs: parseInt(process.env.INTERVAL || '200'),
};

if (!CONFIG.appId || !CONFIG.appKey || !CONFIG.appSecret) {
  console.error('Error: REVERB_APP_ID, REVERB_APP_KEY, and REVERB_APP_SECRET are required');
  console.error('Find these in config/reverb.php or your .env file');
  process.exit(1);
}

let stats = { calls: 0, errors: 0, startTime: Date.now() };

function generateSignature(method, path) {
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const authParams = {
    auth_key: CONFIG.appKey,
    auth_timestamp: timestamp,
    auth_version: '1.0',
  };
  const sortedParams = Object.keys(authParams).sort().map(k => `${k}=${authParams[k]}`).join('&');
  const stringToSign = `${method}\n${path}\n${sortedParams}`;
  const signature = crypto.createHmac('sha256', CONFIG.appSecret).update(stringToSign).digest('hex');
  return `${sortedParams}&auth_signature=${signature}`;
}

function callApi() {
  return new Promise((resolve) => {
    const path = `/apps/${CONFIG.appId}/connections`;
    const url = `${CONFIG.apiUrl}${path}?${generateSignature('GET', path)}`;
    const urlObj = new URL(url);
    const client = urlObj.protocol === 'https:' ? https : http;

    const req = client.get(url, { rejectUnauthorized: false }, (res) => {
      res.on('data', () => {});
      res.on('end', () => { stats.calls++; resolve(); });
    });
    req.on('error', () => { stats.errors++; resolve(); });
    req.setTimeout(5000, () => { req.destroy(); stats.errors++; resolve(); });
  });
}

async function burst() {
  const promises = [];
  for (let i = 0; i < CONFIG.parallelRequests; i++) {
    promises.push(callApi());
  }
  await Promise.all(promises);
}

function report() {
  const elapsed = (Date.now() - stats.startTime) / 1000;
  const rate = (stats.calls / elapsed).toFixed(1);
  console.log(`[${elapsed.toFixed(0)}s] Calls: ${stats.calls}, Rate: ${rate}/s, Errors: ${stats.errors}`);
}

async function main() {
  console.log('Reverb Memory Leak Test');
  console.log('=======================');
  console.log(`Target: ${CONFIG.apiUrl}`);
  console.log(`Rate: ${CONFIG.parallelRequests} requests every ${CONFIG.intervalMs}ms`);
  console.log('');
  console.log('Monitor Reverb memory usage in another terminal:');
  console.log('  watch -n5 "ps -o rss,vsz,pid,command -p $(pgrep -f reverb:start)"');
  console.log('');
  console.log('Press Ctrl+C to stop');
  console.log('');

  setInterval(burst, CONFIG.intervalMs);
  setInterval(report, 5000);

  process.on('SIGINT', () => {
    report();
    console.log('\nTest complete. Check memory growth above.');
    process.exit(0);
  });
}

main();

3. Monitor memory usage

In another terminal:

# For native process
watch -n5 "ps -o rss,vsz,pid,command -p \$(pgrep -f reverb:start)"

# For Docker
watch -n5 "docker stats --no-stream --format 'table {{.Name}}\t{{.MemUsage}}' | grep reverb"

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 retrieval
  • src/Servers/Reverb/Contracts/PubSubProvider.php - Add off() to interface
  • src/Servers/Reverb/Publishing/RedisClient.php - Add removeListener() method
  • src/Servers/Reverb/Publishing/RedisPubSubProvider.php - Implement off() with listener tracking
  • tests/Unit/MetricsHandlerTest.php - Integration test verifying MetricsHandler calls off()
  • tests/Unit/RedisPubSubProviderListenerLeakTest.php - Unit test verifying listener removal in RedisPubSubProvider

@github-actions

Copy link
Copy Markdown

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.

@boutetnico
boutetnico marked this pull request as ready for review December 23, 2025 09:20
@joedixon

joedixon commented Dec 26, 2025 •

Copy link
Copy Markdown
Collaborator

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 removeAllListeners for each event when we are done with it. It would end up looking something like this:

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?

@taylorotwell
taylorotwell marked this pull request as draft December 27, 2025 13:01
@taylorotwell

Copy link
Copy Markdown
Member

Converting to draft while feedback is addressed @boutetnico ... mark as ready for review when you want me to take a look please. 🙏

@boutetnico

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback @joedixon! I refactored the implementation to match your approach.

Changes

  • Unique event names per request (metrics-retrieved-{$key}) instead of shared event
  • Metrics stored per key in $this->metrics[$key]
  • Cleanup with stopListeningForMetrics($key) in finally()

About removeAllListeners()

I checked using removeAllListeners() but all listeners are on the 'message' event with filtering in the wrapper. Using removeAllListeners('message') would also remove the handler from subscribe().

So I track wrappers in $eventListeners and remove them with removeListener(). Same result.

Testing

  • 1-hour stress test (~700k requests at 495/s) - memory stable at ~88-90 MiB
  • Running in production, memory and CPU stable

Let me know if you want changes!

@joedixon joedixon mentioned this pull request Jan 2, 2026
@joedixon

joedixon commented Jan 2, 2026

Copy link
Copy Markdown
Collaborator

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 🙏

@boutetnico

Copy link
Copy Markdown
Contributor Author

Closing in favor of #359.

@boutetnico boutetnico closed this Jan 2, 2026
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.

Memory leaks and high CPU usage

3 participants