Limit MongoDB memory usage using Cgroup on Linux...

The container technology makes everyone forget that Cgroup allows to limit process resource in the Linux operating system. This guide shows a practical way to limit MongoDB hunger for memory on Linux Ubuntu / Debian OS.

Let’s assume you have an updated system for early 2019. In my case, I’m running a kernel 4.6 on Linux Debian Buster and MongoDB 4 is running as service. 
To enable the cgroup we need to install this package.

sudo apt-get install cgroup-tools

Debian, by default, disables the memory controller, we can enable it adding the following in /etc/default/grub.

GRUB_CMDLINE_LINUX_DEFAULT=”quiet cgroup_enable=memory swapaccount=1

This line modified the configuration of Grub which is the tool responsible to start the operating system. When you boot your computer, grub allows to select between Windows, Linux versions. 
Let’s propagate the configuration to the actual Grub boot-loader.

sudo update-grub

Now the environment and tools are ready, we will define some “roles” in /etc/cgconfig.conf

group mongod {
 cpu {
 cpu.shares = 800;
 memory {
 memory.limit_in_bytes = 2000000000;

This configuration creates the following limitation:

  • CPU usage ≤ 80% ( = 800)
  • Memory usage≤ 2GB (= 2e+9 = 2_000_000_000)

Now we need to associate the “roles’ with an actual application. To do so, edit /etc/cgrules.conf

*:mongod cpu,memory mongod

To apply the cgroup limit, you need to stop mongod service if it’s running.

service mongod stop

Then enable the cgroup.

cgconfigparser -l /etc/cgconfig.conf 

Then start mongodb as a service

service mongod start

To make this change persistent, you can add these 2 lines to /etc/rc.localThis file is automatically call after a reboot.

Now let’s check if the limitation is applying properly.
To display the current rules applied to a process like mongod.

pid=` pidof mongod `
cat /proc/$pid/cgroup

To check the actual memory in “RES” column. RES stands for the resident size, which is an accurate representation of how much actual physical memory a process is consuming. This value should be ≤ 2 GB

top -p $pid

or a more modern version of htop

htop -p $pid

More reading.