Compaction and Vacuum

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 8 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Compaction and Vacuum: Mastering Database Maintenance

In the world of high-performance database management, the physical storage of your data is rarely a static affair. When you update or delete a row in a relational database like PostgreSQL or a key-value store like Cassandra, the system does not always immediately reclaim that space. Instead, it often marks the old data as "dead" and writes the new version elsewhere. Over time, this creates "bloat"—a phenomenon where your database files grow significantly larger than the actual data they contain. This leads to slower read queries, increased storage costs, and inefficient cache utilization.

This lesson explores two fundamental mechanisms used to combat this degradation: Vacuuming (specifically in the context of MVCC-based systems like PostgreSQL) and Compaction (the primary strategy for Log-Structured Merge-tree storage engines like Cassandra, RocksDB, or LevelDB). Understanding these processes is not just an administrative task; it is a core performance engineering skill that separates efficient database operators from those who constantly battle mysterious performance spikes.


Not read yet

The Core Problem: Why Do We Need Maintenance?

To understand compaction and vacuuming, we must first understand why databases become messy in the first place. Most modern databases prioritize write performance. Writing to the end of a file or appending data to a log is significantly faster than seeking to a specific location on a disk to overwrite existing bytes. This "append-only" or "copy-on-write" approach ensures that writes are fast and that the system can handle concurrent transactions without locking the entire table.

However, this design creates a storage debt. When you update a record, the database writes a new version. The old version remains on the disk, occupying space. If you delete a record, the database simply marks it as invisible to future queries, but the physical bytes remain. This accumulated "dead space" is known as bloat. Bloat impacts performance because:

  1. I/O Overhead: The database engine must scan through dead tuples or outdated keys to find the live data you are actually looking for.
  2. Memory Pressure: Your cache (RAM) becomes filled with dead, useless data rather than the frequently accessed live records.
  3. Storage Costs: You end up paying for disk space that holds nothing of value to your application.

Not read yet

Part 1: The Vacuuming Mechanism (MVCC Systems)

Vacuuming is the process of cleaning up dead tuples in systems that use Multi-Version Concurrency Control (MVCC). PostgreSQL is the most prominent example of this. When a transaction updates a row, PostgreSQL creates a new version of that row and updates the pointer. The old version becomes "dead" once the transaction that created it completes, but the database doesn't know if other long-running transactions still need that old version for a consistent snapshot.

How VACUUM Works

The basic VACUUM command scans the table and identifies which rows are no longer needed by any active transaction. It then marks those slots as available for future inserts. It does not shrink the physical file size; it simply makes the space reusable by the database engine.

If you want to actually return space to the operating system, you use VACUUM FULL. However, VACUUM FULL is a heavy operation—it effectively locks the table and rewrites the entire file to a new location. This is generally avoided in high-traffic production environments unless absolutely necessary.

Automated Maintenance: Autovacuum

In modern PostgreSQL, you should almost never run manual VACUUM commands for routine maintenance. The autovacuum daemon is a background process that monitors your tables and triggers cleanup automatically based on configuration thresholds.

Callout: VACUUM vs. VACUUM FULL

  • VACUUM: Reclaims space within the existing file for reuse by the database. It is non-blocking and safe to run while the application is active.
  • VACUUM FULL: Reclaims space by creating a new, compact version of the table. It requires an exclusive lock, meaning no other reads or writes can occur on the table during the process. Use this only during scheduled maintenance windows.

Configuring Autovacuum for Performance

To keep your database healthy, you must tune the autovacuum settings. The default settings are often too conservative for high-volume databases. Key parameters include:

  • autovacuum_vacuum_scale_factor: This determines what percentage of a table must change before a vacuum is triggered. If you have a table with 10 million rows and the factor is 0.2, autovacuum will trigger once 2 million rows are updated or deleted.
  • autovacuum_vacuum_cost_limit: This controls how much work the autovacuum process can do before it pauses. If your vacuuming is too aggressive and interfering with application performance, you can lower this limit. Conversely, if your bloat is growing faster than the vacuum can clean, you should increase it.

Warning: The Transaction ID Wraparound PostgreSQL uses 32-bit integers to track transaction IDs. If these IDs wrap around, the database can experience severe data corruption. Autovacuum is the primary mechanism that prevents this by "freezing" old rows. Never disable autovacuum entirely, as it is a critical safety feature.


Not read yet

Part 2: The Compaction Mechanism (LSM Trees)

