Linux Optimize Swap Memory
A conservative Linux memory-pressure tuning script designed to keep desktop/workstation systems responsive when RAM usage gets high.
Instead of replacing your existing swap setup, the script adds a high-priority compressed ZRAM tier in front of it:
RAM
│
▼
ZRAM
compressed in memory
priority 1000
│
▼
existing swapfile / swap partition
disk-backed fallback
This does not physically add RAM to your computer. It increases effective memory headroom by compressing swapped pages in RAM before falling back to slower disk-backed swap.
The script was built from real workstation memory-pressure testing where the objective was not just "avoid OOM", but reduce severe reclaim/swap thrashing and preserve interactive desktop responsiveness.
What it does
optimize_memory_v11.sh installs an adaptive memory policy for modern systemd-based Linux systems.
Adaptive ZRAM
The script detects the system's real MemTotal and configures:
[zram0]
zram-size = ram / 2
compression-algorithm = zstd
swap-priority = 1000
zram-resident-limit = 0
Examples:
| Installed RAM |
ZRAM logical size |
| 8 GiB |
~4 GiB |
| 16 GiB |
~8 GiB |
| 32 GiB |
~16 GiB |
| 40 GiB |
~20 GiB |
| 64 GiB |
~32 GiB |
ZRAM size is a logical capacity, not RAM reserved up front. Physical memory is consumed as compressed pages are actually stored.
Existing swap is preserved
The script intentionally does not remove your current swap.
A normal Linux installation with:
becomes:
RAM -> /dev/zram0 -> /swapfile
Likewise, a machine using a swap partition becomes:
RAM -> /dev/zram0 -> existing swap partition
The existing disk-backed swap remains an emergency/fallback capacity tier.
The script never performs a live swapoff.
Zswap is disabled
This project uses ZRAM as the compressed swap tier, so zswap is disabled to avoid stacking two different compressed-swap strategies.
When GRUB is detected, the script persists:
It also disables zswap live when the running kernel permits it.
A reboot is required before the resulting topology is considered clean.
VM/reclaim policy
The current V11 profile applies:
vm.swappiness=20
vm.watermark_boost_factor=0
vm.watermark_scale_factor=150
vm.page-cluster=2
vm.vfs_cache_pressure=50
vm.compaction_proactiveness=0
vm.compact_unevictable_allowed=0
vm.zone_reclaim_mode=0
vm.dirty_background_bytes=67108864
vm.dirty_bytes=268435456
vm.dirty_writeback_centisecs=200
Unsupported kernel tunables are skipped instead of causing the installation to fail.
Multi-Gen LRU
When supported by the kernel:
MGLRU enabled = 0x0007
min_ttl_ms = 1000
Multi-Gen LRU is used as part of the reclaim policy on kernels that expose the interface.
Transparent Huge Pages
When supported:
THP enabled = madvise
THP defrag = never
khugepaged defrag = 0
khugepaged max_ptes_swap = 0
The goal is to avoid unnecessary latency from aggressive huge-page compaction/defragmentation while still allowing applications that explicitly request THP to use it.
SATA SSD swap queue tuning
If the system uses an active SATA SSD swap block device and BFQ is available, the script can apply the V11 latency-oriented queue policy:
scheduler = bfq
nr_requests = 32
nomerges = 1
rq_affinity = 1
wbt_lat_usec = 0
BFQ low_latency = 1
strict_guarantees = 0
slice_idle = 0
This is deliberately conservative:
- NVMe swap devices are left alone.
- HDD swap devices are left alone.
- USB/unknown transports are left alone.
- Swapfiles are left alone at the block-scheduler level.
- SATA devices without BFQ support are left unchanged.
The script does not guess storage topology.
Supported systems
The target is a modern systemd-based Linux desktop/workstation.
Automatic zram-generator installation is implemented for:
- Debian / Ubuntu-family systems
- Fedora / RHEL-family systems
- Arch Linux
- openSUSE-family systems
The script refuses to apply the policy from inside a container.
Kernel-specific features such as MGLRU, THP controls, zswap controls and BFQ are applied only when the relevant interfaces exist.
Default Linux installations
A standard Linux machine with a swapfile is supported.
Example before:
NAME TYPE SIZE PRIO
/swapfile file 8G -2
Example after installing and rebooting on a ~16 GiB system:
NAME TYPE SIZE PRIO
/dev/zram0 partition ~8G 1000
/swapfile file 8G -2
Linux allocates swap from higher-priority swap areas before lower-priority ones, so the compressed ZRAM tier is preferred while the original swapfile remains available as fallback capacity.
The script does not delete, resize or reformat the existing swapfile.
Installation
Clone the repository:
git clone https://github.com/linsaftw/Linux-Optimize-Swap-Memory.git
cd Linux-Optimize-Swap-Memory
Make the script executable:
chmod +x optimize_memory_v11.sh
Apply the configuration:
sudo ./optimize_memory_v11.sh --apply
Then reboot:
The reboot matters because zram-generator creates and configures the ZRAM device early during system boot. Rebuilding an actively used compressed swap device live is intentionally avoided.
Verify after reboot
Run:
./optimize_memory_v11.sh --verify
Verification checks include:
/dev/zram0 exists
- ZRAM size is approximately 50% of detected RAM
- compressor is ZSTD
- ZRAM swap priority is
1000
- runtime zswap is disabled
- zswap contains no historical pages
- expected V11 VM tunables are active
- disk-backed swap does not outrank ZRAM
- current CPU, memory and I/O PSI are displayed
- persistent systemd service status is displayed
A healthy topology should look conceptually like:
RAM
│
├── normal working set
│
└── pressure
│
▼
/dev/zram0
ZSTD compressed
priority 1000
│
▼
existing disk swap
lower priority
You can also inspect it manually:
free -h
swapon --show
zramctl
cat /proc/pressure/memory
cat /proc/pressure/io
Rollback
The script stores the first-seen configuration/runtime state under:
/var/lib/workspace-memory-v11-universal/
Rollback with:
sudo ./optimize_memory_v11.sh --rollback
sudo reboot
Rollback restores the configuration files and saved runtime/sysfs/queue settings captured during the first application.
It still does not perform swapoff or destroy a live ZRAM device.
The reboot restores the previous boot-time topology cleanly.
Safety model
This project intentionally avoids several aggressive techniques often found in Linux "optimization" scripts.
It does not:
- run
swapoff -a
- force disk swap out of RAM while the system is under pressure
- run
drop_caches
- restart user applications
- impose arbitrary per-application memory limits
- set cgroup
memory.swap.max
- set cgroup
memory.low
- set cgroup
io.weight or io.latency
- pin CPUs or IRQs
- disable CPU turbo
- assume NVMe swap is bad
- hard-code a swap UUID
- hard-code
/dev/sda, /dev/sdb, etc.
- hard-code a RAM capacity
- blindly force BFQ onto every drive
The configuration is designed to fail conservatively when an optional kernel/storage feature is unavailable.
Why ZRAM?
Disk-backed swap is useful because it gives Linux additional virtual-memory capacity, but accessing storage is dramatically slower than accessing RAM.
ZRAM creates a block device whose pages are compressed and stored in physical memory.
For sufficiently compressible workloads, multiple logical pages can occupy substantially less physical memory than they would uncompressed.
That means memory pressure can often be handled like:
anonymous page
│
▼
compress
│
▼
store in ZRAM
instead of immediately:
anonymous page
│
▼
write to SSD
Disk swap still matters. If the compressed tier fills or memory pressure becomes sufficiently severe, the lower-priority disk-backed swap remains available.
Why not remove disk swap?
Because ZRAM and disk swap solve different parts of the problem.
ZRAM provides a fast compressed tier.
Disk-backed swap provides much larger capacity.
Removing disk swap would reduce the amount of overcommit the machine can survive.
For workstation use, this project deliberately favors:
fast compressed tier
+
large slow fallback tier
rather than choosing only one.
Why swappiness=20?
vm.swappiness is not simply an "amount of swapping" percentage.
The kernel uses it as part of the relative reclaim cost between anonymous memory and filesystem-backed pages.
Higher values can make sense when swap itself is very fast, including some ZRAM-only configurations.
This project currently keeps 20 because V11 is a conservative, latency-oriented workstation baseline derived from measured behavior.
It should not be interpreted as the universal mathematically optimal value for every workload.
Future versions may tune this policy further using clean-boot measurements.
What this project is optimized for
The primary target is an interactive Linux workstation running memory-heavy workloads such as:
- browsers with many tabs
- development environments
- multiple terminals
- local services
- containers
- JVM workloads
- IDEs
- AI/coding agents
- long-running desktop sessions
- gaming/development mixed workloads
The main objective is:
Preserve interactive responsiveness for as long as possible when memory pressure becomes severe.
This is different from simply maximizing benchmark throughput.
What this project cannot do
This script cannot turn 16 GiB of physical RAM into 32 GiB of real RAM.
Compressed memory has costs:
- compression consumes CPU time
- incompressible pages save little space
- ZRAM itself consumes physical memory
- once both RAM and compressed swap are heavily saturated, Linux may still need disk swap
- extreme working sets can still thrash
- an application that genuinely requires more resident physical memory still benefits from a RAM upgrade
Think of ZRAM as a memory-efficiency and latency tool, not a substitute for unlimited physical memory.
Troubleshooting
ZRAM does not appear after reboot
Check:
systemctl status systemd-zram-setup@zram0.service
journalctl -b -u systemd-zram-setup@zram0.service
zramctl
Also verify that zram-generator is installed.
Zswap is still enabled
Check:
cat /proc/cmdline
cat /sys/module/zswap/parameters/enabled
grep -E '^(Zswap|Zswapped):' /proc/meminfo
If the machine does not use GRUB, the script may be unable to persist the kernel argument automatically. Configure zswap.enabled=0 using the bootloader used by that distribution, then reboot.
Existing swapfile disappeared
The script does not intentionally remove or disable it.
Check:
grep -i swap /etc/fstab
swapon --show
systemctl --failed
BFQ was not applied
That can be correct.
BFQ tuning is attempted only for a resolvable active SATA SSD swap block device where BFQ is actually exposed by the kernel.
NVMe, HDD, USB, unknown storage and swapfiles are intentionally not modified by this part of the script.
Inspect what the script changes
Before running it on an important machine, read it:
less optimize_memory_v11.sh
The script is intentionally verbose and includes its safety decisions in comments.
Relevant persistent files include:
/etc/sysctl.d/99-workspace-memory-v11-universal.conf
/etc/systemd/zram-generator.conf.d/99-workspace-memory-v11-universal.conf
/etc/systemd/system/workspace-memory-v11-universal.service
/usr/local/sbin/apply-workspace-memory-v11-universal
On GRUB systems it also installs a drop-in used to persist:
Project status
V11 is the current conservative baseline.
The tuning originated from repeated measurement of a heavily overcommitted Linux workstation, including:
- PSI CPU/memory/I/O pressure
- swap-in and swap-out traffic
- direct reclaim
allocstall
- kswapd scanning
- storage utilization
- storage latency
- ZRAM compression efficiency
- desktop responsiveness during pressure events
The current universal version intentionally excludes machine-specific assumptions from the original workstation environment.
More aggressive changes should be measured rather than assumed.
Contributing
Useful contributions include:
- clean before/after PSI captures
- swap-in/swap-out measurements
- ZRAM compression statistics
- distro compatibility reports
- bootloader support improvements
- safe storage-topology detection
- regression fixes
- reproducible heavy-memory workloads
When reporting results, include at minimum: