Resource Management (cgroup, quota)

Resource management ensures that no single process or user can monopolise system resources. Linux provides two complementary mechanisms: cgroups for controlling resource allocation, and quotas for limiting filesystem usage.

Control Groups (cgroups)

Control groups (cgroups) are a Linux kernel feature that limits, accounts for, and isolates resource usage (CPU, memory, disk I/O, network) of a collection of processes.

cgroups v1 vs v2

  • cgroups v1: Separate hierarchies for each resource (cpu, memory, blkio, etc.).
  • cgroups v2: Unified hierarchy with better consistency and pressure stall information (PSI).

Most modern distributions use cgroups v2. Check with:

mount | grep cgroup

Using cgroups

Cgroups are organised as a filesystem hierarchy. Each cgroup is a directory containing control files:

# Create a cgroup
mkdir -p /sys/fs/cgroup/myapp

# Limit CPU to 50% of one core
echo 50000 > /sys/fs/cgroup/myapp/cpu.max

# Limit memory to 256MB
echo 268435456 > /sys/fs/cgroup/myapp/memory.max

# Add a process
echo 1234 > /sys/fs/cgroup/myapp/cgroup.procs

Systemd and cgroups

Systemd integrates with cgroups, creating a cgroup for each service unit. Control resource usage in unit files:

# /etc/systemd/system/myapp.service
[Service]
CPUQuota=50%
MemoryMax=256M
IOWeight=50

Reload and restart:

systemctl daemon-reload
systemctl restart myapp

Disk Quotas

Disk quotas limit the amount of disk space or number of files a user or group can consume. They are managed with quota.

Enable quotas on a filesystem by adding usrquota,grpquota to the mount options in /etc/fstab:

/dev/sda1 /home ext4 defaults,usrquota,grpquota 0 2

Create quota files and enforce limits:

quotacheck -cum /home
quotaon /home
edquota -u alice

The edquota command opens an editor showing current usage and limits.

ulimit: Per-Process Limits

The ulimit builtin sets per-process resource limits. It is often configured in /etc/security/limits.conf or via PAM:

# /etc/security/limits.conf
alice soft nofile 1024
alice hard nofile 2048
@developers soft nproc 100
@developers hard nproc 150

Systemd also supports per-service limits:

# In a service unit file
[Service]
LimitNOFILE=65536
TasksMax=200