Skip to main content
In addition to storing configurations about your Airflow environment, the Airflow metadata database stores data about past and present task runs. Airflow never automatically removes metadata, so the longer you use it, the more task run data is stored in your metadata DB. Over a long enough time, this can result in a bloated metadata DB, which can affect performance across your Airflow environment. When a table in the metadata DB is larger than 50GiB, you might start to experience degraded scheduler performance. This can result in:
  • Slow task scheduling
  • Slow dag parsing
  • Gunicorn timing out when using the Celery executor
  • Slower Airflow UI load times
The following tables in the database are at risk of becoming too large over time:
  • dag_run
  • job
  • log
  • rendered_task_instance_fields
  • task_instance
  • task_state_store
  • xcom
To keep your Airflow environment running at optimal performance, you can clean the metadata DB using the Airflow CLI airflow db clean command. This command was created as a way to safely clean up your metadata DB without querying it directly. In Airflow 3, this command can’t be called from a Dag because tasks can no longer directly access the metadata DB. Instead you can expose Airflow’s utility function used by the command through an HTTP API using an Airflow Plugin. This tutorial describes how to implement the cleanup Dag and corresponding plugin in Airflow so that you can clean your database using the command directly from the Airflow UI.
Even when using Airflow’s DB clean utilities, deleting data from the metadata database can destroy important data. Read the Warnings section carefully before implementing this tutorial Dag in any production Airflow environment.

Warnings

Deleting data from the metadata database can be an extremely destructive action. If you delete data that future task runs depend on, it’s difficult to restore the database to its previous state without interrupting your data pipelines. Before implementing the Dag in this tutorial, consider the following:
  • ⚠️ When specifying the clean_before_timestamp value, use as old a date as possible. The older the deleted data, the less likely it is to affect your currently running Dags.
  • ⚠️ For task_state_store, the cutoff applies to the expires_at column set at write time (controlled by [state_store] default_retention_days), not the row creation date. Rows written with NEVER_EXPIRE (expires_at=NULL) are never deleted regardless of the cutoff.
  • ⚠️ The Dag in this tutorial isn’t designed to keep archived tables. It drops the archived tables it created in the cleanup process by default using the skip_archive=True argument, and doesn’t maintain any history. If the task fails (for example if it runs for longer than five minutes), the archive tables aren’t cleared. By calling drop_archived_tables in the second task of the Dag, we ensure all archive tables are dropped even in the event of the first task failing.

Prerequisites

  • An Airflow project
    This Dag has been designed and optimized for Airflow environments running on Astro. Consider adjusting the parameters and code if you’re running the Dag in any other type of Airflow environment.
  • The HTTP Airflow provider installed

Step 1: Create your Dag and plugin

  1. In your dags folder, create a file called db_cleanup.py.
  2. Copy the following code into the Dag file.
    Rather than running on a schedule, this Dag is triggered manually by default and includes params so that you’re in full control over how you clean the metadata DB. It includes three tasks:
    • get_chunked_timestamps: creates a list of timestamps to process in batches.
    • db_cleanup: calls the run_cleanup utility.
    • clean_archive_tables: calls the drop_archived_tables utility.
    These three tasks run with params you specify at runtime. The params let you specify:
    • clean_before_timestamp: What age of data to delete. Any data that was created before the specified time will be deleted. The default is to delete all data older than 90 days.
    • tables: Which tables to delete data from. By default all tables supported by the DB cleanup utilities are included except for the dag and dag_version table.
    • dry_run: Whether to run the cleanup as a dry run, meaning that no data is deleted. The dag will instead return the SQL that would be executed based on other parameters you have specified. The default is to run the deletion without a dry run.
    • batch_size_days: What batch size to use in order to cleanup data in batches.
    • http_conn_id: Which HTTP connection to use for calling the API exposing the DB cleanup utilities.
  3. In your plugins folder, create a file called db_cleanup.py.
  4. Copy the following code into the plugin file.
    The plugin uses requires_access_configuration("GET") from Airflow’s core API security module to restrict access to users with Airflow configuration access, which is equivalent to admin access. It exposes the following API endpoints:
    • GET /db_cleanup/api/info: Provide a list of tables with their corresponding sizes and row count estimates. This endpoint isn’t used by the Dag, but can be useful to get insights into table sizes.
    • GET /db_cleanup/api/oldest_timestamp: Return the oldest timestamp for the tables to cleanup used for calculating batches.
    • DELETE /db_cleanup/api/records: Call the run_cleanup utility.
    • DELETE /db_cleanup/api/archived: Call the drop_archived_tables utility.
Because the DB cleanup utilities are running on the api-server, the corresponding logs will show up in the api-server logs.
The batch_size query parameter on the DELETE /db_cleanup/api/records endpoint is forwarded to Airflow’s run_cleanup utility, which only accepts batch_size in Airflow 3.1 and later. When using the API endpoint directly with Airflow 3.0, omit the parameter, otherwise the request fails with TypeError: run_cleanup() got an unexpected keyword argument 'batch_size'. The db_cleanup Dag doesn’t pass batch_size and is compatible with Airflow 3.0 and 3.1+.

Step 2: Configure an HTTP connection

Add an HTTP connection used for calling the API endpoints.
  • host: Set this to the deployment’s URL. For example on Astro this would look like something like https://cmls9yey09fpw01ncvse41m4n.4n.astronomer.run/dse41m4n. When running locally in astro dev this should be set to http://api-server:8080.
  • extra: If needed, set the authorization header. On Astro with an API token this would look something like {"Authorization": "Bearer mytoken1234...abc1234"}.

Step 3: Practice running the Dag

In this step, run the Dag in a local Airflow environment to practice the workflow for cleaning metadata DB records. If you completed Step 1 in your production environment, you will need to repeat it here before starting your local Airflow project. Typically in a fresh local Airflow environment there isn’t much to clean up. When completing this process in a production environment which has been running for a while, there are more historic records to cleanup.
  1. Run astro dev start in your Astro project to start Airflow, then open the Airflow UI at localhost:8080.
  2. Ensure the Airflow connection http_default with host http://api-server:8080 is set.
    Instead of creating an Airflow connection, you can also define it as an environment variable AIRFLOW_CONN_HTTP_DEFAULT=http://api-server:8080 in your local .env file.
  3. In the Airflow UI, run the astronomer_db_cleanup Dag by clicking the play button and configure the following params:
    • dry_run is enabled
    • Choose an appropriate cutoff date for clean_before_timestamp
In some older 3.0 versions a bug causes malformed timestamps when using date-time param fields in the Airflow UI. If you are on Airflow 3.0 and encounter an error like ValueError: Invalid isoformat string: '2026-03-06T13:19:00.000Z:00+00:00' set your clean_before_timestamp directly in the Configuration JSON under Advanced Options instead of using the Run Parameter.
  1. Click Trigger.
  2. In a local terminal run astro dev logs --api-server -f to show the api-server logs.
  3. Check that the run_cleanup utility completed successfully. Note that if you created a new Astro project for this tutorial, the run won’t show much data to be deleted.
You can now use this Dag to periodically clean data from the Airflow metadata DB as needed.