While MVCC databases use Vacuuming, storage engines based on Log-Structured Merge-trees (LSM trees)—such as Cassandra, RocksDB, and LevelDB—use a process called Compaction. These engines are designed for write-heavy workloads. They accept writes into an in-memory buffer (MemTable) and periodically flush them to disk as immutable files called SSTables (Sorted String Tables).

The Compaction Process

Because SSTables are immutable, you cannot update or delete data in place. Instead, you write a "tombstone" (a marker indicating deletion) or a new version of the key. Over time, you end up with multiple versions of the same key spread across different files. Compaction is the background process that merges these files, discards the tombstone-marked entries, keeps only the latest version of each key, and writes a fresh, optimized file.

Common Compaction Strategies

Different database systems offer different compaction strategies, each suited for specific workloads:

  1. Size-Tiered Compaction Strategy (STCS): This is the default in many systems. It groups files of similar size and merges them into larger files. It is excellent for write-heavy workloads but can be inefficient for read-heavy ones because a single key might exist in multiple levels.
  2. Leveled Compaction Strategy (LCS): This strategy organizes data into levels. Each level is strictly partitioned. This results in much better read performance because you only ever need to check one file per level to find a key. However, it requires significantly more write I/O to maintain the structure.
  3. Time-Window Compaction Strategy (TWCS): This is designed for time-series data. It groups data by time buckets. Once a time window passes, the entire SSTable is compacted and then effectively ignored. This makes "dropping" old data extremely fast and efficient.

The Trade-off: Write Amplification

A critical concept in compaction is "Write Amplification." Because compaction involves reading data from disk, merging it, and writing it back, a single logical write from your application might result in multiple physical writes to the disk.

Strategy Best For Read Performance Write Performance
Size-Tiered Write-heavy, logs Moderate High
Leveled Read-heavy, key-value High Moderate
Time-Window Time-series, events Moderate High

Not read yet

Part 3: Practical Implementation and Monitoring

Optimizing these processes requires a combination of observation and configuration. You cannot manage what you do not measure.

Monitoring Vacuum/Compaction Health

For PostgreSQL, you should monitor the age of your tables. You can use the following query to identify tables that are accumulating significant bloat:

SELECT
  relname AS table_name,
  n_dead_tup AS dead_tuples,
  last_autovacuum,
  last_autoanalyze
FROM pg_stat_user_tables
WHERE n_dead_tup > 10000 -- Look for tables with significant bloat
ORDER BY n_dead_tup DESC;

For LSM-based systems like Cassandra, you should monitor the "pending compactions" metric. If this number is consistently rising, your compaction throughput cannot keep up with your incoming write rate, and your database will eventually hit a performance wall.

Step-by-Step: Tuning for a Busy Table

If you notice a specific table in PostgreSQL is consistently showing high bloat despite autovacuum running, follow these steps:

  1. Analyze the workload: Is the table receiving a massive amount of updates? If so, the default autovacuum settings are likely too slow.
  2. Check current settings: Run \d+ table_name in your database client to see if custom autovacuum settings have been applied.
  3. Adjust thresholds: Lower the autovacuum_vacuum_scale_factor for that specific table to trigger cleanup sooner.
    ALTER TABLE my_high_traffic_table SET (
      autovacuum_vacuum_scale_factor = 0.05,
      autovacuum_vacuum_threshold = 1000
    );
    
  4. Monitor: Keep an eye on the pg_stat_user_tables view for the next 24 hours to ensure the bloat stays within acceptable limits.

Callout: The "Cost" of Compaction Compaction and Vacuuming are "background" tasks, but they consume CPU and I/O bandwidth. If you set your thresholds too aggressively, the maintenance tasks will compete with your application queries for resources, causing latency spikes. Always tune these parameters incrementally and observe the impact on your latency percentiles (P99).


Not read yet

Best Practices for Database Maintenance

Maintaining a healthy database is a continuous process of calibration. Below are industry-standard practices for managing compaction and vacuuming.

1. Prioritize I/O Throughput

Maintenance tasks are I/O intensive. If your database is running on cloud-based storage (like AWS EBS), ensure you have enough Provisioned IOPS. If the disk is saturated with maintenance writes, your application will experience "stalls" where queries seem to hang.

2. Schedule Heavy Maintenance

Avoid running manual, heavy operations like VACUUM FULL or massive compaction merges during peak traffic hours. Use monitoring tools to identify your daily traffic troughs and automate your maintenance jobs to run during those windows.

