dataiotech Labs
Back to Performance Guide
[MySQL]DEEP DIVEMySQL 8.4 LTS / 8.024 minSenior DBA / SRE

[MySQL] DEEP DIVE: InnoDB Purge and Undo Tuning — The MySQL Counterpart of Vacuum

If Vacuum lags in PostgreSQL, the table bloats. If Purge lags in MySQL, Undo bloats. The result is the same: The table grows, queries slow down, disk fills up, and worst of all the system stalls because of a long transaction. In this guide you will learn InnoDB's MVCC model, how the Purge mechanism works, why Undo tablespace grows, what History List Length means, and how to keep Purge healthy in production.

Production Incident Scenario

There is a table. `orders` table, 20 million rows. Every day 500 thousand rows are updated. The DBA looks: Table size grows 30 GB every month but row count is the same. Disk is filling up. Queries are getting slower. In `SHOW ENGINE INNODB STATUS` output, `History list length` is 2 million. So 2 million old row versions are waiting to be purged. Why? Because a reporting transaction has been open for 6 hours. Purge cannot delete old versions that transaction might still see. One long transaction stopped Purge, bloated Undo, slowed the whole system. This guide shows how to diagnose and fix that problem.

Summary

If Vacuum lags in PostgreSQL, the table bloats. If Purge lags in MySQL, Undo bloats. The result is the same: The table grows, queries slow down, disk fills up, and worst of all the system stalls because of a long transaction. In this guide you will learn InnoDB's MVCC model, how the Purge mechanism works, why Undo tablespace grows, what History List Length means, and how to keep Purge healthy in production.

Scenario

There is a table. orders table, 20 million rows. Every day 500 thousand rows are updated. The DBA looks: Table size grows 30 GB every month but row count is the same. Disk is filling up. Queries are getting slower. In SHOW ENGINE INNODB STATUS output, History list length is 2 million. So 2 million old row versions are waiting to be purged. Why? Because a reporting transaction has been open for 6 hours. Purge cannot delete old versions that transaction might still see. One long transaction stopped Purge, bloated Undo, slowed the whole system. This guide shows how to diagnose and fix that problem.

Concept: MVCC — Multiple Versions of the Same Row

InnoDB keeps multiple versions of the same row. This is called MVCC. Multi-Version Concurrency Control.

Analogy: Think of different versions of a document. While you edit the document, someone else continues reading the old version. Nobody waits for anyone. But old versions cannot be kept forever. After a while they must be cleaned.

In PostgreSQL, Vacuum does this cleaning. In MySQL, Purge does it.

When you update a row, what happens?

  1. 1The old version is written to Undo log.
  2. 2The new version is written to the table.
  3. 3The old version is kept if there are transactions that still need to read it.
  4. 4If no transaction needs that old version, Purge deletes it.

Purge is like a garbage collector. It collects old versions and reclaims space.

How Does Purge Work?

Purge is a background cleaning process. It has 3 main parts:

  • •Purge Threads: Worker threads that do the cleaning. By default there are 4.
  • •Undo Tablespace: The area where old versions are stored. In MySQL 8.0 by default undo_001 and undo_002 files.
  • •History List: The list of old versions waiting to be purged. As this list grows, Purge is falling behind.

▸What Is Purge Lag?

Purge Lag means Purge is falling behind. New old versions are produced but Purge cannot delete them. Reasons:

  • •A long transaction stays open.
  • •Purge thread count is insufficient.
  • •Write load is very high.
  • •Disk is slow.

As Purge Lag grows, Undo bloats, table bloats, queries slow down.

Step 1: Is Purge Healthy? Understand in 60 Seconds

The most important metric is History List Length.

sql
SHOW ENGINE INNODB STATUS\G

In the output, look for this in the TRANSACTIONS section:

text
History list length 12345

▸How to Interpret the Value?

  • •0 - 1,000: Excellent. Purge is keeping up.
  • •1,000 - 10,000: Normal. It can reach this value during heavy hours.
  • •10,000 - 100,000: Warning. Purge is starting to fall behind. Look at the cause.
  • •100,000 - 1,000,000: Problem. There is a long transaction or Purge insufficiency.
  • •Over 1,000,000: Crisis. Purge may have stopped. Intervene immediately.

More practical method, monitor with Performance Schema:

sql
SELECT VARIABLE_NAME, VARIABLE_VALUE FROM performance_schema.global_status WHERE VARIABLE_NAME LIKE '%purge%' OR VARIABLE_NAME LIKE '%undo%' OR VARIABLE_NAME LIKE '%history%';

Also check Undo tablespace size:

sql
SELECT TABLESPACE_NAME, FILE_NAME, ROUND((TOTAL_EXTENTS * EXTENT_SIZE) / 1024 / 1024, 2) AS size_mb FROM information_schema.files WHERE TABLESPACE_NAME LIKE 'undo%';

