webtorrent: WebTorrent Memory Leak

What version of this package are you using? WebTorrent 1.8.26

What operating system, Node.js, and npm version? Ubuntu 22.04 Server, Node.JS 18.7.0, NPM 8.15.0

What happened? I created a Discord bot to allow friends to torrent content to my Plex server through the bot without having to ask me. I noticed that memory usage would creep up until the process was eventually killed by systemd for being too swappy. I worked through debugging my code and couldn’t find any obvious leaks, so I made a test app and confirmed that the leak was happening in WebTorrent. Test code is as follows:

const WebTorrent = require('webtorrent');

const client = new WebTorrent();

const magnets = []; //magnet links here - torrents them one at a time after the previous one has finished

client.add(magnets.pop(), { path: './', destroyStoreOnDestroy: false }, (torrent) => { updateProgress(torrent); });

function updateProgress(torrent) {
    // Record whether or not the torrent has completed
    const done = torrent.done;

    console.log(`Downloading '${torrent.name}': ${Math.round(torrent.progress * 100)}%`);

    if(done) {
      torrent.destroy();
      if(magnets.length > 0)
      client.add(magnets.pop(), { path: './', destroyStoreOnDestroy: false }, (torrent) => { updateProgress(torrent); });
    } else {
      setTimeout(() => { updateProgress(torrent); }, 3000);
    }
  }

I took a heapdump of the process running with the Discord bot, and most of the memory is being utilized by system/JSArrayBufferData, specificially in Connection/UTP/Wire. Let me know if you’d like me to post a snapshot of the heapdump.

What did you expect to happen? Chrome’s V8 should garbage collect objects after a torrent has completed.

Are you willing to submit a pull request to fix this bug? If I could be pointed to where the issue lies (whether it be the store, in WebTorrent, etc).

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 37 (13 by maintainers)

Most upvoted comments