Quick take: Linux caches disk reads in RAM to dramatically speed up repeated file access. You can force the kernel to release this cache with echo 1/2/3 > /proc/sys/vm/drop_caches and clear swap with swapoff -a && swapon -a. These are safe operations — but clearing cache on a healthy production server is usually counterproductive.
Introduction
If you've ever run free -h on a Linux system and been alarmed by the "used" column showing most of your RAM occupied, you've experienced one of Linux's most misunderstood design decisions: the kernel deliberately fills available RAM with disk cache. This isn't a memory leak — it's a feature. Linux uses idle RAM to buffer and cache filesystem data, making future reads from those files nearly instantaneous.
That said, there are legitimate scenarios where you need to free this cached memory: running memory benchmarks with a clean baseline, investigating memory leaks, recovering from a misconfigured application that has filled swap, or testing system behavior under memory pressure. This guide covers every method to clear RAM cache, buffer cache, and swap space on Linux, along with the exact commands, what each one does, and when you should (and shouldn't) use them.
Understanding Linux Memory Management
Linux treats RAM as a performance resource rather than a storage resource. The kernel's memory manager tracks four broad categories of memory usage:
- Used: Memory actively allocated by running processes.
- Free: Completely unused RAM — Linux tries to keep this close to zero by proactively caching.
- Buff/cache: Memory used by the kernel for disk buffers and the page cache. This can be reclaimed instantly if a process needs it.
- Available: The most honest column — an estimate of how much memory can be given to new processes without swapping. Includes most of buff/cache.
The key insight is that buff/cache memory is not wasted. The kernel reclaims it automatically when processes need more RAM. What drop_caches does is force-evict this cache before the kernel naturally would, giving you an empty cache at the cost of subsequent disk reads being slower until the cache refills.
Types of Cache in Linux
Linux maintains three distinct types of cache that drop_caches can target:
- Page cache: Cached copies of file contents read from disk. When you open a file, Linux reads it into the page cache. Subsequent reads of the same file are served from RAM. This is the largest cache category on most systems.
- Dentry cache: Cached directory entries — the mapping between file names and inode numbers. Clearing this forces the kernel to re-read directory structures from disk on next access.
- Inode cache: Cached file metadata — permissions, timestamps, file size, block locations. Clearing this forces the kernel to re-read file attributes from disk.
- Slab cache: Kernel data structure allocations managed by the slab allocator. The dentry and inode caches are stored in the slab cache.
drop_cacheswith values 2 or 3 flushes the relevant slab objects.
Checking Current Memory Usage
Always check memory state before and after clearing cache to understand the impact:
# Human-readable memory overview
free -h
# Detailed memory information
cat /proc/meminfo
# Real-time memory monitoring
watch -n 1 'free -h'
# Slab cache usage breakdown
sudo slabtop -o
# Buffer and cache breakdown via vmstat
vmstat -s
The output of free -h on a typical system looks like this:
total used free shared buff/cache available
Mem: 31Gi 4.2Gi 1.1Gi 512Mi 26Gi 26Gi
Swap: 8.0Gi 0B 8.0Gi
In this example, 26 GB is in buff/cache, but "available" is also 26 GB — meaning all of that cache can be freely given to processes. The system is healthy, not memory-starved.
How to Clear Page Cache (echo 1)
Writing 1 to /proc/sys/vm/drop_caches instructs the kernel to free clean pages from the page cache — cached file contents that haven't been modified since they were read. Dirty pages (modified data not yet written to disk) are never freed by this operation.
# Always sync first to commit pending writes
sync
# Clear page cache only
sudo sh -c 'echo 1 > /proc/sys/vm/drop_caches'
# Alternatively, using sysctl
sudo sysctl -w vm.drop_caches=1
# Verify the result
free -h
Running sync before drop_caches is a best practice — it flushes all pending writes from the write buffer to disk before the cache is dropped, eliminating any theoretical risk of data inconsistency. In practice, dirty pages are not freed by drop_caches, but sync is a good habit before any memory or storage operation.
How to Clear Dentries and Inodes (echo 2)
Writing 2 frees the dentry and inode caches — the kernel's in-memory map of the filesystem directory structure and file metadata. This does not free the page cache (file contents).
# Clear dentries and inodes only
sync
sudo sh -c 'echo 2 > /proc/sys/vm/drop_caches'
When would you use this instead of echo 3? Rarely — this option is most useful when debugging filesystem metadata operations or testing tools that measure directory traversal and stat() call overhead with a cold metadata cache. On typical Linux systems, the dentry and inode caches are much smaller than the page cache.
How to Clear All Cache (echo 3)
Writing 3 clears all three: page cache, dentry cache, and inode cache. This is the most commonly used option when you want to reclaim the maximum possible memory from cache.
# Clear all cache (page cache + dentries + inodes)
sudo sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches'
# One-liner with confirmation
sudo sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches' && echo "Cache cleared" && free -h
After running this, your free -h output will show a dramatically reduced buff/cache number and a correspondingly higher free value. The next time files are accessed, the kernel will re-read them from disk and rebuild the cache. Expect noticeably slower disk I/O for a few minutes while the cache warms back up.
Important limitation: This is a one-time operation. The kernel will immediately begin rebuilding the cache as soon as any process reads a file. You cannot permanently reduce Linux's cache usage with this command — Linux will always use available free RAM for caching.
How to Clear Swap Space
Swap space is disk space used to extend virtual memory when RAM fills up. Swapped pages are slower than RAM pages by several orders of magnitude. Clearing swap moves all swapped data back into RAM and resets the swap partition to empty.
# Check current swap usage before clearing
swapon --show
free -h
# Clear swap: disable it (moves data back to RAM), then re-enable
sudo swapoff -a && sudo swapon -a
# Verify swap is now empty
free -h
swapon --show
Critical warning: swapoff -a moves all swapped data back into RAM. If your system has very little free RAM and significant swap usage, this command will fail or cause the OOM (Out-Of-Memory) killer to terminate processes. Always check free -h first and ensure you have enough free RAM to absorb the swap contents before running swapoff -a.
To identify which processes are using the most swap before clearing:
# List top swap consumers
for pid in /proc/[0-9]*; do
swap=$(grep VmSwap "$pid/status" 2>/dev/null | awk '{print $2}')
if [ -n "$swap" ] && [ "$swap" -gt 0 ]; then
name=$(grep Name "$pid/status" 2>/dev/null | awk '{print $2}')
echo "$swap kB - $name (PID: ${pid##*/})"
fi
done | sort -rn | head -20
Automating Cache Clearing with Cron
For environments where you want to schedule periodic cache clearing (memory benchmarking setups, certain embedded applications), you can add the command to cron:
# Edit root's crontab
sudo crontab -e
# Example: clear page cache every day at 2 AM
0 2 * * * /bin/sh -c 'sync; echo 1 > /proc/sys/vm/drop_caches'
A better approach for production environments is to write a script that checks available memory first and only drops cache if free RAM is below a threshold — this avoids dropping useful cache when memory pressure is already low.
#!/bin/bash
# Clear page cache only if available memory is below 500 MB
AVAILABLE=$(awk '/MemAvailable/ {print $2}' /proc/meminfo)
THRESHOLD=512000 # 500 MB in kB
if [ "$AVAILABLE" -lt "$THRESHOLD" ]; then
sync
echo 1 > /proc/sys/vm/drop_caches
logger "drop_caches: freed page cache (available was ${AVAILABLE}kB)"
fi
When Should You Clear Cache?
Clearing cache is appropriate in specific situations — and actively harmful in others:
Appropriate use cases:
- Running disk I/O or memory benchmarks where you need a cold cache baseline.
- Debugging an application's memory usage by isolating its own allocations from cached data.
- After a large batch job (database import, log processing) that filled the cache with data you won't need again.
- Recovering from a memory configuration mistake where swap is full and processes are being killed.
When not to clear cache:
- As a routine maintenance task on production servers — this only causes temporary slowdowns as the cache rebuilds.
- When running a database server — databases rely heavily on the page cache for query performance.
- When the system is under active load — dropping cache mid-workload causes a burst of disk reads that can spike latency.
- When you're trying to "fix" high memory usage — high cache usage is normal and healthy on Linux.
Final Thoughts
The Linux page cache is one of the most effective performance mechanisms in the kernel. Understanding it properly helps you stop misinterpreting free -h output as a problem and start using cache clearing as a precise tool rather than a maintenance habit. The /proc/sys/vm/drop_caches interface is safe, well-documented, and production-grade — but reaching for it without understanding what you're clearing and why usually does more harm than good.
For genuine memory pressure on production systems, the right tools are OOM analysis with dmesg | grep -i 'oom\|killed', swap tuning via vm.swappiness, and profiling actual process memory usage with smem or /proc/[pid]/smaps — not blindly dropping cache and hoping for the best.
FAQ: Clear RAM Cache, Buffer and Swap on Linux
Is it safe to clear Linux RAM cache while services are running?+
Yes, dropping the page cache is safe while services are running. The kernel only frees pages that are not currently in use — dirty pages (modified data not yet written to disk) are never freed by drop_caches. Running sync first ensures any pending writes are committed. Services will re-read data from disk on the next access, with a brief performance dip while the cache warms back up.
What is the difference between sync and drop_caches?+
sync writes all pending dirty data from memory to disk without freeing any cache. drop_caches instructs the kernel to release cached memory pages (page cache, dentry cache, or inode cache). You should run sync before drop_caches as a best practice: sudo sh -c 'sync; echo 3 > /proc/sys/vm/drop_caches'. Dirty pages are not freed by drop_caches regardless, so skipping sync is technically safe but not recommended.
Why does Linux use so much RAM for cache?+
Linux deliberately uses available RAM for disk caching because idle RAM is wasted RAM. Cached data is served directly from memory — orders of magnitude faster than reading from disk. The kernel tracks which cached pages are "clean" and frees them automatically when a process needs more memory. A system showing high buff/cache in free -h is healthy and performing well, not suffering a memory problem.
How do I clear swap space without rebooting on Linux?+
Run sudo swapoff -a && sudo swapon -a. This disables all swap (moving swapped data back into RAM), then re-enables it empty. Before running this, check free -h to ensure you have enough free RAM to hold all swapped data — if free RAM is insufficient, swapoff will fail or trigger the OOM killer.
Will clearing the Linux page cache improve performance?+
No — clearing the page cache removes data the kernel was keeping ready for fast access, so the system will be noticeably slower immediately after until the cache refills. Clearing cache is only useful for benchmarking (cold-cache baselines), debugging memory isolation scenarios, or post-batch-job cleanup. It is not a routine performance improvement technique and should not be run as a scheduled maintenance task on production servers.
Need help with infrastructure or virtualization?
Work directly with Muhammad Irfan Aslam for Linux, Proxmox, Docker, DevOps, cloud, CI/CD, or infrastructure support.
Hire Me for Support