Learn / Linux / Processes & System
Lesson 25 of 74

Priorities and Resource Limits

How the scheduler shares the CPU, niceness from -20 to 19, nice and renice, NI vs PRI in ps and top, disk priority with ionice, resource limits with soft and hard values, ulimit, /etc/security/limits.d, systemd's LimitNOFILE, prlimit for running processes, timeout, and how cgroups cap whole services and containers.

20 min read Report a problem Hands-on lab included 6-question quiz

Sharing a server fairly

A server runs hundreds of processes on a handful of CPU cores. Most of the time they're sleeping, but when more of them want the CPU than there are cores, the kernel's scheduler decides who runs next and for how long.

Left alone, the scheduler treats everyone roughly equally. That's often not what you want:

  • A nightly backup shouldn't slow down customers browsing the shop.
  • A video encode should use spare CPU, not steal it.
  • One buggy program shouldn't be able to open a million files or start a million processes and take the server down.

Two tools handle this: priorities decide who goes first, and limits cap what one process may use.

Niceness

Every process has a niceness value from -20 to 19. The name says it all: a "nice" process lets others go ahead of it.

Niceness scale

-20greediest · root only
-5important services
0default for everything
10default for nice cmd
19nicest · only spare CPU

Each step is about 10% more or less CPU relative to a neighbour: a nice-0 process gets roughly 10× the CPU of a nice-10 one when both want it.

Important facts:

  • Niceness only matters under contention. On an idle CPU, a nice-19 job runs at full speed.
  • Children inherit niceness, so starting a script with nice makes everything it launches nice too.
  • Anyone can make their own processes nicer. Only root can make a process greedier, or use negative values.

nice: start with a niceness

bash
nice -n 15 /opt/jobs/compress.sh > /dev/null &
ps -o pid,ni,pri,comm -C compress.sh,video-encode
text
    PID  NI PRI COMMAND
     33   0  19 video-encode
     45  15   4 compress.sh

nice alone prints your current niceness; nice cmd without -n adds 10.

Try it · Task 1 of 4

Start a job politely

Run the compression job in the background at niceness 15.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

nice starts a command with a given niceness. Batch work like backups, compression and report generation should always run "nice", so customer-facing processes win whenever the CPU is contended.

1. Who's using the CPU, at what priority?

bash
ps -eo pid,ni,pri,%cpu,comm --sort=-%cpu | head -4
ColumnMeaning
NIniceness (-20 to 19)
PRIthe kernel's priority in ps's scale: higher = more important here (in top, lower PR is more important; each tool counts differently)
text
    PID  NI PRI %CPU COMMAND
     33   0  19 74.8 video-encode
     34   0  19  0.6 shop-api
     38   0  19  0.4 bash

Everything runs at the default niceness 0, including the CPU-hungry encoder.

2. Start the job nicely

bash
nice -n 15 /opt/jobs/compress.sh > /dev/null &
ps -o pid,ni,pri,comm -C compress.sh,video-encode
PartMeaning
nice -n 15start with niceness 15 (plain nice cmd means +10)
&in the background
ps -C name,nameselect processes by command name
text
    PID  NI PRI COMMAND
     33   0  19 video-encode
     45  15   4 compress.sh

The compression job runs at niceness 15, so its priority is far below the encoder's. Child processes inherit niceness: every gzip it starts is nice too.

Anyone can make their processes nicer (raise niceness). Only root may make them greedier (lower it, or go below 0). On this lab machine even root can't go below 0, because the container isn't given that capability; on a normal server root can.

2 · Your task

Start /opt/jobs/compress.sh in the background with niceness 15.

Expected result: ps -o pid,ni,comm -C compress.sh shows NI 15.

Hint: the commands, explained
text
nice -n 15 /opt/jobs/compress.sh > /dev/null &

What each part does

  • nice -n 15 COMMAND: start the script with niceness 15 (range -20 to 19; higher = lower priority), so it only gets CPU time other processes don't need.
  • > /dev/null &: discard its output and run it in the background, so your prompt comes back.
First start the lab machine in the terminal panel on the right.

renice: change a running process