3. Keep Statistics Updated

Vacuuming and Analyzing go hand-in-hand. While VACUUM cleans up space, ANALYZE updates the statistics the query planner uses to decide how to execute queries. If your stats are stale, the database might choose a slow table scan instead of a fast index lookup. Most autovacuum configurations include an autoanalyze component—ensure it is enabled.

4. Monitor Disk Usage Trends

Don't just look at the current disk usage; look at the rate of change. If your disk usage is increasing linearly, you are likely failing to reclaim space effectively. This is a clear indicator that your compaction or vacuum settings are not tuned to your current write volume.

5. Avoid "Over-Tuning"

A common mistake is to set vacuum thresholds to extremely low values in an attempt to keep the database "perfectly clean." This is counter-productive. Frequent vacuuming causes unnecessary I/O overhead. Aim for a "good enough" state where bloat is kept within a manageable range (e.g., 10-20%) rather than zero.


Not read yet

Common Pitfalls and How to Avoid Them

Pitfall 1: The "Vacuum Lag"

This happens when autovacuum cannot keep up with the rate of data modification. The result is a table that grows indefinitely until the disk is full.

  • Solution: Check your logs for "autovacuum worker" saturation. If all available workers are busy, you may need to increase autovacuum_max_workers in your configuration.

Pitfall 2: Compaction Backlog

In systems like Cassandra, if compaction cannot keep up, you end up with "read amplification." A single read request might have to check dozens of SSTables to find the latest version of a row.

  • Solution: Increase the compaction throughput limit if your hardware can handle it. If the hardware is maxed out, consider adding more nodes to the cluster to distribute the I/O load.

Pitfall 3: Ignoring Tombstones

In LSM systems, if you perform a massive delete (e.g., "delete all data older than 2 years"), you create a massive number of tombstones. If these aren't compacted, your reads will slow down significantly as the engine processes these markers.

  • Solution: Use time-based compaction strategies (TWCS) for time-series data. This allows the system to drop entire files of data without generating individual tombstones.

Pitfall 4: Misconfigured "Freezing"

In PostgreSQL, if vacuum_freeze_min_age is set too high, the system may struggle to freeze rows effectively, leading to transaction ID wraparound risks.

  • Solution: Stick to reasonable defaults unless you have a very specific reason to change them. The default settings are designed to be safe for a wide variety of workloads.

Not read yet

Quick Reference: Maintenance Checklist

Task Frequency Impact
Monitor Bloat Daily Low
Review Autovacuum Logs Weekly Low
Check I/O Saturation Daily Low
Tune Thresholds As Needed Moderate
Run Manual Vacuum Full Rarely/Maintenance High (Blocking)
Check Compaction Pending Daily Low

Key Takeaways

  1. Maintenance is Mandatory: Databases that rely on MVCC or LSM trees require background processes (Vacuuming or Compaction) to reclaim space and maintain performance. Ignoring these leads to slow queries and eventual system failure.
  2. Understand Your Engine: Whether your database uses Vacuuming (PostgreSQL) or Compaction (Cassandra/RocksDB), the underlying goal is the same: reduce I/O by removing dead or superseded data.
  3. Optimize for Your Workload: There is no "perfect" configuration. Use Size-Tiered compaction for write-heavy logs, Leveled compaction for read-heavy key-value stores, and aggressive autovacuuming for high-update relational tables.
  4. Don't Fear the Background Process: Autovacuum and Compaction are your friends. They are automated janitors. Your goal as an administrator is to ensure they have enough resources to finish their work without starving your primary application.
  5. Measure Before You Change: Always use monitoring tools (like pg_stat_user_tables or database-specific metrics) to verify that a problem exists before changing configuration parameters. Incremental changes are safer than drastic overhauls.
  6. I/O is the Bottleneck: Maintenance tasks are essentially I/O tasks. If you find that your maintenance is falling behind, you likely need to optimize your storage throughput or scale your hardware.
  7. The "Maintenance Window" is Still Relevant: Even with automated systems, there are times when heavy maintenance is needed. Having a well-defined maintenance window allows you to perform operations like VACUUM FULL or major compaction re-indexes without impacting your users.

By mastering these concepts, you shift from being a reactive administrator who "fixes" the database when it slows down to a proactive performance engineer who ensures the database stays lean, fast, and reliable under any load. Remember: a database that cleans itself is a database that scales.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.