How to Monitor and Limit Resource Usage with cgroups or cpulimit Print

  • cpu limit, monitor, resource, cgroups, cpulimit
  • 0

If you want to prevent a process from using excessive CPU or memory on your Linux VPS, tools like cgroups and cpulimit can help. This guide explains how to monitor and limit resource usage using both methods.

 


 

Why Limit Resource Usage?

• Prevent a single process from slowing down or crashing your server

• Manage performance on multi-user or multi-app environments

• Control rogue scripts or background tasks

• Improve overall server stability

 


 

Option 1: Limit CPU Usage Using cpulimit

 

What is cpulimit?

 

cpulimit restricts the CPU usage of a single process by PID or process name.

 

Step 1: Install cpulimit

 

Debian/Ubuntu:

apt install cpulimit

CentOS/AlmaLinux:

yum install epel-release
yum install cpulimit

Step 2: Run a Process with Limited CPU

 

To limit a command or script to 30% CPU:

cpulimit -l 30 -- your_command_here

Example:

cpulimit -l 30 -- dd if=/dev/zero of=/dev/null

Step 3: Limit an Existing Process by PID

 

First, find the process ID:

ps aux | grep process_name

Then:

cpulimit -p PID -l 30
Replace PID with the actual process ID.

 


 

Option 2: Control CPU/Memory with cgroups (Control Groups)

 

What are cgroups?

 

Control Groups (cgroups) allow fine-grained control over CPU, memory, I/O, and more. You can assign limits to groups of processes.

 

Step 1: Install Required Tools

 

Ubuntu/Debian:

apt install cgroup-tools

CentOS/AlmaLinux:

yum install libcgroup-tools

Step 2: Create a cgroup

 

Example to limit CPU:

cgcreate -g cpu:/limited

Limit the CPU to 20%:

echo 20000 > /sys/fs/cgroup/cpu/limited/cpu.cfs_quota_us
echo 100000 > /sys/fs/cgroup/cpu/limited/cpu.cfs_period_us

Step 3: Add a Process to the cgroup

 

Run a process in that group:

cgexec -g cpu:limited your_command_here

Or move an existing PID into it:

echo PID > /sys/fs/cgroup/cpu/limited/cgroup.procs
Replace PID with your target process ID.

 


 

Monitoring Usage

 

Use htop, top, or ps to monitor CPU/memory usage. You can also view live usage inside cgroups:

cat /sys/fs/cgroup/cpu/limited/cpuacct.usage

 

 


 

Best Practices

• Use cpulimit for temporary or simple limits on individual processes

• Use cgroups for more advanced, persistent control over system resources

• Always test limits on a staging server before applying to production workloads

 


 

Conclusion

 

By using cpulimit or cgroups, you can prevent processes from consuming too many system resources and keep your VPS stable. These tools are especially useful for managing background jobs, scripts, or multi-user environments.

 

For help managing server resources, contact Hosteons Support or access the VNC console via https://vps.hosteons.com if your server becomes unresponsive.

 


Was this answer helpful?

« Back