bash
renice -n 19 -p $(pgrep video-encode)   # one process
renice -n 10 -u rohan                   # all of a user's processes
text
33 (process ID) old priority 0, new priority 19

renice says "priority" but means niceness. The process keeps running, now only on spare CPU. Inside top, press r to do the same interactively.

Try it · Task 2 of 4

Calm down a running hog

Lower the video encoder's priority to the minimum, without stopping it.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

renice changes the niceness of a process that's already running. It's the gentle alternative to killing a CPU hog: the job keeps going, but only gets the CPU when nothing more important wants it.

1. Renice the encoder

bash
renice -n 19 -p $(pgrep video-encode)
ps -o pid,ni,comm -p $(pgrep video-encode)
OptionMeaning
-n 19the new niceness (19 = the nicest possible)
-p PIDwhich process; -u user renices all of a user's processes, -g a process group
text
33 (process ID) old priority 0, new priority 19
    PID  NI COMMAND
     33  19 video-encode

Same PID, still running, now at the lowest priority. (renice says "priority" but means niceness.)

2. Seeing it in top

top shows niceness in the NI column, and the CPU summary line splits CPU time into us (normal user processes) and ni (niced ones):

text
top - 16:15:11 up  1:30,  0 user,  load average: 0.44, 0.26, 0.20
Tasks:  10 total,   2 running,   8 sleeping,   0 stopped,   0 zombie
%Cpu(s): 52.4 us,  0.0 sy,  0.0 ni, 47.6 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st 
MiB Mem :   8023.6 total,   6544.8 free,    671.7 used,   1061.4 buff/cache     
MiB Swap:      0.0 total,      0.0 free,      0.0 used.   7352.0 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
     33 root      20   0   15536  10260   6824 S  50.0   0.1   0:01.78 video-encode
     60 root      35  15    3432   1976   1360 R  50.0   0.0   0:00.05 gzip

That's top -b -n 1 -o %CPU before the renice: the gzip started by the nice compression job shows NI 15 (and PR 35: in top, a higher PR means lower priority). Inside top you can also press r to renice a process interactively.

A normal user can only raise niceness, never lower it again, even for their own process:

text
55 (process ID) old priority 0, new priority 5
renice: failed to set priority for 55 (process ID): Permission denied

That was appsvc renicing its own shell to 5, then trying to go back to 0.

2 · Your task

Set the running video-encode process to niceness 19, without restarting it.

Expected result: ps -o ni= -p $(pgrep video-encode) prints 19, and it's still the same process.

Hint: the commands, explained
text
renice -n 19 -p $(pgrep video-encode)

What each part does

  • renice -n 19 -p PID: change the priority of an already running process to 19, the lowest. $(pgrep video-encode) supplies its PID.
  • It prints old priority 0, new priority 19. The NI column in top shows 19.
First start the lab machine in the terminal panel on the right.

NI and PRI: two numbers, confusing scales

ToolColumnScale
ps -o niNIniceness, -20…19 (lower = more CPU)
ps -o priPRIps's own scale: higher = more important
topNIniceness, same as above
topPRkernel priority: 20 + niceness, so lower = more important; rt = real-time

When in doubt, look at NI: it's the same everywhere.

text
    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
     33 root      20   0   15536  10260   6824 S  50.0   0.1   0:01.78 video-encode
     60 root      35  15    3432   1976   1360 R  50.0   0.0   0:00.05 gzip

In top: niceness 15 shows as PR 35. In top's summary line, CPU time used by niced processes is counted separately as ni.

Disk priority: ionice

A backup is often limited by the disk, not the CPU, and nice doesn't help there. ionice sets I/O scheduling priority:

bash
ionice -c 3 tar czf /backup/site.tgz /var/www    # class 3 = idle: only when the disk is free
ionice -c 2 -n 7 -p 1234                         # best-effort, lowest level, for a running PID
nice -n 19 ionice -c 3 ./backup.sh               # both: the classic backup recipe

How much ionice achieves depends on the disk's I/O scheduler, but it costs nothing to use for batch work.

Resource limits

Limits cap what a single process may use. Each limit has two values:

