Course contentsShow
← Linux
Lesson 503 of 1,8195. Process Management and SignalingFree lesson

Resource Throttling via Cgroups

Apply limits on CPU and memory usage to prevent rogue processes from degrading system performance.

In this lesson, you will learn how to use Control Groups (cgroups) to partition hardware resources and prevent runaway processes from consuming your entire system.

The Concept of Resource Throttling

While signals like SIGTERM allow you to kill a misbehaving process, sometimes you simply want to prevent a process from "hogging" resources without stopping it entirely. Cgroups (Control Groups) provide a way to group processes and apply hard limits to their consumption of CPU and memory. Think of cgroups as a "speed governor" or "budget" for your applications.

Applying CPU Limits

When a process enters an infinite loop, it can spike your CPU to 100%, causing the system to become unresponsive. By using cgroups, we can tell the kernel that a specific group of processes is only allowed to use, for example, 20% of a single CPU core.

If you were to create a cgroup called restricted_app, you would interact with the virtual filesystem (usually found at /sys/fs/cgroup/). To limit CPU usage, you modify the cpu.max file:

# Set a limit: 20000 microseconds of quota every 100000 microseconds period (20%)
echo "20000 100000" > /sys/fs/cgroup/restricted_app/cpu.max

Applying Memory Limits

Unlike CPU, which is a temporal resource, memory is a capacity resource. If a process attempts to allocate more memory than it is permitted, the kernel will step in. Depending on your configuration, the kernel may trigger an OOM (Out Of Memory) event specifically for that group, effectively killing the process before it can drain the system's RAM and trigger a global crash.

To limit memory for our restricted_app:

# Limit the group to 512 Megabytes
echo "512M" > /sys/fs/cgroup/restricted_app/memory.max

By placing a process into this group, you ensure that even if the code enters a memory leak or an intensive calculation loop, it remains confined within its assigned boundaries. This prevents local performance issues from cascading into a full system lockup.

Key Takeaway: Cgroups allow you to define hard resource boundaries for processes, ensuring that individual applications cannot exhaust system capacity and degrade overall stability.