Linux Internals
Copy-on-Write in Linux: fork(), Memory and Filesystems Explained
By NileVPS Team · Published · 4 min read
اقرأ المقال بالعربيCopy-on-write, usually shortened to COW, is one of those ideas that quietly shows up all over a Linux server. It is the reason fork() returns almost instantly even for a process using gigabytes of RAM, the reason Docker containers start without copying a whole image, and the reason some filesystems can clone a large file in a fraction of a second. It also explains a few surprises, such as Redis memory usage climbing during a background save. The principle is simple: when two parties share the same data, do not copy it until one of them tries to change it.
Copy-on-write in process memory
When a process calls fork(), the kernel creates a child that is logically a full copy of the parent. Copying every page would be slow and wasteful, especially since many children immediately call exec() and throw that memory away. Instead, Linux does this:
- The child gets its own page tables that point to the same physical pages as the parent.
- Writable private pages are marked read-only in both processes and flagged as copy-on-write.
- Either process can read the shared pages freely.
- When one of them writes, the CPU raises a page fault. The kernel allocates a new page, copies the 4 KB of content, maps the copy as writable for the writer, and lets the write continue.
The cost of fork() therefore depends mostly on the size of the page tables, not on the amount of memory. The real copying happens lazily, page by page, and only for pages that are actually modified.
Where you can observe it
/proc/<pid>/smaps_rollup shows Shared_Clean, Shared_Dirty, Private_Clean and Private_Dirty totals. Right after a fork, most of the child's memory appears as shared. As either process writes, pages move into the private columns. This is also why summing the RSS of a forking server's workers overstates real memory use; PSS (proportional set size) in the same file is a fairer number.
Practical consequences on servers
Redis and other snapshotting databases
Redis persists data with BGSAVE and AOF rewrites by forking a child that writes the dataset to disk while the parent keeps serving clients. Thanks to COW, the child sees a frozen snapshot. But every key the parent modifies during the save forces a page copy. On a write-heavy instance, memory use can grow substantially during the save, in the worst case approaching double the dataset. Practical advice:
- Leave headroom in RAM for snapshots instead of sizing to the dataset alone.
- Redis recommends
vm.overcommit_memory = 1so the fork is not refused when the kernel's heuristic thinks memory is short. - Redis also warns about transparent huge pages: with THP, one small write can force copying a 2 MB page instead of 4 KB.
cat /sys/kernel/mm/transparent_hugepage/enabled
sudo sysctl vm.overcommit_memory=1Pre-forking web servers
PHP-FPM, Gunicorn with --preload and similar servers load code once and fork workers so that read-only data is shared. Language runtimes that touch object headers during garbage collection or reference counting can gradually dirty shared pages, so the sharing shrinks over time. That is normal; recycling workers periodically keeps it in check.
Copy-on-write in filesystems
The same idea applies to blocks on disk. A COW filesystem never overwrites a block in place; it writes the new version elsewhere and then updates the metadata pointers.
| Filesystem | How COW is used |
|---|---|
| Btrfs | All data and metadata are COW by default; snapshots and clones are cheap |
| ZFS | Fully COW; snapshots are instant and consistent |
| XFS | Not COW by default, but supports reflink copies that share blocks until modified |
| ext4 | Overwrites in place; no reflink support |
On Btrfs or XFS with reflink enabled, this makes an instant clone that shares blocks until either file changes:
cp --reflink=always big-image.qcow2 clone.qcow2The trade-off is fragmentation for files with many small random overwrites, such as databases and VM images. On Btrfs you can disable COW for a directory before creating files in it:
mkdir /var/lib/mysql-data
chattr +C /var/lib/mysql-dataThe +C attribute only takes effect for files created after it is set, and it also disables checksumming for those files.
Copy-on-write in containers
Docker's default overlay2 storage driver stacks read-only image layers under a thin writable layer. When a container modifies a file from the image, overlayfs performs a "copy-up" of the whole file into the writable layer first. For large files that change often, use a volume instead so writes go directly to the host filesystem. If you are setting this up, see our guide to installing Docker on a VPS.
Quick checklist
- Budget extra RAM for any service that forks to snapshot.
- Prefer PSS over RSS when estimating memory of forked workers.
- Use reflink copies for fast clones where the filesystem supports them.
- Disable COW on Btrfs directories holding databases or VM disks.
- Put write-heavy container data on volumes, not in the image layer.
FAQ
Does fork() double my memory usage?
Not immediately. After fork() both processes share physical pages. Memory grows only as pages are written by either process, so the final increase depends on how much data changes while both exist.
Is copy-on-write the same as a snapshot?
COW is the mechanism that makes cheap snapshots possible. A snapshot keeps references to the current blocks or pages, and COW guarantees that later writes go to new locations, so the snapshot stays unchanged.
Should I avoid COW filesystems for databases?
Not necessarily, but be deliberate. Many people run databases on ext4 or XFS for predictable performance. On Btrfs, disabling COW for the data directory is a common compromise, while ZFS users usually tune record size to match the database page size.