MeaningWho can raise it
softthe limit in force nowthe process itself, up to the hard limit
hardthe ceilingonly root

Limits are inherited by child processes, which is how a limit set at login applies to everything you start.

bash
ulimit -a          # all soft limits of this shell
ulimit -n          # open files (soft)
ulimit -Hn         # open files (hard)
ulimit -n 2048     # change the soft limit for this shell and its children
text
core file size              (blocks, -c) 0
file size                   (blocks, -f) unlimited
max locked memory           (kbytes, -l) 8192
open files                          (-n) 4096
max user processes                  (-u) 32017
stack size                  (kbytes, -s) 8192
cpu time                   (seconds, -t) unlimited
virtual memory              (kbytes, -v) unlimited

(The most relevant lines of ulimit -a on a lab machine.)

The limits that matter most in practice:

Limitulimitlimits.confWhy it matters
open files-nnofileevery file, socket and connection; databases, web servers and proxies need thousands
user processes-unprocstops fork bombs and runaway process spawning
core file size-ccore0 = no crash dumps (default); raise when debugging crashes
locked memory-lmemlockdatabases and Elasticsearch lock memory
stack size-sstackdeep recursion

Trying to go past the hard limit fails, even for root without the right capability:

text
bash: line 1: ulimit: open files: cannot modify limit: Operation not permitted

ulimit -n 100000 on a lab machine, whose hard limit is 8192.

"Too many open files"

This is the classic limit problem: a service works fine in testing, then fails under real traffic with EMFILE / "Too many open files":

text
open-file limit: soft=1024 hard=1024
failed after 1021 files: [Errno 24] Too many open files: '/dev/null'

The process had used up its 1024 file descriptors (three of them are stdin, stdout and stderr).

How to investigate:

text
cat /proc/PID/limits | grep 'open files'      # its limit
ls /proc/PID/fd | wc -l                       # how many it has open right now
lsof -p PID | awk '{print $5}' | sort | uniq -c   # what kind: REG files, IPv4 sockets...

If the count keeps growing without bound, the application is leaking file descriptors, and a bigger limit only delays the crash.

Persistent limits: limits.conf

For login sessions (SSH, su, console), limits come from /etc/security/limits.conf and the files in /etc/security/limits.d/, applied by PAM at session start:

text
# /etc/security/limits.d/appsvc.conf
appsvc     soft   nofile   4096
appsvc     hard   nofile   8192
@devops    hard   nproc    500
*          soft   core     0

Columns: who (a user, @group or *), soft/hard (or - for both), which limit, the value. New sessions pick it up; running ones don't.

text
4096
8192
open-file limit: soft=4096 hard=8192
opened 3000 product images: OK

A new su session for appsvc after the change above.

Try it · Task 3 of 4

Too many open files

Raise the appsvc account's open-file limit so the image service works.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Every process has resource limits: the most open files, processes, memory locks, file size and more it may use. Each limit has a soft value (what applies now) and a hard value (the ceiling). A process may raise its soft limit up to the hard limit; only root can raise the hard limit.

The limit that bites most often is open files (nofile). Every file, socket and connection counts. A busy web server, database or image service with the common default of 1024 fails with "Too many open files".

1. Look at the limits

bash
ulimit -a
ulimit -n; ulimit -Hn

ulimit -a = all soft limits of this shell; -n open files; -Hn the hard limit.

text
real-time non-blocking time  (microseconds, -R) unlimited
core file size              (blocks, -c) 0
data seg size               (kbytes, -d) unlimited
scheduling priority                 (-e) 0
file size                   (blocks, -f) unlimited
pending signals                     (-i) 32017
max locked memory           (kbytes, -l) 8192
max memory size             (kbytes, -m) unlimited
open files                          (-n) 4096
pipe size                (512 bytes, -p) 8
POSIX message queues         (bytes, -q) 819200
real-time priority                  (-r) 0
stack size                  (kbytes, -s) 8192
cpu time                   (seconds, -t) unlimited
max user processes                  (-u) 32017
virtual memory              (kbytes, -v) unlimited
file locks                          (-x) unlimited
4096
8192

Your shell may open 4096 files (soft), and could raise that to 8192 (hard).

