Course contentsShow
← Linux
Lesson 726 of 1,8197. Storage Management and Logical VolumesFree lesson

Btrfs defragmentation techniques

Execute targeted defragmentation for database and high-churn filesets.

In this lesson, you will learn how to optimize performance for high-churn data by performing targeted defragmentation on specific files and directories in a Btrfs filesystem.

The Problem with High-Churn Data

Because Btrfs uses Copy-on-Write (CoW), every time you modify a file, the system writes the changes to a new block rather than overwriting the original. Over time, files that are frequently updated—like virtual machine images or active database files—become heavily fragmented. This forces the disk heads to jump around to read a single file, significantly slowing down performance.

Targeted Defragmentation

While you can defragment an entire subvolume, it is often more efficient to target only the problematic data. Defragmenting the entire disk is resource-intensive, so for high-churn filesets, we focus our efforts exactly where they are needed.

To defragment a specific file (such as a database file), use the btrfs filesystem defragment command:

# Defragment a single database file
sudo btrfs filesystem defragment /path/to/database.db

# Defragment an entire directory of high-churn files recursively
sudo btrfs filesystem defragment -r /var/lib/my-database/

Tips for Better Results

When dealing with databases, fragmentation is an ongoing battle. If you notice performance dips recurring, you can combine the command with the -c flag to compress the data while defragmenting, which can further reduce I/O overhead:

# Defragment and apply zlib compression to a directory
sudo btrfs filesystem defragment -r -c zlib /var/lib/my-database/

Keep in mind that while defragmentation is helpful for file-based workloads, it does not stop the underlying CoW process; it simply "cleans up" the current state of the file by rewriting it into contiguous blocks. For databases that are constantly being rewritten, you may need to schedule these commands as a periodic task via cron to keep performance stable.

Key Takeaway: Use btrfs filesystem defragment with the -r flag to surgically target high-churn directories, improving read/write speeds for fragmented database and application files without the need to process the entire filesystem.