SEO Metadata
SEO Title Options
- Configuring Linux swap: Size, Priority & zram for Better
- Configuring Linux swap: Size, Priority: Practical 2026
- Performance Playbook: Configuring Linux swap: Size
Meta Description Options
- Learn Configuring Linux swap: Size, Priority & zram for Better Performance with a practical Performance framework, expert mistakes, implementation steps.
- Explains swap partitions vs swapfiles, tuning swappiness and vfs_cache_pressure, and setting up compressed zram for low-memory systems.
URL Slug
configuring-linux-swap-size-priority-zram-better-performance
Focus Keyword
Configuring Linux swap: Size, Priority & zram for Better Performance
Additional LSI Keywords
- Performance
- Linux
- Swap
- zram
- Memory
- sysctl
- Configuring Linux swap: Size, Priority & zram for Better Performance
- production checklist
- implementation guide
- best practices
- architecture decisions
- testing strategy
Table of Contents
- Article overview
- What Configuring Linux swap: Size, Priority & zram for Better Performance means
- Why it matters now
- Implementation framework
- Practical comparison
- Expert workflow
- Common mistakes
- Media and link plan
- Original technical deep dive
- FAQ
- Structured data
- Conclusion
Article overview
Configuring Linux swap: Size, Priority & zram for Better Performance is the kind of topic that looks simple until it reaches production. Teams usually discover the real cost late: unclear boundaries, weak defaults, hidden maintenance work, and decisions that seemed harmless when the codebase was small.
The problem gets worse when the article, tutorial, or implementation guide only explains the happy path. This guide closes that gap with a practical framework, a comparison table, common mistakes, and a deep technical section you can use while planning real work.
Keep reading for the non-obvious part: the safest implementation is rarely the most impressive-looking one. It is the one your team can debug, test, document, and evolve without turning every future change into archaeology.
Key Takeaways
- Configuring Linux swap: Size, Priority & zram for Better Performance should be evaluated as a production decision, not only as a syntax or tooling choice.
- The best implementation keeps responsibilities visible, with clear ownership, tests, documentation, and rollback paths.
- Search visibility improves when practical depth, structured answers, and expert examples live on the same page.
[IMAGE: A mobile-first technical article layout showing the main concept, decision table, implementation checklist, and FAQ blocks. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance expert guide for Performance]
What Configuring Linux swap: Size, Priority & zram for Better Performance means
Configuring Linux swap: Size, Priority & zram for Better Performance means applying performance knowledge to a concrete engineering decision, then turning that decision into reliable code, documentation, and operational behavior. In practice, it combines the topic's core concepts with trade-off analysis, implementation boundaries, testing strategy, and maintenance discipline.
This is the definition worth optimizing for featured snippets because it avoids hype. It tells the reader what the topic does and what a professional implementation must include.
Why it matters now
The technical web is more crowded than it was a few years ago. Thin tutorials can still get indexed, but they rarely earn trust from senior developers, buyers, AI answer systems, or teams that need production guidance.
For performance topics, the strongest content now has three layers:
- a clear answer for fast scanning
- a practical framework for implementation
- expert context that explains what breaks later
That same structure helps search engines understand the page. It also helps readers decide whether the advice fits their project.
Implementation framework
Use this framework before adopting the approach described in this article.
- Define the user problem and the production risk.
- Identify the smallest reliable implementation boundary.
- Keep configuration, secrets, and environment-specific behavior outside the article's core logic.
- Add tests for the behavior that would hurt if it regressed.
- Document the trade-off, not only the final code.
- Measure the result with logs, metrics, or user-facing outcomes.
- Revisit the decision after real usage exposes edge cases.
The sequence is deliberately conservative. It keeps the work grounded in outcomes instead of novelty.
[IMAGE: A seven-step implementation framework with discovery, boundary design, configuration, tests, documentation, measurement, and iteration. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance implementation framework]
Practical comparison
| Decision area | Strong approach | Weak approach | Why it matters |
|---|---|---|---|
| Scope | Solve one clear problem | Mix unrelated concerns | Focus improves testing and search intent |
| Architecture | Put logic in explicit classes or documented boundaries | Hide behavior in templates or incidental callbacks | Future changes stay easier to review |
| Data flow | Pass prepared data into the view or endpoint | Query or compute in presentation code | Reduces regressions and performance surprises |
| Testing | Cover the risky behavior directly | Test only the happy path | Catches production failures earlier |
| Documentation | Explain trade-offs and limits | Repeat generic definitions | Builds E-E-A-T and reader trust |
| Operations | Track logs, metrics, and rollback steps | Ship without measurement | Makes the decision reversible |
This table is intentionally practical. It gives a reviewer something to check before the implementation becomes expensive to change.
Expert workflow
Expert tip: "Treat Configuring Linux swap: Size, Priority & zram for Better Performance as a system boundary. If the next developer cannot find where the decision lives, how it is tested, and when it should be avoided, the implementation is not finished."
A useful workflow is simple:
- Start with the smallest working example.
- Add the constraints that exist in your real project.
- Remove anything that only demonstrates cleverness.
- Write down the failure modes.
- Add links to related decisions so future readers can navigate the topic cluster.
That last point matters for both humans and search systems. A single article can answer a question; a cluster proves authority.
Common mistakes
Mistake 1: Copying a pattern without its context
A pattern that works in a small demo can fail in a real application. The missing context is usually data volume, team experience, deployment process, security requirements, or observability.
Before copying the pattern, ask what assumption made it safe in the original example.
Mistake 2: Putting business logic in the wrong layer
This is the fastest way to make future debugging expensive. In Laravel, PHP, and server-rendered websites, presentation should receive prepared data, not discover rules on its own.
Keep decision logic in models, actions, services, policies, requests, jobs, or documented helpers where it can be tested directly.
Mistake 3: Optimizing for novelty instead of maintainability
Newer tools and language features can be valuable. They can also hide simple behavior behind unfamiliar syntax.
Use the option that makes the next production incident easier to understand.
Mistake 4: Publishing without a measurement plan
If the article describes a performance, SEO, security, or architecture improvement, define how success will be checked. Logs, tests, crawl diagnostics, analytics, and user behavior are all stronger than assumptions.
[IMAGE: A common-mistakes board with context loss, wrong layer, novelty bias, and missing measurement highlighted. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance common mistakes]
Media and link plan
Image placeholders
- [IMAGE: A concept diagram for Configuring Linux swap: Size, Priority & zram for Better Performance with input, decision boundary, implementation, tests, and production feedback. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance concept diagram]
- [IMAGE: A mobile screenshot-style checklist for Configuring Linux swap: Size, Priority & zram for Better Performance. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance mobile checklist]
- [IMAGE: A comparison table visualization for strong versus weak implementation choices. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance comparison table]
Video placeholder
[VIDEO: Insert a 5-8 minute YouTube walkthrough that demonstrates the main decision, the implementation boundary, the test strategy, and the production caveats for Configuring Linux swap: Size, Priority & zram for Better Performance.]
Trustworthy outbound links
- Linux manual pages - use this as the trust reference for operating-system reference.
- Google Search quality guidance - use this as the trust reference for people-first content and E-E-A-T alignment.
Internal linking opportunities
- Internal guide: Linux Performance Tuning: CPU, Memory & I/O - use this when readers need a related Performance follow-up.
- Internal guide: Linux Kernel Tuning With sysctl: Network - use this when readers need a related Performance follow-up.
Original Technical Deep Dive
The short version
Swap is not a performance upgrade. Swap is a pressure release valve.
Use it deliberately:
measure memory pressure
keep enough swap to survive spikes
put the fastest swap first
use zram for small hosts and desktops
avoid sustained disk swapping
monitor page-ins and page-outs
For most servers, start here:
RAM <= 2 GB: 1x to 2x RAM swap, consider zram
RAM 4-8 GB: 2-4 GB swap
RAM 16-64 GB: 4-8 GB swap
RAM > 64 GB: 4-16 GB swap unless hibernation or workload evidence says more
For a low-memory VM or laptop, a practical setup is:
zram swap: high priority, compressed in RAM
disk swap: lower priority, last resort
vm.swappiness: higher with zram, lower with only slow disk swap
Do not tune swap from guesswork. First check whether the machine is actually under memory pressure:
free -h
swapon --show
vmstat 1
cat /proc/pressure/memory 2>/dev/null || true
Watch the si and so columns in vmstat. Occasional movement is normal. Sustained non-zero swap-in and swap-out during normal traffic means the system is short on memory, leaking memory, or running too much workload for the host.
What swap actually does
Linux uses RAM for processes, kernel memory, and file cache. Under pressure, the kernel can reclaim memory by dropping clean file-backed cache, writing dirty file-backed pages, or moving anonymous memory pages to swap.
Swap can help when:
| Situation | Why swap helps |
|---|---|
| Short memory spikes | The kernel can move cold anonymous pages instead of killing a process immediately |
| Idle desktop applications | Unused memory can move out of RAM and leave more room for active work |
| Small VPS hosts | A small swap area can prevent one spike from becoming an outage |
| Hibernation | The system needs enough swap-backed storage to save memory state |
| zram systems | Compressed swap in RAM can fit more inactive pages into the same physical memory |
Swap does not help when:
| Situation | Real fix |
|---|---|
| Hot working set is larger than RAM | Add RAM, reduce workload, or split services |
| Database buffer pool is too large | Reduce the buffer pool or move services |
| Application leaks memory | Fix the leak and restart safely |
| Disk is slow and swap is busy | Stop swapping or move swap to faster storage |
| OOM happens inside a container limit | Fix cgroup memory limits and service sizing |
The goal is not "use zero swap." The goal is "avoid sustained swap I/O on the critical path."
Inspect the current swap layout
Use swapon --show instead of only reading free:
swapon --show --bytes --output=NAME,TYPE,SIZE,USED,PRIO
cat /proc/swaps
free -h
Example:
NAME TYPE SIZE USED PRIO
/dev/zram0 partition 2147483648 0 100
/swapfile file 4294967296 0 -2
Read it like this:
| Column | Meaning |
|---|---|
NAME | Swap device or file |
TYPE | partition or file |
SIZE | Configured swap size |
USED | Current swap usage |
PRIO | Higher priority swap is preferred first |
Check memory pressure while the workload is running:
vmstat 1
Important columns:
| Column | Meaning |
|---|---|
swpd | Total memory currently swapped out |
free | Free RAM, not including useful cache |
buff | Buffer memory |
cache | Page cache |
si | Swap-in from disk or zram to RAM |
so | Swap-out from RAM to swap |
wa | CPU time waiting on I/O |
[IMAGE: Supporting visual 1 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 1]
[IMAGE: Supporting visual 1 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 1]
Use PSI when available:
cat /proc/pressure/memory
Example:
some avg10=0.00 avg60=0.03 avg300=0.11 total=1234567
full avg10=0.00 avg60=0.00 avg300=0.00 total=12345
some means at least one task was delayed by memory pressure. full means all non-idle tasks were delayed. If full rises under normal traffic, the machine is in serious memory trouble.
Choose a swap size
There is no universal swap size. The right size depends on RAM, storage speed, hibernation, and failure mode.
Use these starting points:
| Host type | Starting swap size |
|---|---|
| 1 GB VPS | 1-2 GB |
| 2 GB VPS | 2-4 GB |
| 4 GB VPS | 2-4 GB |
| 8 GB server | 2-4 GB |
| 16-32 GB server | 4-8 GB |
| 64 GB+ server | 4-16 GB |
| Laptop with hibernation | At least RAM size, adjusted for distro hibernation requirements |
| zram-only small system | 50-100 percent of RAM as zram device size, then measure |
For production servers, do not blindly use "2x RAM." That old rule is wasteful on large memory hosts and still insufficient for some hibernation setups.
Use enough swap to:
survive short spikes
preserve room for an admin shell
avoid immediate OOM during deploys
capture failure signals in monitoring
Do not use so much disk swap that a dead service spends thirty minutes thrashing instead of failing and restarting.
Partition vs swapfile
Both are valid.
Use a swap partition when:
| Reason | Detail |
|---|---|
| Installer already created one | Keep it unless you have a reason to change |
| Hibernation matters | A dedicated partition is often simpler to wire into resume configuration |
| You want filesystem independence | No sparse-file or filesystem restrictions |
| You use encrypted block layouts | Easier to reason about with LUKS and device mapper |
Use a swapfile when:
| Reason | Detail |
|---|---|
| You need easy resizing | Files are easier to grow or replace |
| You manage cloud images | Swapfiles are simple in provisioning scripts |
| You want fewer partitions | Common on Ubuntu installations |
| You need per-host flexibility | Size can vary by instance class |
The important rules for swapfiles:
file must not be sparse
permissions should be root-only
filesystem must support swapfiles correctly
fstab must use an absolute path
The swapon manual notes filesystem caveats for swapfiles, including preallocated files and Btrfs requirements. When in doubt, create the file with dd or use mkswap --file on util-linux versions that support it.
[IMAGE: Supporting visual 2 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 2]
Create a safe swapfile
Check current swap first:
swapon --show
df -h /
Create a 4 GB swapfile with dd:
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Verify:
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
free -h
Persist it in /etc/fstab:
sudo cp /etc/fstab /etc/fstab.backup.$(date +%Y%m%d%H%M%S)
echo '/swapfile none swap sw,pri=10 0 0' | sudo tee -a /etc/fstab
Test the file before rebooting:
sudo swapoff /swapfile
sudo swapon -a
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
If swapon -a fails, fix /etc/fstab before rebooting.
Create swap with mkswap --file when available
Modern util-linux includes a safer file mode:
sudo mkswap --file /swapfile --size 4G
sudo swapon /swapfile
[IMAGE: Supporting visual 2 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 2]
Verify permissions:
ls -lh /swapfile
stat -c '%a %U %G %n' /swapfile
Expected:
600 root root /swapfile
If your installed mkswap does not support --file, use the dd method.
Resize a swapfile
Disable only the swapfile you are replacing:
sudo swapoff /swapfile
Recreate it:
sudo rm /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=8192 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
Confirm:
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
If /etc/fstab already points to /swapfile, no fstab edit is needed unless you also want to change priority or discard options.
Add a swap partition
This example assumes the new partition is /dev/sdb2. Replace it with the real device from your system.
List block devices:
lsblk -f
sudo fdisk -l
Create the swap signature:
sudo mkswap -L swapfast /dev/sdb2
Enable it:
sudo swapon /dev/sdb2
Find the UUID:
blkid /dev/sdb2
Persist it:
echo 'UUID=YOUR-SWAP-UUID none swap sw,pri=20 0 0' | sudo tee -a /etc/fstab
Then test:
sudo swapoff /dev/sdb2
sudo swapon -a
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
Use UUIDs for block-device swap in /etc/fstab. Device names like /dev/sdb2 can change when disks are added, removed, or enumerated differently.
Understand swap priority
Swap priority controls which swap area is used first. Higher number wins.
Set priority at activation time:
sudo swapon --priority 100 /dev/zram0
sudo swapon --priority 10 /swapfile
Set priority in /etc/fstab:
/swapfile none swap sw,pri=10 0 0
UUID=YOUR-SWAP-UUID none swap sw,pri=20 0 0
Useful pattern:
| Swap area | Priority | Reason |
|---|---|---|
| zram | 100 | Fast compressed memory-backed swap |
| NVMe swap partition | 20 | Fast disk fallback |
| SSD swapfile | 10 | General fallback |
| HDD swap | 1 | Last resort |
If two swap areas have the same priority, the kernel can distribute use across them. If priorities differ, it prefers the higher priority area first.
Check priority:
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
Tune swappiness
Check current value:
sysctl vm.swappiness
cat /proc/sys/vm/swappiness
The Linux kernel documents vm.swappiness as a rough relative I/O cost between swapping and filesystem paging. The range is 0 to 200, and the default is 60.
Lower values treat swap as more expensive. Higher values treat swap as cheaper.
Temporary change:
sudo sysctl -w vm.swappiness=10
Persistent change:
sudo tee /etc/sysctl.d/60-swap-tuning.conf >/dev/null <<'EOF'
vm.swappiness = 10
EOF
sudo sysctl --system
Starting values:
| System | Starting value |
|---|---|
| Database server with disk swap | 1 to 10 |
| General web server with disk swap | 10 to 30 |
| Desktop with SSD swap | 30 to 60 |
| zram-first system | 100 to 150 |
| zram plus slow disk fallback | 100, with zram priority higher than disk |
[IMAGE: Supporting visual 3 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 3]
Do not set vm.swappiness=0 as a reflex. The kernel documentation says 0 does not fully disable swap; it makes the kernel avoid initiating swap until free and file-backed pages drop below a high watermark. If you want no swap, disable swap explicitly. If you want swap as an emergency buffer, keep swappiness low and measure behavior.
Tune vfs_cache_pressure
Check current value:
sysctl vm.vfs_cache_pressure
sysctl vm.vfs_cache_pressure_denom 2>/dev/null || true
vm.vfs_cache_pressure controls how aggressively the kernel reclaims directory and inode caches.
[IMAGE: Supporting visual 3 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 3]
Common advice says "set it to 50." That is not universally correct.
Use this starting point:
| Workload | Starting value |
|---|---|
| General server | 100 |
| Many repeated filesystem metadata lookups | 50 to 100, test carefully |
| Memory-constrained host | Keep 100 unless metadata cache churn is proven |
| System already near OOM | Do not lower it |
Temporary change:
sudo sysctl -w vm.vfs_cache_pressure=100
Persistent change:
sudo tee /etc/sysctl.d/60-swap-tuning.conf >/dev/null <<'EOF'
vm.swappiness = 10
vm.vfs_cache_pressure = 100
EOF
sudo sysctl --system
Do not set vfs_cache_pressure=0. The kernel documentation warns that this prevents reclaiming dentries and inodes due to memory pressure and can lead to out-of-memory conditions.
Set up zram with systemd-zram-generator
zram creates compressed RAM-backed block devices. When used as swap, pages written to zram are compressed and stored in memory instead of being written directly to disk.
Install the generator on Ubuntu or Debian:
sudo apt update
sudo apt install -y systemd-zram-generator
Create a local config:
sudo mkdir -p /etc/systemd/zram-generator.conf.d
sudo tee /etc/systemd/zram-generator.conf.d/10-zram.conf >/dev/null <<'EOF'
[zram0]
zram-size = min(ram / 2, 4096)
compression-algorithm = zstd
swap-priority = 100
options = discard
EOF
Reload systemd and start the generated unit:
sudo systemctl daemon-reload
sudo systemctl start systemd-zram-setup@zram0.service
Verify:
zramctl
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
cat /sys/block/zram0/comp_algorithm
Expected shape:
NAME TYPE SIZE USED PRIO
/dev/zram0 partition 2G 0B 100
If the service name differs on your distribution, inspect generated units:
systemctl list-units 'systemd-zram-setup@*'
systemctl status systemd-zram-setup@zram0.service
Size zram sanely
The zram-size setting is the logical device size, not the amount of physical RAM permanently consumed. zram consumes memory as pages are written and compressed, plus metadata.
Start conservative:
2 GB RAM: zram-size = min(ram, 2048)
4 GB RAM: zram-size = min(ram / 2, 4096)
8 GB RAM: zram-size = min(ram / 2, 4096)
16 GB RAM: zram-size = min(ram / 4, 4096)
Good default:
zram-size = min(ram / 2, 4096)
More aggressive for small desktops:
zram-size = min(ram, 8192)
Do not create a huge zram device just because it is compressed. The kernel zram documentation notes that there is little point in creating zram larger than twice memory when assuming a 2:1 compression ratio.
Use zram before disk swap
Keep zram priority higher than disk swap:
[zram0]
zram-size = min(ram / 2, 4096)
compression-algorithm = zstd
swap-priority = 100
options = discard
[IMAGE: Supporting visual 4 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 4]
Then keep disk swap lower:
/swapfile none swap sw,pri=10 0 0
Confirm:
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
The output should show zram at a higher priority:
NAME TYPE SIZE USED PRIO
/dev/zram0 partition 2G 0B 100
/swapfile file 4G 0B 10
This gives the kernel a fast compressed swap layer first, then slower disk swap as a last resort.
Manual zram setup without generator
Use this for testing or minimal systems:
sudo modprobe zram
sudo zramctl --find --size 2G --algorithm zstd
sudo mkswap /dev/zram0
sudo swapon --priority 100 /dev/zram0
Verify:
zramctl
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
Disable and reset:
sudo swapoff /dev/zram0
sudo zramctl --reset /dev/zram0
Manual setup disappears after reboot unless you add systemd units or use a generator package.
Monitor zram
Use:
zramctl --output-all
cat /sys/block/zram0/mm_stat
cat /sys/block/zram0/io_stat
swapon --show --output=NAME,SIZE,USED,PRIO
zramctl shows logical data size, compressed size, total memory used, algorithm, and mount point.
Example:
NAME ALGORITHM DISKSIZE DATA COMPR TOTAL STREAMS MOUNTPOINT
/dev/zram0 zstd 2G 512M 160M 190M 4 [SWAP]
Read it like this:
| Field | Meaning |
|---|---|
DATA | Uncompressed amount stored in zram |
COMPR | Compressed payload size |
TOTAL | Actual memory used including overhead |
ALGORITHM | Compression algorithm |
DISKSIZE | Logical zram device size |
If TOTAL grows close to available memory and the system still swaps heavily, the host is too small or the workload is too large.
[IMAGE: Supporting visual 4 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 4]
Choose a compression algorithm
Common choices:
| Algorithm | Typical behavior |
|---|---|
lz4 | Very fast, lower compression ratio |
zstd | Good default on modern systems, better compression |
lzo | Older fast option |
Check what the kernel exposes:
cat /sys/block/zram0/comp_algorithm
The selected algorithm is shown in brackets:
lzo lzo-rle [lz4] zstd
With systemd-zram-generator, set:
compression-algorithm = zstd
If CPU is the bottleneck, test lz4. If memory is the bottleneck and CPU has room, test zstd.
Use discard carefully
For disk swap on SSD, discard can release freed swap blocks back to the device:
/swapfile none swap sw,pri=10,discard=pages 0 0
For zram generator, the default options may include discard, and explicit config can set:
options = discard
Verify the swapon manual for your distribution. Some devices benefit from discard, others do not. Treat it as a storage-specific setting, not a universal performance win.
Keep hibernation separate from zram
Do not rely on zram for hibernation. zram contents are memory-backed and temporary.
For hibernation, plan a disk-backed swap device or swapfile that your distro can use for resume. In many setups a partition is easier:
disk swap partition: resume target
zram swap: high-priority runtime pressure absorber
If hibernation matters, validate the complete suspend and resume path before calling the setup finished.
Production sysctl profile
[IMAGE: Supporting visual 5 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 5]
General web server with disk swap:
sudo tee /etc/sysctl.d/60-swap-tuning.conf >/dev/null <<'EOF'
vm.swappiness = 10
vm.vfs_cache_pressure = 100
EOF
sudo sysctl --system
Small VM with zram first and disk fallback:
sudo tee /etc/sysctl.d/60-swap-tuning.conf >/dev/null <<'EOF'
vm.swappiness = 100
vm.vfs_cache_pressure = 100
EOF
sudo sysctl --system
Database host with a large buffer pool:
sudo tee /etc/sysctl.d/60-swap-tuning.conf >/dev/null <<'EOF'
vm.swappiness = 1
vm.vfs_cache_pressure = 100
EOF
sudo sysctl --system
These are starting values. Keep only settings that improve measured behavior.
Test under pressure
Install tools:
sudo apt update
sudo apt install -y stress-ng sysstat
Run a controlled memory test on a non-production host:
stress-ng --vm 2 --vm-bytes 70% --timeout 120s --metrics-brief
Watch in another shell:
vmstat 1
swapon --show --output=NAME,SIZE,USED,PRIO
zramctl 2>/dev/null || true
cat /proc/pressure/memory 2>/dev/null || true
Stop the test if the machine becomes unresponsive.
Signals to capture:
Does swap usage rise gradually or spike?
Does zram absorb pressure before disk swap?
Do si/so stay high after the test ends?
Does iowait rise when disk swap is used?
Does PSI full become non-zero?
Does the OOM killer run?
Check kernel logs:
journalctl -k -b --no-pager | grep -Ei 'oom|out of memory|swap|zram'
Troubleshooting
swapon says insecure permissions
Fix permissions:
sudo chmod 600 /swapfile
sudo chown root:root /swapfile
sudo swapon /swapfile
swapon says invalid argument
Common causes:
file is sparse
filesystem does not support swapfiles
Btrfs file lacks required attributes
swap signature was not created
fstab line has wrong fields
Recreate the file with dd:
sudo swapoff /swapfile 2>/dev/null || true
sudo rm -f /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
zram service does not start
Check configuration:
systemctl status systemd-zram-setup@zram0.service
journalctl -u systemd-zram-setup@zram0.service -b --no-pager
systemd-analyze cat-config zram-generator.conf
Check whether the kernel module exists:
modinfo zram
sudo modprobe zram
Check the algorithm:
cat /sys/block/zram0/comp_algorithm 2>/dev/null || true
If zstd is unavailable, use lz4 or leave compression-algorithm unset.
Disk swap is used before zram
Check priority:
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
Fix zram priority:
swap-priority = 100
Fix disk swap priority:
/swapfile none swap sw,pri=10 0 0
Reload:
sudo swapoff -a
sudo systemctl daemon-reload
sudo systemctl start systemd-zram-setup@zram0.service
sudo swapon -a
swapon --show --output=NAME,TYPE,SIZE,USED,PRIO
Do this during a maintenance window. swapoff -a can fail or stall if the system does not have enough RAM to page everything back in.
The server still freezes
Look for real memory pressure:
free -h
vmstat 1
ps aux --sort=-rss | head -20
systemd-cgtop
cat /proc/pressure/memory 2>/dev/null || true
If the active working set does not fit in RAM, swap tuning will not fix the host. Reduce service memory, split workloads, fix leaks, or add RAM.
[IMAGE: Supporting visual 5 for Configuring Linux swap: Size, Priority & zram for Better Performance, showing Configuring Linux swap: Size, Priority & zram for Better Performance decisions, examples, and Linux, Swap, zram. Alt: Configuring Linux swap: Size, Priority & zram for Better Performance configuring-linux-swap-size-priority-zram-better-performance visual 5]
Operational checklist
Before rollout:
[ ] Current swap layout is recorded with swapon --show.
[ ] New swapfile or partition is tested with swapon -a.
[ ] /etc/fstab has a backup.
[ ] zram priority is higher than disk swap.
[ ] disk swap remains available if the host needs emergency fallback.
[ ] sysctl changes are stored in /etc/sysctl.d/.
[ ] memory pressure is measured under representative load.
[ ] monitoring tracks swap used, si/so, PSI, OOM events, and disk iowait.
[ ] hibernation is tested separately if required.
[ ] rollback commands are documented.
Rollback example:
sudo swapoff /swapfile
sudo sed -i.bak '/\/swapfile none swap/d' /etc/fstab
sudo rm -f /swapfile
sudo rm -f /etc/sysctl.d/60-swap-tuning.conf
sudo sysctl --system
Disable zram generator config:
sudo swapoff /dev/zram0 2>/dev/null || true
sudo rm -f /etc/systemd/zram-generator.conf.d/10-zram.conf
sudo systemctl daemon-reload
FAQ
What is Configuring Linux swap: Size, Priority & zram for Better Performance?
Configuring Linux swap: Size, Priority & zram for Better Performance is a practical performance topic that should be evaluated through implementation scope, production risk, testing, documentation, and long-term maintainability.
When should a team use Configuring Linux swap: Size, Priority & zram for Better Performance?
Use Configuring Linux swap: Size, Priority & zram for Better Performance when it solves a real project constraint, improves clarity, or reduces operational risk. Avoid it when it only adds novelty or hides behavior from future maintainers.
What is the biggest risk with Configuring Linux swap: Size, Priority & zram for Better Performance?
The biggest risk is copying a pattern without its context. Production systems need clear boundaries, rollback options, tests, and observability before a technique becomes dependable.
How do you test Configuring Linux swap: Size, Priority & zram for Better Performance?
Test the smallest unit that owns the behavior, then add integration coverage for the path users or systems actually rely on. Include failure cases, configuration differences, and regression checks.
How does Configuring Linux swap: Size, Priority & zram for Better Performance affect SEO and AI search visibility?
It improves visibility when the article gives a direct answer, expert context, structured headings, internal links, trustworthy references, and FAQ content that matches the visible page.
Conclusion
Configuring Linux swap: Size, Priority & zram for Better Performance is worth doing when the implementation improves clarity, reliability, or delivery speed. It is not worth doing when it hides ownership, increases operational risk, or makes the system harder to explain.
Use the framework above as a review checklist. Then connect this topic to the rest of the project documentation so readers can move from concept to implementation without losing context.