RAM is usually the resource that limits how many VMs fit on a host. KVM memory management features like ballooning, KSM and huge pages let you trade between density and performance. This guide explains each one and how to tune it.
Before you start
- Root on a KVM host with libvirt.
- Background on overcommit: see CPU pinning and overcommit.
Memory ballooning
The virtio_balloon driver in the guest can "inflate" to hand unused memory back to the host, or deflate to return it.
- Requires a balloon device in the VM XML (
<memballoon model='virtio'/>, present by default). - Set the current memory below the maximum:
virsh setmem web01 2G --live. - Check from the host:
virsh dommemstat web01. - Proxmox VE's automatic ballooning shrinks guests toward their minimum when the host passes about 80% RAM use.
Ballooning reclaims memory only if the guest truly has spare RAM; shrinking too far makes the guest swap or kill processes.
Kernel Samepage Merging (KSM)
KSM scans memory for identical pages across VMs (common when many run the same OS) and merges them copy-on-write.
echo 1 | sudo tee /sys/kernel/mm/ksm/runSee how much it saves:
grep -H '' /sys/kernel/mm/ksm/pages_sharing /sys/kernel/mm/ksm/pages_sharedMultiply pages_sharing by 4 KiB for an estimate of memory saved. Many distributions provide ksmtuned, and Proxmox enables it by default.
- Cost: CPU time for scanning.
- Security: page merging can enable side-channel attacks between VMs; some providers disable it on multi-tenant hosts.
Transparent huge pages (THP)
Linux can back memory with 2 MiB pages instead of 4 KiB, reducing TLB misses. THP does this automatically:
cat /sys/kernel/mm/transparent_hugepage/enabled[always] or [madvise] is typical. QEMU uses madvise, so guests benefit in both modes.
Static huge pages
For latency-sensitive VMs (databases, NFV) reserve huge pages at boot and back the VM with them:
echo "vm.nr_hugepages = 4096" | sudo tee /etc/sysctl.d/80-hugepages.confThat reserves 8 GiB in 2 MiB pages. In the VM XML add:
<memoryBacking><hugepages/></memoryBacking>Reserved huge pages cannot be used by anything else, ballooned or merged by KSM.
Which to use
| Goal | Use |
|---|---|
| Maximum VM density | KSM + ballooning, careful monitoring |
| General VPS hosts | THP, modest or no overcommit |
| Lowest latency | Static huge pages, pinning, no ballooning |
Frequently asked questions
Why does my VPS show less RAM than I bought after a while?
Usually it does not; tools may show cache as used. On KVM your plan's RAM is assigned to the VM unless the provider balloons it.
Should I disable the balloon driver in my guest?
No. It also reports memory statistics and is harmless when the host does not use ballooning.
Does KSM work with huge pages?
KSM merges normal 4 KiB pages; static huge pages are excluded.
