Compaction and Vacuum
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② 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:
- I/O Overhead: The database engine must scan through dead tuples or outdated keys to find the live data you are actually looking for.
- Memory Pressure: Your cache (RAM) becomes filled with dead, useless data rather than the frequently accessed live records.
- 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:
- 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.
- 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.
- 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:
- Analyze the workload: Is the table receiving a massive amount of updates? If so, the default autovacuum settings are likely too slow.
- Check current settings: Run
\d+ table_namein your database client to see if custom autovacuum settings have been applied. - Adjust thresholds: Lower the
autovacuum_vacuum_scale_factorfor that specific table to trigger cleanup sooner.ALTER TABLE my_high_traffic_table SET ( autovacuum_vacuum_scale_factor = 0.05, autovacuum_vacuum_threshold = 1000 ); - Monitor: Keep an eye on the
pg_stat_user_tablesview 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_workersin 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
- 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.
- 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.
- 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.
- 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.
- Measure Before You Change: Always use monitoring tools (like
pg_stat_user_tablesor database-specific metrics) to verify that a problem exists before changing configuration parameters. Incremental changes are safer than drastic overhauls. - 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.
- 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 FULLor 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.
- Workspace Level Access Controls
- Workspace Level Access Controls Quiz5q
- Item Level Access Controls
- Item Level Access Controls Quiz5q
- Row and Column Level Security
- Row and Column Level Security Quiz5q
- Object and File Level Security
- Object and File Level Security Quiz5q
- Dynamic Data Masking
- Dynamic Data Masking Quiz5q
- Sensitivity Labels
- Sensitivity Labels Quiz5q
- Fabric Audit Logs
- Fabric Audit Logs Quiz5q
- OneLake Security Configuration
- OneLake Security Configuration Quiz5q
- Endorsing Items
- Endorsing Items Quiz5q
- Choosing Orchestration Tools
- Choosing Orchestration Tools Quiz5q
- Schedules and Event Triggers
- Schedules and Event Triggers Quiz5q
- Orchestration with Notebooks
- Orchestration with Notebooks Quiz5q
- Parameters and Dynamic Expressions
- Parameters and Dynamic Expressions Quiz5q
- Pipeline Patterns
- Pipeline Patterns Quiz5q
- Choosing Data Stores
- Choosing Data Stores Quiz5q
- Transformation Tool Selection
- Transformation Tool Selection Quiz5q
- OneLake Shortcuts
- OneLake Shortcuts Quiz5q
- Implementing Mirroring
- Implementing Mirroring Quiz5q
- Pipeline Data Ingestion
- Pipeline Data Ingestion Quiz5q
- PySpark Transformations
- PySpark Transformations Quiz5q
- SQL Transformations
- SQL Transformations Quiz5q
- KQL Transformations
- KQL Transformations Quiz5q
- Data Denormalization
- Data Denormalization Quiz5q
- Grouping and Aggregating Data
- Grouping and Aggregating Data Quiz5q
- Handling Duplicate Data
- Handling Duplicate Data Quiz5q
- Handling Missing and Late Data
- Handling Missing and Late Data Quiz5q
- Dataflows Gen2 Ingestion
- Dataflows Gen2 Ingestion Quiz5q
- Delta Lake Table Management
- Delta Lake Table Management Quiz5q
- Choosing Streaming Engine
- Choosing Streaming Engine Quiz5q
- Native Tables vs OneLake Shortcuts
- Native Tables vs OneLake Shortcuts Quiz5q
- Query Acceleration for Shortcuts
- Query Acceleration for Shortcuts Quiz5q
- Eventstreams Processing
- Eventstreams Processing Quiz5q
- Spark Structured Streaming
- Spark Structured Streaming Quiz5q
- KQL for Streaming
- KQL for Streaming Quiz5q
- Windowing Functions
- Windowing Functions Quiz5q
- Tumbling and Hopping Windows
- Tumbling and Hopping Windows Quiz5q
- Pipeline Error Resolution
- Pipeline Error Resolution Quiz5q
- Dataflow Gen2 Error Resolution
- Dataflow Gen2 Error Resolution Quiz5q
- Notebook Error Resolution
- Notebook Error Resolution Quiz5q
- Eventhouse Error Resolution
- Eventhouse Error Resolution Quiz5q
- Eventstream Error Resolution
- Eventstream Error Resolution Quiz5q
- T-SQL Error Resolution
- T-SQL Error Resolution Quiz5q
- OneLake Shortcut Error Resolution
- OneLake Shortcut Error Resolution Quiz5q
- Lakehouse Table Optimization
- Lakehouse Table Optimization Quiz5q
- Pipeline Optimization
- Pipeline Optimization Quiz5q
- Data Warehouse Optimization
- Data Warehouse Optimization Quiz5q
- Eventstreams and Eventhouses Optimization
- Eventstreams and Eventhouses Optimization Quiz5q
- Spark Performance Optimization
- Spark Performance Optimization Quiz5q
- Query Performance Optimization
- Query Performance Optimization Quiz5q
- V-Order Optimization
- V-Order Optimization Quiz5q
- Compaction and Vacuum
- Compaction and Vacuum Quiz5q
- Partitioning and Z-Order
- Partitioning and Z-Order Quiz5q
- Caching Strategies
- Caching Strategies Quiz5q
- Query Optimization Techniques
- Query Optimization Techniques Quiz5q
- Parallel Processing Configuration
- Parallel Processing Configuration Quiz5q
- Data Skew Resolution
- Data Skew Resolution Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-700 exam-style practice questions.
Practice for DP-700