2. The image service fails

bash
su -s /bin/bash appsvc -c 'ulimit -n; python3 /opt/shop/imgsvc.py'
cat /etc/security/limits.d/appsvc.conf
text
1024
open-file limit: soft=1024 hard=1024
failed after 1021 files: [Errno 24] Too many open files: '/dev/null'
appsvc  soft  nofile  1024
appsvc  hard  nofile  1024

A past admin capped appsvc at 1024 files, soft and hard. The service needs about 3000. (It failed at 1021 because stdin, stdout and stderr already use three.)

3. Raise the limit

Limits for logins and su come from /etc/security/limits.conf and the files in /etc/security/limits.d/, applied by PAM when the session starts. Each line is:

text
appsvc   soft   nofile   4096
└─┬──┘   └─┬┘   └──┬─┘   └─┬┘
 user or  soft/  which     value
 @group   hard   limit
bash
printf 'appsvc  soft  nofile  4096\nappsvc  hard  nofile  8192\n' > /etc/security/limits.d/appsvc.conf
su -s /bin/bash appsvc -c 'ulimit -n; ulimit -Hn; python3 /opt/shop/imgsvc.py'
text
4096
8192
open-file limit: soft=4096 hard=8192
opened 3000 product images: OK

A new session picks up the new limits, and the service works. Sessions that were already running keep their old limits.

Services started by systemd don't read limits.conf. Set their limits in the unit file instead: LimitNOFILE=8192. That's the most common reason "I raised the limit and nothing changed".

2 · Your task

Change /etc/security/limits.d/appsvc.conf so that appsvc gets a soft open-file limit of 4096 and a hard limit of 8192.

Expected result: su -s /bin/bash appsvc -c 'python3 /opt/shop/imgsvc.py' prints "opened 3000 product images: OK".

Hint: the commands, explained
text
printf 'appsvc  soft  nofile  4096\nappsvc  hard  nofile  8192\n' > /etc/security/limits.d/appsvc.conf

What each part does

  • printf '...\n...\n' > FILE: write two lines into a new file in /etc/security/limits.d/.
  • Each line: user, soft or hard, the limit name (nofile = open files), the value. Soft is the starting limit; the user may raise it up to hard.
  • These apply at the user's next login; running processes don't change.
First start the lab machine in the terminal panel on the right.

systemd services

Services started by systemd don't go through PAM, so limits.conf has no effect on them. Set limits in the unit:

text
[Service]
LimitNOFILE=65536
LimitNPROC=4096
LimitCORE=infinity

Then systemctl daemon-reload and restart the service. Check what it actually got with cat /proc/$(pidof nginx | cut -d' ' -f1)/limits.

prlimit: change a running process

bash
prlimit --pid $(pgrep shop-api) --nofile
prlimit --pid $(pgrep shop-api) --nofile=4096:8192
prlimit --pid $(pgrep shop-api) --nofile
text
RESOURCE DESCRIPTION              SOFT HARD UNITS
NOFILE   max number of open files 1024 8192 files
RESOURCE DESCRIPTION              SOFT HARD UNITS
NOFILE   max number of open files 4096 8192 files

A live fix with no restart. Make it permanent in the service's configuration too.

prlimit can also start a command with limits: prlimit --nofile=256 --nproc=50 ./untrusted.sh.

Try it · Task 4 of 4

Fix a running process

Raise the running API server's open-file limit without restarting it.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

limits.conf only affects new sessions. A process that's already running keeps the limits it started with. prlimit can read and change the limits of a running process, which saves a restart during business hours.

1. The running API server's limits

bash
grep -E 'Limit|open files' /proc/$(pgrep shop-api)/limits
prlimit --pid $(pgrep shop-api) --nofile
text
Limit                     Soft Limit           Hard Limit           Units     
Max open files            1024                 8192                 files     
RESOURCE DESCRIPTION              SOFT HARD UNITS
NOFILE   max number of open files 1024 8192 files

Both show the same thing: /proc/PID/limits is where the kernel publishes it, and prlimit reads it for you.

2. Raise it live