If Undo files constantly grow and never shrink, Purge is not keeping up.

Step 2: Find the Long Transaction Blocking Purge

The most common cause of Purge problems is a long transaction. Because Purge cannot delete an old version that an open transaction might still see. Until that transaction closes, those versions must be kept.

Find long transactions:

sql
SELECT trx_id, trx_state, trx_started, TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS time_sec, trx_mysql_thread_id AS thread_id, LEFT(trx_query, 150) AS query_text FROM information_schema.innodb_trx ORDER BY trx_started LIMIT 20;

If a transaction has been open for more than 1 hour, it is blocking Purge. Find it first, then ask its owner.

▸Types of Long Transactions

  • •Reporting transaction: A 6-hour report holds all old versions. Run the report on a read replica. Not on the primary.
  • •Forgotten transaction: The application opened a transaction but never closed it. commit or rollback is missing in code. Similar to idle in transaction in PostgreSQL.
  • •Backup transaction: During mysqldump or xtrabackup, a long transaction may stay open. Check the backup method.
  • •Interactive session: Someone opened a transaction in a MySQL client and went to lunch. The most common and most annoying reason.

▸What Should You Do?

First find the owner of the transaction. Application, report, or human?

sql
SELECT ID AS process_id, USER AS user_name, HOST AS source, DB AS database_name, TIME AS time_sec, STATE AS state, LEFT(INFO, 150) AS query_text FROM information_schema.processlist WHERE TIME > 300 ORDER BY TIME DESC;

If the transaction has been open for more than 30 minutes and the owner is unreachable, as a last resort kill it:

sql
-- First verify the PID, then kill it KILL 12345;

But warn before killing. Because the killed transaction is rolled back and its work is lost.

Step 3: Check Purge Settings

Purge is sufficient with default settings in most systems. But write-heavy systems may need tuning.

sql
SHOW VARIABLES LIKE 'innodb_purge_threads'; SHOW VARIABLES LIKE 'innodb_purge_batch_size'; SHOW VARIABLES LIKE 'innodb_max_purge_lag'; SHOW VARIABLES LIKE 'innodb_max_purge_lag_delay'; SHOW VARIABLES LIKE 'innodb_undo_tablespaces'; SHOW VARIABLES LIKE 'innodb_undo_log_truncate';

▸innodb_purge_threads — How Many Cleaning Workers?

ini
[mysqld] innodb_purge_threads = 4

Default is 4. In write-heavy systems it can be increased to 8. But above 8, usually no benefit. Because Purge is limited by disk and CPU. Increasing thread count does not increase disk speed.

▸innodb_purge_batch_size — How Many Rows to Clean Each Time?

ini
[mysqld] innodb_purge_batch_size = 300

Default is 300. Purge cleans 300 old versions each time. In write-heavy systems it can be increased to 1000. But a very large value causes Purge to hold locks for a long time. Between 300 and 1000 is a safe range.

▸innodb_max_purge_lag — Slow Down Writes If Purge Falls Behind

This setting slows down write operations when Purge Lag grows, giving Purge time to catch up. Like insurance.

ini
[mysqld] innodb_max_purge_lag = 100000 innodb_max_purge_lag_delay = 10000

innodb_max_purge_lag = 100000 means, if History List exceeds 100 thousand, add a small delay to write operations. So Purge tries to catch up. This setting exists to protect the system. Do not turn it off.

▸innodb_undo_tablespaces and Truncate

In MySQL 8.0, Undo is kept in separate tablespace files. By default there are 2. As Undo files grow, automatic shrinking can be done.

ini
[mysqld] innodb_undo_tablespaces = 2 innodb_undo_log_truncate = ON innodb_max_undo_log_size = 1073741824

innodb_max_undo_log_size = 1G means, if Undo file exceeds 1 GB, truncate it automatically. This setting prevents Undo from growing infinitely. But during truncate there may be a short slowdown. Check it in a maintenance window.

Step 4: How to Recover If Undo Is Already Bloated?

If Undo is already bloated, changing settings alone is not enough. A recovery plan is needed.

▸Step 4.1: First Close the Blocking Transaction

If the cause of Undo bloat is a long transaction, close it first. Setting changes do not work before the blocking transaction closes.

▸Step 4.2: Wait for Purge to Catch Up

After the blocking transaction closes, Purge automatically starts cleaning old versions. History List Length starts to drop. It does not drop immediately. A 1-million History List can take hours. Wait, monitor.

sql
-- Check every 5 minutes SHOW ENGINE INNODB STATUS\G -- Is History list length dropping?

▸Step 4.3: Optimize the Table — Last Resort

If the table is still bloated and space was not reclaimed even though Purge caught up, rebuild the table.

