Use this when the Airflow metadata database keeps growing, the grid view is slow, or an upgrade migration will take too long on old history. If the scheduler is already down because the disk is full, free disk space first. This runbook writes data before it frees any.
Warning
By default
airflow db cleancopies purged rows into archive tables in the same database. Running it on a nearly full disk can fill it.
Checks before you start
1. Find the tables that are really big
SELECT relname,
pg_size_pretty(pg_total_relation_size(relid)) AS total,
n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 15;
| What is large | Likely cause | Action |
|---|---|---|
log | Audit events never purged | Clean log first, if audit retention allows |
task_instance, dag_run | Years of runs, or very frequent DAGs | Clean with an agreed retention |
xcom | Large values returned from tasks | Clean, then move large XComs to object storage |
job | Old heartbeat records | Clean; low risk |
_airflow_deleted__* | Archives from earlier cleanups | Export if needed, then drop |
High n_dead_tup on any table | Autovacuum not keeping up | Vacuum before deleting more |
2. Look for long transactions
An old open transaction stops PostgreSQL removing dead rows, so the cleanup appears to do nothing.
SELECT pid, usename, state, now() - xact_start AS xact_age, left(query, 80) AS query
FROM pg_stat_activity
WHERE datname = current_database() AND xact_start IS NOT NULL
ORDER BY xact_start
LIMIT 10;
3. Check your build's options
Table names and flags vary by version. For example, --batch-size and --dag-ids are not in older releases, and Airflow 3 adds tables such as dag_version.
airflow version
airflow db clean --help
airflow db check
4. Agree a retention period
The cutoff must be older than:
- your longest-running task or deferred run
- any window you clear and rerun
- the history needed by
depends_on_past,ExternalTaskSensorand backfills - your audit retention, if the
logtable is your audit record
airflow db clean keeps the latest non-manual run for each DAG so scheduling continues correctly. It doesn't keep the history that your own sensors and backfills expect.
Run the cleanup
1. Take a restorable backup
pg_dump -Fc -h "$PGHOST" -U "$PGUSER" -d airflow -f "airflow_meta_$(date +%Y%m%d).dump"
pg_restore --list "airflow_meta_$(date +%Y%m%d).dump" | head
Listing the dump only proves the file is readable; restore it to a scratch database to prove the backup. On a managed database, take a manual snapshot instead. Keep the Fernet key with your recovery material: encrypted connections and variables are unreadable without it.
2. Dry run
CUTOFF="$(date -u -d '180 days ago' '+%Y-%m-%d 00:00:00+00:00')"
airflow db clean --clean-before-timestamp "$CUTOFF" --dry-run --verbose
Read the row count for each table. Check the dag line carefully: that table is selected on last parsed time, so old, removed DAGs are matched. Name the tables explicitly if you don't want that.
3. Start with the low-risk tables
airflow db clean --clean-before-timestamp "$CUTOFF" \
--tables log,job,import_error \
--batch-size 10000 --verbose
The command asks you to type delete rows. Keep the prompt for manual runs. Drop --batch-size if your version doesn't have it and step the cutoff instead, as shown below.
Tip
Archive tables are only useful if someone will read them. If the backup is verified and audit doesn't need the rows,
--skip-archivedeletes directly and avoids the extra disk use.
4. Clean run history in steps
Work from the oldest data forward. Short transactions are easier on the scheduler than one huge delete.
set -euo pipefail
for DAYS in 720 540 360 270 180; do
CUTOFF="$(date -u -d "${DAYS} days ago" '+%Y-%m-%d 00:00:00+00:00')"
echo "== cleaning before ${CUTOFF}"
airflow db clean --clean-before-timestamp "$CUTOFF" \
--tables xcom,task_instance,dag_run \
--skip-archive --yes --verbose
sleep 60
done
Caution
--yes --skip-archivedeletes with no prompt and no archive copy. Run it only after the dry run and the backup. Deletingdag_runrows also removes their dependent task history.
Run this in a quiet period, and watch scheduler heartbeat and database locks while it runs:
SELECT pid, wait_event_type, pg_blocking_pids(pid) AS blocked_by, left(query, 80) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
If the scheduler is blocked, stop the cleanup. Committed batches stay deleted; rerun later with a smaller step.
5. Check that it worked
By default, a failure on one table, such as a statement timeout, is logged and the command can still exit 0. Check the log for skipped tables. Recent releases have --error-on-cleanup-failure to return a non-zero exit code; use it in automation if --help lists it.
SELECT min(start_date) AS oldest_run, count(*) AS total_runs FROM dag_run;
SELECT min(dttm) AS oldest_event, count(*) AS total_events FROM log;
One old dag_run per inactive DAG is normal, because the last scheduled run is kept.
Remove archive tables
List them with their size:
SELECT c.relname, pg_size_pretty(pg_total_relation_size(c.oid)) AS total
FROM pg_class c
WHERE c.relkind = 'r' AND c.relname LIKE '\_airflow\_deleted\_\_%'
ORDER BY pg_total_relation_size(c.oid) DESC;
Export what you must keep, check the files, then drop:
mkdir -p /backup/airflow-archive
airflow db export-archived --export-format csv --output-path /backup/airflow-archive
ls -lh /backup/airflow-archive
airflow db drop-archived
Caution
airflow db drop-archiveddrops every archive table unless you limit it with--tables. It can't be undone.
Reclaim the space
A delete makes space reusable inside PostgreSQL. It doesn't normally return it to the operating system.
VACUUM (ANALYZE, VERBOSE) task_instance;
VACUUM (ANALYZE, VERBOSE) dag_run;
VACUUM (ANALYZE, VERBOSE) log;
This is enough in most cases: new rows reuse the space and statistics are fresh. Dropped archive tables do return their space.
Warning
VACUUM FULLreturns space but takes anACCESS EXCLUSIVElock and needs room for a second copy of the table. Stop the schedulers, API server or webserver, and triggerers first, and plan an outage.
On MySQL, InnoDB behaves in a similar way: OPTIMIZE TABLE rebuilds the table and needs temporary space.
When it goes wrong
| Symptom | Cause | Fix |
|---|---|---|
| Disk use rises during cleanup | Rows copied to archive tables | Stop, drop archives you no longer need, use --skip-archive |
| Exit code 0 but rows remain | Table error was suppressed | Read the warnings; use --error-on-cleanup-failure if available |
statement timeout | Too much in one transaction | Use --batch-size or step the cutoff |
Foreign key error on dag_version | Rows still referenced by task instances | Clean older task instances first; check your version's release notes |
| Sensor waits for a run that has gone | Cutoff shorter than its lookback | Increase retention and resolve the waiting sensor by hand |
| Table size unchanged | Dead space kept for reuse | Expected; vacuum and reassess |
Prevent it next time
Schedule a small, regular cleanup outside Airflow, so it still works when the scheduler is unhealthy. Example script for a host with the Airflow config:
#!/usr/bin/env bash
# /opt/airflow/bin/db_clean.sh (cron: 30 3 * * 0)
set -euo pipefail
CUTOFF="$(date -u -d '180 days ago' '+%Y-%m-%d 00:00:00+00:00')"
airflow db clean --clean-before-timestamp "$CUTOFF" \
--tables log,job,import_error,xcom,task_instance,dag_run \
--skip-archive --yes --verbose
- Alert when the job has not succeeded for two weeks and when database disk passes your threshold.
- In Airflow 3, don't put the cleanup in a task that opens a metadata session. Task code no longer has direct database access.
- On a managed service, use the vendor's documented cleanup method; CLI access is often limited.
- Task log files are separate. Set a lifecycle rule on the remote log bucket.
- Run a cleanup before every Airflow upgrade. Smaller tables mean shorter migrations.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get