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.
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
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
nicemakes 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
nice -n 15 /opt/jobs/compress.sh > /dev/null &
ps -o pid,ni,pri,comm -C compress.sh,video-encode PID NI PRI COMMAND
33 0 19 video-encode
45 15 4 compress.shnice alone prints your current niceness; nice cmd without -n adds 10.
Start a job politely
Run the compression job in the background at niceness 15.
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?
ps -eo pid,ni,pri,%cpu,comm --sort=-%cpu | head -4| Column | Meaning |
|---|---|
NI | niceness (-20 to 19) |
PRI | the kernel's priority in ps's scale: higher = more important here (in top, lower PR is more important; each tool counts differently) |
PID NI PRI %CPU COMMAND
33 0 19 74.8 video-encode
34 0 19 0.6 shop-api
38 0 19 0.4 bashEverything runs at the default niceness 0, including the CPU-hungry encoder.
2. Start the job nicely
nice -n 15 /opt/jobs/compress.sh > /dev/null &
ps -o pid,ni,pri,comm -C compress.sh,video-encode| Part | Meaning |
|---|---|
nice -n 15 | start with niceness 15 (plain nice cmd means +10) |
& | in the background |
ps -C name,name | select processes by command name |
PID NI PRI COMMAND
33 0 19 video-encode
45 15 4 compress.shThe 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.
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
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.
renice: change a running process
renice -n 19 -p $(pgrep video-encode) # one process
renice -n 10 -u rohan # all of a user's processes33 (process ID) old priority 0, new priority 19renice says "priority" but means niceness. The process keeps running, now only on spare CPU. Inside top, press r to do the same interactively.
Calm down a running hog
Lower the video encoder's priority to the minimum, without stopping it.
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
renice -n 19 -p $(pgrep video-encode)
ps -o pid,ni,comm -p $(pgrep video-encode)| Option | Meaning |
|---|---|
-n 19 | the new niceness (19 = the nicest possible) |
-p PID | which process; -u user renices all of a user's processes, -g a process group |
33 (process ID) old priority 0, new priority 19
PID NI COMMAND
33 19 video-encodeSame 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):
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 gzipThat'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:
55 (process ID) old priority 0, new priority 5
renice: failed to set priority for 55 (process ID): Permission deniedThat was appsvc renicing its own shell to 5, then trying to go back to 0.
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
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 intopshows 19.
NI and PRI: two numbers, confusing scales
| Tool | Column | Scale |
|---|---|---|
ps -o ni | NI | niceness, -20…19 (lower = more CPU) |
ps -o pri | PRI | ps's own scale: higher = more important |
top | NI | niceness, same as above |
top | PR | kernel priority: 20 + niceness, so lower = more important; rt = real-time |
When in doubt, look at NI: it's the same everywhere.
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 gzipIn 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:
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 recipeHow 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:
| Meaning | Who can raise it | |
|---|---|---|
| soft | the limit in force now | the process itself, up to the hard limit |
| hard | the ceiling | only root |
Limits are inherited by child processes, which is how a limit set at login applies to everything you start.
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 childrencore 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:
| Limit | ulimit | limits.conf | Why it matters |
|---|---|---|---|
| open files | -n | nofile | every file, socket and connection; databases, web servers and proxies need thousands |
| user processes | -u | nproc | stops fork bombs and runaway process spawning |
| core file size | -c | core | 0 = no crash dumps (default); raise when debugging crashes |
| locked memory | -l | memlock | databases and Elasticsearch lock memory |
| stack size | -s | stack | deep recursion |
Trying to go past the hard limit fails, even for root without the right capability:
bash: line 1: ulimit: open files: cannot modify limit: Operation not permittedulimit -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":
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:
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:
# /etc/security/limits.d/appsvc.conf
appsvc soft nofile 4096
appsvc hard nofile 8192
@devops hard nproc 500
* soft core 0Columns: who (a user, @group or *), soft/hard (or - for both), which limit, the value. New sessions pick it up; running ones don't.
4096
8192
open-file limit: soft=4096 hard=8192
opened 3000 product images: OKA new su session for appsvc after the change above.
Too many open files
Raise the appsvc account's open-file limit so the image service works.
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
ulimit -a
ulimit -n; ulimit -Hnulimit -a = all soft limits of this shell; -n open files; -Hn the hard limit.
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
8192Your shell may open 4096 files (soft), and could raise that to 8192 (hard).
2. The image service fails
su -s /bin/bash appsvc -c 'ulimit -n; python3 /opt/shop/imgsvc.py'
cat /etc/security/limits.d/appsvc.conf1024
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 1024A 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:
appsvc soft nofile 4096
└─┬──┘ └─┬┘ └──┬─┘ └─┬┘
user or soft/ which value
@group hard limitprintf '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'4096
8192
open-file limit: soft=4096 hard=8192
opened 3000 product images: OKA 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".
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
printf 'appsvc soft nofile 4096\nappsvc hard nofile 8192\n' > /etc/security/limits.d/appsvc.confWhat each part does
printf '...\n...\n' > FILE: write two lines into a new file in/etc/security/limits.d/.- Each line: user,
softorhard, 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.
systemd services
Services started by systemd don't go through PAM, so limits.conf has no effect on them. Set limits in the unit:
[Service]
LimitNOFILE=65536
LimitNPROC=4096
LimitCORE=infinityThen 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
prlimit --pid $(pgrep shop-api) --nofile
prlimit --pid $(pgrep shop-api) --nofile=4096:8192
prlimit --pid $(pgrep shop-api) --nofileRESOURCE 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 filesA 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.
Fix a running process
Raise the running API server's open-file limit without restarting it.
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
grep -E 'Limit|open files' /proc/$(pgrep shop-api)/limits
prlimit --pid $(pgrep shop-api) --nofileLimit Soft Limit Hard Limit Units
Max open files 1024 8192 files
RESOURCE DESCRIPTION SOFT HARD UNITS
NOFILE max number of open files 1024 8192 filesBoth show the same thing: /proc/PID/limits is where the kernel publishes it, and prlimit reads it for you.
2. Raise it live
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.
RESOURCE DESCRIPTION SOFT HARD UNITS
NOFILE max number of open files 4096 8192 filesThe 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:
timeout 2 sleep 10; echo "exit code: $?"exit code: 124timeout 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).
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
prlimit --pid $(pgrep shop-api) --nofile=4096:8192What 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 withgrep 'open files' /proc/PID/limits.
timeout: limit the run time
timeout 2 sleep 10; echo "exit code: $?"
timeout -k 5 300 ./deploy.sh # SIGTERM after 300 s, SIGKILL 5 s laterexit code: 124124 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:
| Tool | Example | Effect |
|---|---|---|
| systemd unit | CPUQuota=50%, MemoryMax=512M | the service and all its children together |
| Docker | docker run --cpus=1.5 --memory=512m | the container |
| Kubernetes | resources.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/PRuse different scales in different tools.ionice -c 3for 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. timeoutcaps run time (exit 124). cgroups cap whole services and containers.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.