sql
-- First check size SELECT TABLE_NAME, ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2) AS size_mb FROM information_schema.tables WHERE TABLE_SCHEMA = 'production_db' AND TABLE_NAME = 'orders'; -- Then optimize, in a maintenance window OPTIMIZE TABLE orders;

OPTIMIZE TABLE rebuilds the table and reclaims empty space. But it locks the table. On a large table it can take hours. Do it in a maintenance window. Alternatively, online tools like pt-online-schema-change can be used.

Step 5: Permanent Measures to Keep Purge Healthy

You survived the crisis. Now take 4 permanent measures so it does not repeat.

▸1. Keep Transactions Short

Transactions must not contain:

  • •HTTP calls
  • •External API waiting
  • •User confirmation waiting
  • •Sleep, waiting, long loops

A transaction should only do database work. A transaction longer than 3 seconds is suspicious. A transaction longer than 30 seconds requires an alarm.

▸2. Move Reporting to a Replica

Long reports must not run on the primary. They must run on a read replica. So a report transaction does not block Purge on the primary.

▸3. Set Up a Long Transaction Alarm

sql
-- List transactions longer than 5 minutes SELECT trx_id, trx_started, TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS time_sec, LEFT(trx_query, 120) FROM information_schema.innodb_trx WHERE TIMESTAMPDIFF(SECOND, trx_started, NOW()) > 300 ORDER BY trx_started;

Add this query to the monitoring system as an alarm. If a transaction over 5 minutes exists, the team should be notified.

▸4. Set Up a History List Length Alarm

If History List exceeds 50 thousand, generate an alarm. If it exceeds 100 thousand, generate a critical alarm. Intervene before Purge falls behind.

Comparison with PostgreSQL Vacuum

TopicPostgreSQLMySQL
Cleaning processVacuum / AutovacuumPurge
Old version locationDead rows inside tableUndo Tablespace
Main metricn_dead_tupHistory list length
BlockerLong transactionLong transaction
Manual cleaningVACUUMOPTIMIZE TABLE
Automatic shrinkingAutovacuumUndo Truncate

The two engines speak different languages but the problem is the same. Long transaction stops cleaning, table bloats, system slows down. So the solution is the same in both engines: Keep transactions short, monitor cleaning, set alarms.

Verification: Is Purge Catching Up?

After the change, compare 3 metrics:

  • •Is History List Length dropping?
  • •Is Undo tablespace size stable or shrinking?
  • •Did average time of most expensive queries drop?

Success criteria:

  • •History List below 10 thousand and stable
  • •Undo size not growing
  • •Long transaction count zero
  • •Disk growth speed back to normal

7 Common Mistakes

First mistake: Not monitoring Purge. You cannot manage a system without looking at History List Length.

Second mistake: Running long reports on the primary. Reports must run on a replica.

Third mistake: Making HTTP calls inside a transaction. A transaction is opened for database work.

Fourth mistake: Running OPTIMIZE TABLE immediately when Undo bloats. First close the blocking transaction, wait for Purge to catch up.

Fifth mistake: Turning off innodb_max_purge_lag. This setting is insurance that protects the system.

Sixth mistake: Turning off Undo truncate. Undo grows infinitely.

Seventh mistake: Thinking a Purge problem is a disk problem. Growing disk to solve disk filling hides the root cause. First look at Purge.

Checklist

  • History List Length measured
  • Undo tablespace size measured
  • Long transaction existence checked
  • Owner of blocking transaction identified
  • Purge thread and batch settings checked
  • max_purge_lag setting verified
  • Undo truncate is on checked
  • Blocking transaction closed
  • Purge catching up monitored
  • OPTIMIZE TABLE done in maintenance window if needed
  • Long transaction alarm set up
  • History List alarm set up
  • Reports moved to replica
  • Transaction design rule shared with team

Conclusion

Purge is MySQL's invisible hero. When it works you do not notice it, when it stops everything slows down. History List Length is the pulse of the system. Monitor the pulse, catch long transactions early, give Purge time. If you do not break this loop, Undo will not bloat, table will not bloat, system will not slow down.

Next cluster: MySQL Lock Diagnosis. Because after solving the Purge problem, next is to diagnose lock waits that queue queries.

Related Articles

  • •Pillar: Performance Guide — Performance & Query Optimization
  • •Cluster: [MySQL] Finding the 20 Most Expensive Queries with Performance Schema
  • •Cluster: [MySQL] InnoDB Buffer Pool and Redo Log Tuning
  • •Cluster: [PostgreSQL] Vacuum / Analyze — Autovacuum Tuning
  • •Cluster: [PostgreSQL] Lock Diagnosis — pg_locks + pg_stat_activity in 5 Minutes
  • •Next: [MySQL] Lock Diagnosis — InnoDB Lock Waits
Operational Checklist

Verify each operational safety check before completing the task: