mediasoup: Memory leak in mediasoup c++ worker
Bug Report
Your environment
- Operating system: Debian
- Node version: v16.14.0
- npm version: 8.3.1
- gcc/clang version: gcc (Debian 10.2.1-6) 10.2.1 20210110
- mediasoup version: v3.9.3
- mediasoup-client version:
Issue description
C++ worker doesn’t free memory once all participant left and router is closed with router.close.
So I create one router on one worker on one cpu, then create meeting with some participant(~30-40) I see ram usages go up to ~600 MBs then all participant left and router got closed. but I can see that mediasoup worker is still taking the same amount of memory.
This heavily affects big meetings happening on routers. I have also opened a discussion on forum.

About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 43 (36 by maintainers)
This is probably related to the leak I’m seeing in v3. So I’m going to reuse this issue.
STR:
mediasoup-workermemory usageWhat happens?
mediasoup-worker memory is not released
What should happen?
memory should be released
Notes
After some investigations I came to the fact that initialising
bufferhere with a much larger size (262144 instead of 65536) makes the memory to be released.I’m still investigating this issue. I’ve verified that each cloned RTP packet is deleted, so the leak is not that.
@ibc, any idea?
I commeted code from after this line, and ran heap profile again. https://github.com/versatica/mediasoup/blob/ff17d135957513aff86d45d99e82ffce45187318/worker/src/handles/UdpSocketHandler.cpp#L189
It shows RtpStreamSend objects cost most of memory now.
When we
malloca memory < 128K, glibc will callbrk()/sbrk()to alloc memory from sytem, when wemalloca memory >128K, glibc will callmmap()to alloc memory. Memory alloced bymmap()will be release back to the system once we free it. Memory alloced bybrk()will only be release back to the system when there is a contiguous 128K memory on the top of heap.See M_TRIM_THRESHOLD and M_MMAP_THRESHOLD in https://man7.org/linux/man-pages/man3/mallopt.3.html That’s maybe why the memory of a four times size vector will be release as soon as it destructed.
So i think we should make the size of UvDataSend a fixed value to avoid holes in heap, and use memory pool or circular queue, so that glibc can use
mmapto alloc memory, and limit the max number of UvDataSend objects to avoid out of memory in heavy load.