Linux Page Cache and Writeback Explained
Linux page cache and writeback sit between ordinary file access and persistent storage. They let applications read hot data from RAM and let the kernel combine and defer writes, but they also mean that a successful write() does not necessarily mean data is already safe on a device. This explainer is for Linux administrators, developers, and storage engineers who need to understand that boundary, diagnose memory and I/O behavior, and choose the right durability or direct-I/O operation.
What Is the Linux Page Cache?
The page cache is the kernel’s in-memory cache for file contents. The Linux kernel page-cache documentation describes it as the primary way users and the rest of the kernel interact with filesystems: normal reads, writes, and memory mappings go through it, although operations such as O_DIRECT can bypass it. In current kernel terminology, a folio is the unit of memory management used within the page cache. A folio can represent one or more physically contiguous pages, allowing the kernel to manage larger chunks of cached file data.
A process using read() receives bytes copied from a cached file range when that range is resident. If it is not resident, the kernel issues storage I/O, fills the cache, and then satisfies the read. A later reader can use the same cached data without another device request.
The cache also supports file-backed mmap(). A mapping creates virtual addresses for a file range; the first access to an absent range can cause a page fault that brings file data into memory. The Linux mmap(2) manual distinguishes shared mappings, whose changes can reach the underlying file, from private copy-on-write mappings, whose changes are not written back to that file.
The kernel VFS documentation describes the path lookup, dentries, inodes, file objects, and filesystem methods around the page cache. The page cache handles file contents; metadata caches help the kernel find and describe them.
Why Does the Page Cache Exist?
Storage is persistent but relatively slow compared with CPU and RAM. If every small read had to wait for a device, normal applications would spend much of their time stalled on storage latency. Keeping recently used file data in RAM turns repeated reads into memory accesses and lets the kernel use available memory productively without requiring each application to implement its own shared cache.
Write caching solves a different problem. Applications often produce small, adjacent, or bursty writes. The kernel can acknowledge the write after copying data into cache memory, then combine nearby changes and submit larger operations later. That reduces system-call and device overhead and lets the filesystem arrange data and metadata updates according to its consistency rules.
The trade-off is that cache memory is volatile. A dirty file range may exist only in RAM for a period of time, and a crash or power failure can lose it unless the application requested synchronization and every relevant layer honors the required durability semantics. The cache therefore improves throughput and responsiveness, but it does not by itself provide persistence.
How File Reads, Writes, and Writeback Work
A simplified path looks like this:
Application → system call or mmap() → VFS and filesystem → page cache → block layer → device or remote storage
Reads and writes follow different timing:
- A read checks the cache. If the requested file range is present, Linux can copy it to the process or map it into the process’s address space. A cache miss starts filesystem and block-layer I/O, often with readahead to fetch data the kernel predicts will be needed next.
- A buffered write changes cached data. The kernel copies or maps the new bytes into a cache folio and marks the affected file data dirty. Metadata such as file size or modification time can become dirty as well.
- Writeback submits dirty data. Background kernel workers and filesystem writeback mechanisms choose dirty pages or folios and send them through the filesystem and block layer. The storage device may still have its own volatile or non-volatile cache.
- Completion clears or updates dirty state. After the filesystem and lower layers report progress, the kernel can reclaim clean cache memory. Errors can be recorded and later reported to processes that touched the affected file.
Writeback is not one single global queue. Filesystems track dirty data by inode and superblock, while the backing device and block layer maintain their own queues and limits. The kernel uses thresholds to prevent a fast writer from consuming all available RAM with dirty data. When dirty memory grows, new writes can be throttled until writeback catches up. This is why a program can appear fast during an initial burst and then slow down once it reaches a dirty-memory limit.
Key Components and Boundaries
Folios, file offsets, and address spaces
A cached file range is associated with an inode and an address-space mapping. The mapping connects file offsets to cached folios and coordinates operations such as lookup, insertion, invalidation, and writeback. Folios are a kernel implementation detail, not a user-visible replacement for the file’s logical byte offsets. A program still reads and writes bytes; the kernel chooses how to group those bytes in memory.
Clean and dirty cache
A clean cached range agrees with the filesystem’s current view of storage, subject to the filesystem and device’s completion guarantees. A dirty range has changes that still need to be written. Clean cache can generally be discarded and refilled later. Dirty cache must be written, or the data is lost when that memory is reused or the machine stops.
Reclaim
Reclaim is memory management, not a durability command. The kernel can discard clean page-cache data because it can read it again from storage. Dirty data must first be written back before its memory can be reused. The Linux memory-management concepts documentation describes page cache as reclaimable memory and explains how kswapd performs asynchronous reclaim while direct reclaim can stall an allocating process under pressure.
This distinction explains why a machine can report a large amount of cached RAM without being out of memory. Cached memory is available for reuse when applications need it. Persistent dirty memory is different: it represents pending storage work and can contribute to writeback pressure and application stalls.
Writeback controls
Linux exposes VM controls such as dirty background thresholds, dirty limits, and writeback intervals. Their units and behavior can vary with kernel and distribution configuration, and filesystem or cgroup policies can affect the result. Inspect current values with:
sysctl vm.dirty_background_bytes vm.dirty_bytes \
vm.dirty_expire_centisecs vm.dirty_writeback_centisecs
Changing these values is not a general performance fix. Larger dirty limits can make short bursts look faster while increasing the amount of work at a later stall or increasing data at risk during a failure. Tune only with a measured workload and a defined durability and latency objective.
Buffered I/O, mmap(), and direct I/O
Buffered read() and write() use the page cache in the normal case. File-backed shared mappings also interact with the cache, but their dirtying and synchronization rules are different from a sequence of write() calls. Applications that modify a shared mapping need a suitable msync() or file synchronization strategy when they require defined persistence timing.
O_DIRECT asks Linux to minimize or bypass the page cache for the I/O path. The Linux open(2) documentation notes that direct I/O has filesystem- and device-dependent alignment requirements and that applications should not casually mix overlapping buffered and direct access. Direct I/O can avoid cache pollution for a database that already manages its own cache, but it does not automatically make writes durable or faster. Controller, device, filesystem, and remote-storage caches still matter.
Durability: write(), flush(), and fsync()
A successful buffered write() normally means that the kernel accepted the data into its in-memory path; it is not a portable promise that the bytes have reached non-volatile media. The exact guarantees depend on the system call, filesystem, mount options, device, and storage hardware.
fsync() requests synchronization for a file descriptor. The POSIX specification for fsync defines it as requesting that the file’s data be transferred to the associated storage device and says the call should not return until the action completes or an error is detected. On Linux, fsync() also synchronizes relevant file metadata, while fdatasync() can avoid metadata that is not needed to retrieve the file’s data. If a program creates or replaces a file and needs the directory entry itself to survive a crash, synchronizing only the file may not be sufficient; the directory may need its own synchronization.
The important sequence for a small file replacement is usually:
- Write the new contents to a temporary file in the target directory.
- Call
fsync()on the temporary file. - Atomically rename it over the old name.
- Open and
fsync()the containing directory when the directory entry must be durable.
The precise sequence should match the application’s failure model and filesystem documentation. fsync() is not a backup, and it cannot make a failing or misconfigured storage device trustworthy. It is a request that propagates synchronization through the supported stack; the application must handle errors.
Real-World Uses
- Databases: Database engines commonly manage their own buffer pools and use carefully selected flush and synchronization operations for transaction logs. They may use direct I/O to avoid duplicating a large database cache in the page cache, but the choice is engine- and filesystem-specific.
- File servers and content repositories: The page cache serves hot shared files, but memory pressure, readahead behavior, and network filesystem semantics affect the observed result.
- Containers and virtual machines: A container’s filesystem layers ultimately use the host kernel’s memory and storage path. A guest operating system can also cache data, creating multiple caching layers that make benchmark results difficult to interpret.
Practical Inspection and Troubleshooting
Start with observation rather than clearing caches or changing sysctls:
# See memory totals and the page-cache/writeback counters.
grep -E '^(Mem|Cached|Buffers|Dirty|Writeback|WritebackTmp|SReclaimable):' \
/proc/meminfo
# Watch runnable tasks, memory, and I/O wait over time.
vmstat 1
# Correlate filesystem mounts and block devices.
findmnt -T /var/lib
lsblk -o NAME,TYPE,FSTYPE,SIZE,ROTA,MOUNTPOINTS
In /proc/meminfo, Cached is a broad file-cache measure and Dirty is memory that needs writeback; neither number alone tells you whether an application is safe from data loss or whether a device is saturated. vmstat can reveal rising writeback activity and I/O wait, but correlate it with application latency and device statistics such as iostat -xz 1.
For a controlled benchmark, use a disposable file and state whether the test is buffered or direct. A buffered read test can mostly measure cache hits after the first pass, so do not compare it with a direct-I/O test as if they were the same workload. The block storage performance guide covers request size, queue depth, latency, and safe fio testing in more detail.
Avoid using echo 3 | sudo tee /proc/sys/vm/drop_caches as routine tuning. Dropping clean caches changes the starting conditions and can make a synthetic test less representative; it does not fix a slow device, remove dirty data safely, or improve normal application behavior. If an incident requires cache invalidation, record why it was done and measure the recovery effect.
Common Misconceptions
- “Linux uses free RAM badly because
freeshows little unused memory.” File cache is reclaimable and is intentionally used to accelerate future reads. Check available memory, reclaim activity, and pressure rather than the unused column alone. - “A completed
write()means the data is on disk.” Buffered writes can remain dirty in RAM. Use the synchronization operation appropriate to the application and verify the storage stack’s durability guarantees. - “
fsync()is the same asfflush().”fflush()moves buffered data from a C library stream to the kernel;fsync()asks the kernel to synchronize a file descriptor with storage. A program using stdio may need both. - “
O_DIRECTalways makes storage faster.” Direct I/O can reduce double caching for some workloads, but alignment, concurrency, filesystem behavior, device caches, and application buffer management can make it slower or more complex. - “Reclaim writes every cached page.” Clean cache can be discarded without I/O. Dirty pages need writeback before their memory can be reused, which is why dirty pressure can cause stalls.
Related Articles
- Linux blk-mq and multi-queue block I/O explains the block-layer queues below the filesystem and page cache.
- Block storage performance and benchmarking covers workload design, IOPS, throughput, latency, and queue depth.
- Btrfs vs. ZFS filesystem architecture compares filesystems whose copy-on-write and caching behavior affect storage operations.
- Container storage for persistent workloads connects host filesystems and caches to Docker and Kubernetes storage choices.
Changelog
- Initial publication.
Last updated: 2026-12-02

