Skip to content

Cleaning up wp_postmeta bloat at scale without locking the site

Orphaned postmeta from deactivated plugins can outweigh wp_posts ten to one. The safe path is primary-key chunked deletes that respect replication lag.

A 12,000-post WooCommerce site has 8.4 million rows in wp_postmeta. The shop owner mentions the database has been slow to back up — mysqldump now takes 38 minutes when it used to take six. You count rows per meta_key and discover that a SEO plugin removed three years ago left 4.1 million orphaned _yoast_old_xyz rows. A WooCommerce extension that processes refunds has 1.2 million _refund_pending_lock rows with no expiry. Half of wp_postmeta is dead weight.

What’s happening

wp_postmeta has no built-in garbage collector. When a plugin is deactivated or uninstalled, its postmeta rows stay unless the plugin’s uninstall hook removed them explicitly — which most plugins do not. Worse, plugins that get updated through major versions sometimes change their meta_key scheme and leave the old keys behind.

Once wp_postmeta grows past 5–10 million rows you start paying for it in three places:

  • meta_query slowness. WP_Query joins wp_postmeta for every meta_query filter. With orphaned rows inflating the table, the join hits more pages even when the actual matches stay small.
  • Backup duration. mysqldump walks the whole table, and so do logical backups via JetBackup or Duplicator. Bigger table, longer dump, longer restore.
  • Replication lag. Any batched cleanup you do later replicates row-by-row, and a naive DELETE FROM wp_postmeta WHERE meta_key='dead_key' can lock the table for minutes on the primary and saturate the replica behind it.

The naive cleanup approach — a single big DELETE — is exactly what fails in production:

-- DO NOT DO THIS on a live site
DELETE FROM wp_postmeta WHERE meta_key='_yoast_old_xyz';

This takes a long-running row lock on every matching row, blocks writes against wp_postmeta (every post save touches it), generates a single massive binlog event, and replication catches up minutes later. We have seen this take a managed WooCommerce site offline mid-checkout.

The correct approach is primary-key chunked deletes that hold short transactions and respect replica lag between batches.

How to verify

Count rows by meta_key to find the bloat candidates:

wp db query "SELECT meta_key, COUNT(*) AS n FROM wp_postmeta GROUP BY meta_key ORDER BY n DESC LIMIT 40"

Anything with more than 100,000 rows whose corresponding plugin is no longer installed is a candidate. Confirm orphaned status:

wp plugin list --format=csv | cut -d, -f1

Match the meta_key prefix against the active plugin slugs. If a meta_key like _acme_inventory_state survives but acme-inventory is gone from the plugin list, those rows are orphans.

Also catch orphaned rows whose post_id no longer exists in wp_posts (posts deleted but meta survived):

SELECT COUNT(*) FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;

On a healthy site this should be zero or very close. Numbers in the millions mean orphaned meta from deleted posts (common with WooCommerce orders auto-deleted by retention rules).

Check replication topology before starting any cleanup:

mysql -e "SHOW REPLICA STATUS\G" | grep -E "Seconds_Behind|Replica_(IO|SQL)_Running"

If you are on a replica-backed cluster, the cleanup script must monitor lag.

The fix

Use a chunked delete loop that walks the primary key, deletes in small batches, and pauses if replication lag grows. Save this as postmeta-cleanup.sh:

#!/bin/bash
# Stack Harbor — wp_postmeta chunked cleanup
# Deletes orphaned postmeta rows in batches of 5,000 with replica-lag awareness.

set -euo pipefail

META_KEY="${1:?usage: $0 <meta_key> [batch_size] [max_lag_seconds]}"
BATCH="${2:-5000}"
MAX_LAG="${3:-10}"
WP_DB_HOST="$(wp config get DB_HOST)"
WP_DB_NAME="$(wp config get DB_NAME)"
WP_DB_USER="$(wp config get DB_USER)"
WP_DB_PASS="$(wp config get DB_PASSWORD)"

mysql_q() {
  mysql --defaults-extra-file=<(printf "[client]\nhost=%s\nuser=%s\npassword=%s\n" "$WP_DB_HOST" "$WP_DB_USER" "$WP_DB_PASS") \
    "$WP_DB_NAME" -N -e "$1"
}

# Confirm row count first
TOTAL=$(mysql_q "SELECT COUNT(*) FROM wp_postmeta WHERE meta_key='$META_KEY'")
echo "About to delete $TOTAL rows where meta_key='$META_KEY' in batches of $BATCH."
read -p "Proceed? (yes/N) " ack
[[ "$ack" == "yes" ]] || { echo "Aborted."; exit 1; }

DELETED=0
while :; do
  # Find the next batch by primary key
  IDS=$(mysql_q "SELECT meta_id FROM wp_postmeta WHERE meta_key='$META_KEY' ORDER BY meta_id LIMIT $BATCH")
  [[ -z "$IDS" ]] && break

  ID_LIST=$(echo "$IDS" | tr '\n' ',' | sed 's/,$//')
  mysql_q "DELETE FROM wp_postmeta WHERE meta_id IN ($ID_LIST)"
  DELETED=$((DELETED + $(echo "$IDS" | wc -l)))
  echo "Deleted $DELETED / $TOTAL"

  # Wait for replica to catch up before next batch
  while :; do
    LAG=$(mysql_q "SHOW REPLICA STATUS" 2>/dev/null | awk '/Seconds_Behind/ {print $2}' || echo 0)
    [[ "$LAG" == "NULL" || -z "$LAG" ]] && break
    (( LAG <= MAX_LAG )) && break
    echo "Replica lag $LAG seconds, sleeping 5..."
    sleep 5
  done

  sleep 0.2  # let other writes through
done

echo "Done. Deleted $DELETED rows."

Run it once per orphaned meta_key:

chmod +x postmeta-cleanup.sh
./postmeta-cleanup.sh _yoast_old_xyz 5000 10
./postmeta-cleanup.sh _refund_pending_lock 5000 10

For orphaned rows whose post_id no longer exists:

-- Run in a loop with LIMIT, same chunking principle
DELETE pm FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL
LIMIT 5000;

If you have percona-toolkit installed, pt-archiver does the same thing with better lag handling:

pt-archiver --source h=localhost,D=wp,t=wp_postmeta \
  --where "meta_key='_yoast_old_xyz'" \
  --purge --limit 5000 --commit-each --sleep 0.2 \
  --check-replica-lag h=replica.example.com \
  --max-lag 10

After the cleanup, run OPTIMIZE TABLE wp_postmeta during a maintenance window. InnoDB does not return freed pages to the OS until the table is rebuilt — without OPTIMIZE the table size on disk stays the same and your backup duration does not improve.


Stack Harbor handles wp_postmeta cleanups as part of the WordPress estate work under enterprise WordPress hosting, and the chunked-delete tooling is baked into our environment management runbooks. If your postmeta has been growing untouched for years, we will plan the cleanup.