How to Set CPU and Memory Limits Using Linux Control Groups (cgroups)

Added:

The Case for Dynamic Soft Limits and Share-Based Allocation

While setting strict, hard limits on CPU and memory via cgroups ensures containment, it often leads to operational inefficiencies and instability. Hard CPU limits introduce artificial latency spikes and throttling, even when the host has idle capacity. Similarly, hard memory limits risk triggering the Linux Out-Of-Memory (OOM) killer, which abruptly terminates processes rather than allowing graceful degradation. An alternative perspective advocates for soft limits and share-based allocation (such as `cpu.shares` or `cpu.weight`). This approach allows processes to dynamically burst and utilize idle hardware capacity during spikes, enforcing constraints only during active resource contention. This maximizes hardware utilization and improves application resilience.

Basic Linux command-line proficiency and process management concepts, including process IDs (PIDs) and tools like 'ps', 'top', or 'htop'.
Fundamental understanding of operating system resource allocation, specifically how the kernel schedules CPU time and manages RAM and swap memory.
Familiarity with the Linux virtual filesystem concept, as cgroups are configured and monitored through the hierarchical file interface under '/sys/fs/cgroup'.
Understanding of administrative privileges (superuser/root) and the usage of 'sudo' to modify kernel-level configurations.
Exploring the structural and functional differences between legacy cgroups v1 and the modern, unified hierarchy of cgroups v2.
Understanding how containerization technologies like Docker, containerd, and LXC leverage cgroups to enforce runtime resource limits on containers.
Implementing systemd slice and scope configurations to manage and restrict resource usage of system services and user sessions natively.
Configuring additional cgroup resource controllers, such as block I/O (blkio) bandwidth limits and network traffic controller (net_cls) tagging.
Using stress-testing tools (like 'stress-ng') to benchmark system performance and verify that cgroup limits are actively and correctly restricting processes.
616 views10likes36:13@onpremaOriginal Release: 2025-07-13

Linux cgroups (control groups) are kernel features that allow processes to be organized into hierarchical groups whose CPU and memory usage can be limited and monitored. To set resource limits, create a cgroup directory in /sys/fs/cgroup, configure CPU limits by writing to the CPU.max file (e.g., '10000 100000' for 10% CPU), configure memory limits by writing to memory.max (e.g., '500m' for 500MB), and add a running process to the cgroup by writing its PID to the cgroup.procs file. When a process exceeds its memory limit, the kernel's OOM killer terminates it, protecting the system from resource exhaustion.