bash
prlimit --pid $(pgrep shop-api) --nofile=4096:8192
prlimit --pid $(pgrep shop-api) --nofile

--nofile=SOFT:HARD sets both values; --nofile=4096: would change only the soft one.

text
RESOURCE DESCRIPTION              SOFT HARD UNITS
NOFILE   max number of open files 4096 8192 files

The running process can now open 4096 files. It's a live fix: make it permanent in the service's configuration (LimitNOFILE= for systemd) so it survives the next restart.

3. Limiting time: timeout

A related tool caps how long a command may run:

bash
timeout 2 sleep 10; echo "exit code: $?"
text
exit code: 124

timeout sent SIGTERM after 2 seconds; exit code 124 means "timed out". Use it in scripts and CI so a hung command can't block forever (timeout -k 5 30 cmd adds a SIGKILL 5 s after the SIGTERM).

2 · Your task

Raise the running shop-api process's open-file limit to soft 4096, hard 8192, without restarting it.

Expected result: prlimit --pid $(pgrep shop-api) --nofile shows 4096 and 8192, and the PID is unchanged.

Hint: the commands, explained
text
prlimit --pid $(pgrep shop-api) --nofile=4096:8192

What each part does

  • prlimit --pid PID: change the limits of a process that is already running, without restarting it.
  • --nofile=4096:8192: soft:hard open-file limits. Check with grep 'open files' /proc/PID/limits.
First start the lab machine in the terminal panel on the right.

timeout: limit the run time

bash
timeout 2 sleep 10; echo "exit code: $?"
timeout -k 5 300 ./deploy.sh     # SIGTERM after 300 s, SIGKILL 5 s later
text
exit code: 124

124 means "timed out". In CI pipelines and cron jobs, a timeout around network calls and deployments stops one hung command from blocking everything.

Beyond one process: cgroups

nice and ulimit work per process. To cap a whole service or container, including every process it starts, Linux uses control groups (cgroups). You'll rarely touch them directly, because systemd and container runtimes manage them:

ToolExampleEffect
systemd unitCPUQuota=50%, MemoryMax=512Mthe service and all its children together
Dockerdocker run --cpus=1.5 --memory=512mthe container
Kubernetesresources.limits.cpu: "500m"the container in a pod

A container's "memory limit" and "CPU limit" are cgroup settings: the same kernel feature, managed for you.

Expecting nice to cap CPU. A nice-19 process still uses 100% of an idle core. To cap usage, use a cgroup (CPUQuota=, --cpus).

Raising limits in limits.conf for a systemd service. It has no effect. Use LimitNOFILE= in the unit.

Raising nofile to hide a leak. If the count of open descriptors keeps growing, the app has a bug.

Testing limits in an old session. limits.conf applies to new sessions. Log in again, or start a fresh su -.

"What is niceness?" A value from -20 to 19 that influences how much CPU a process gets when the CPU is contended; higher is nicer (lower priority). Default 0; only root can lower it.

"How do you lower the priority of a running process?" renice -n 19 -p PID, or r in top.

"An app fails with 'Too many open files'. What do you do?" Check /proc/PID/limits and the count in /proc/PID/fd. Raise nofile (limits.d for logins, LimitNOFILE for systemd, prlimit for the running process) and make sure it isn't leaking descriptors.

"Soft vs hard limits?" Soft is in effect; processes can raise it up to the hard limit; only root raises hard limits.

"How do you limit a service's CPU or memory?" cgroups, via systemd (CPUQuota=, MemoryMax=) or the container runtime.

Summary

  • Niceness -20 (greedy) to 19 (nice), default 0, only matters when the CPU is busy. nice -n N cmd, renice -n N -p PID. Users can only raise it.
  • Look at NI; PRI/PR use different scales in different tools. ionice -c 3 for disk-heavy batch work.
  • Limits: soft (current) and hard (ceiling). ulimit -a, -n, -Hn. Open files (nofile) is the usual culprit.
  • Logins: /etc/security/limits.d/. systemd services: LimitNOFILE= in the unit. Running processes: prlimit --pid.
  • timeout caps run time (exit 124). cgroups cap whole services and containers.
Check your understanding

Quick quiz

Feedback