xxntti3n opened a new issue, #77363:
URL: https://github.com/apache/airflow/issues/77363

   ### Under which category would you file this issue?
   
   Providers
   
   ### Apache Airflow version
   
   3.4.0
   
   ### What happened and how to reproduce it?
   
   ### What happened
   
   Every running task sends a heartbeat every `[workers] min_heartbeat_interval`
   (default 5 s). The execution API route `ti_heartbeat`
   
(`airflow-core/src/airflow/api_fastapi/execution_api/routes/task_instances.py`)
   and its in-process twin `TaskInstance.update_heartbeat`
   (`airflow-core/src/airflow/models/taskinstance.py`) execute a real UPDATE:
   
   ```python
   update(TI).where(...).values(last_heartbeat_at=timezone.utcnow())
   ```
   
   `task_instance.__table_args__` contains
   `Index("ti_heartbeat", last_heartbeat_at)`
   (`airflow-core/src/airflow/models/taskinstance.py`).
   
   Because an indexed column changes, that UPDATE can never be HOT. PostgreSQL 
must
   insert a new tuple version *and* a new index entry into **every index on the
   table** — 13 in 3.4 (10 plain, 2 partial, PK + 2 unique), including
   `ti_heartbeat` itself. One heartbeat = 1 heap write + 13 index writes.
   
   The index was inherited mechanically by migration `d8cd3297971e` (0045), 
which
   dropped `job_id`/`ti_job_id` and created `ti_heartbeat` in the same change 
that
   removed `LocalTaskJob`. In Airflow 2.10 the equivalent zombie-scan predicate 
ran
   against the small `job` table
   (`airflow/jobs/scheduler_job_runner.py`, `Job.latest_heartbeat < 
limit_dttm`); in
   Airflow 3 it runs against `task_instance`
   (`TI.last_heartbeat_at < limit_dttm`).
   
   On a `task_instance` table with millions of historical rows,
   `last_heartbeat_at < now() - 300s` matches almost the whole table, so no 
plan uses
   a plain single-column index on it. The only query that could use it already 
carries
   `.with_hint(TI, "USE INDEX (ti_state)", dialect_name="mysql")`
   (`airflow-core/src/airflow/jobs/scheduler_job_runner.py`).
   
   Net effect: the index is written on every heartbeat and read by no query 
plan.
   
   ### How to reproduce
   
   Any Airflow 3.x deployment with a PostgreSQL metadata database. No DAG 
complexity
   is needed — one long-running task is enough.
   
   **1. Run a task that stays running for a few minutes.**
   
   ```python
   from airflow.sdk import dag, task
   import time
   
   @dag()
   def heartbeat_repro():
       @task
       def sleepy():
           time.sleep(300)
   
       sleepy()
   
   heartbeat_repro()
   ```
   
   **2. While it is RUNNING, sample the update counters, wait 60 s, sample 
again.**
   
   ```sql
   SELECT n_tup_upd, n_tup_hot_upd, n_dead_tup
   FROM pg_stat_user_tables WHERE relname = 'task_instance';
   ```
   
   Observed with the default 5 s interval and a single running task:
   
   | | n_tup_upd | n_tup_hot_upd |
   | --- | --- | --- |
   | t0 | 100 | 0 |
   | t0 + 60 s | 112 | 0 |
   
   `n_tup_upd` climbs by ~12/min while `n_tup_hot_upd` stays at **0** — every
   heartbeat is a non-HOT update, so all 13 indexes receive a new entry.
   
   **3. Confirm no query plan uses `ti_heartbeat`.**
   
   ```sql
   EXPLAIN (COSTS OFF)
   SELECT id FROM task_instance
   WHERE state IN ('running', 'restarting')
     AND last_heartbeat_at < now() - interval '300 seconds';
   ```
   
   This is the shape of `_find_task_instances_without_heartbeats`. Output is
   `Index Scan using ti_state`, never `ti_heartbeat`.
   
   **4. Counterfactual — drop the index and repeat step 2** (test environment 
only):
   
   ```sql
   DROP INDEX CONCURRENTLY ti_heartbeat;
   ```
   
   `n_tup_upd` keeps climbing by ~12/min, but now `n_tup_hot_upd` climbs with 
it.
   That isolates the index as the cause rather than the heartbeat itself.
   
   Restore afterwards:
   
   ```sql
   CREATE INDEX CONCURRENTLY ti_heartbeat ON task_instance (last_heartbeat_at);
   ```
   
   **5. Optional — observe the cost at scale.** With ~30 concurrent tasks the
   statement dominates the workload: `UPDATE task_instance SET 
last_heartbeat_at`
   accounts for 286,623 s of execution time over 24 h (**~64 % of all SQL 
time**) on
   a 2 vCPU / 4 GB Cloud SQL instance pinned at 100 % CPU, while `ti_heartbeat` 
is
   1078 MB with 810 `idx_scan`/24h versus 48,213 for `ti_state`. Full figures in
   "Anything else".
   
   ### What you think should happen instead?
   
   Two independent changes. Either reduces the load; together they remove the 
write
   amplification entirely.
   
   1. **Threshold-gate the heartbeat write** so a healthy beat does not issue an
      UPDATE at all, while `task_instance_heartbeat_timeout` and therefore the
      failure budget stay unchanged.
   
   2. **Drop `ti_heartbeat`** — it is written on every heartbeat and used by no 
query
      plan — and set `fillfactor = 90` on `task_instance` so the 
now-HOT-eligible
      update actually stays HOT.
   
   The heartbeat write path should not touch 13 indexes per beat.
   
   ### Operating System
   
   Linux
   
   ### Deployment
   
   Official Apache Airflow Helm Chart
   
   ### Apache Airflow Provider(s)
   
   _No response_
   
   ### Versions of Apache Airflow Providers
   
   _No response_
   
   ### Official Helm Chart version
   
   Not Applicable
   
   ### Kubernetes Version
   
   _No response_
   
   ### Helm Chart configuration
   
   Custom values file from a forked chart. Settings relevant to this report:
   
   - `[workers] min_heartbeat_interval` — left at the default (5)
   - `[workers] max_failed_heartbeats` — left at the default (30)
   - `[scheduler] task_instance_heartbeat_timeout` — 300
   - `[scheduler] task_instance_heartbeat_timeout_detection_interval` — default 
(10)
   - executors: KubernetesExecutor + CeleryExecutor
   - metadata DB: Cloud SQL for PostgreSQL, `db-custom-2-4096`
   
   ### Docker Image customizations
   
   _No response_
   
   ### Anything else?
   
   ### Measured impact
   
   PostgreSQL on Google Cloud SQL, `db-custom-2-4096`, metadata DB only, ~29
   concurrent task instances, Airflow 3.4.0.
   
   **1. Write amplification is the dominant SQL cost.**
   
   Cloud Monitoring `insights/perquery/execution_time`, 24 h window:
   
   | statement | total seconds / 24 h |
   | --- | --- |
   | `UPDATE task_instance SET last_heartbeat_at …` | 286,623 |
   | `DELETE FROM rtif_v2 …` | 30,329 |
   | `ceil(COUNT(*))` (KEDA scaler) | 11,102 |
   | `INSERT INTO rtif_v2 …` | 10,150 |
   
   ≈64 % of all SQL execution time, on an instance pinned at 100 % CPU.
   
   **2. The planner does not use `ti_heartbeat`.**
   
   `pg_stat_user_indexes` on `task_instance`, 24 h:
   
   | index | size | idx_scan |
   | --- | --- | --- |
   | `ti_state` | 28 MB | 48,213 |
   | `ti_dag_state` | 35 MB | 359,219 |
   | `ti_dag_run` | 193 MB | 322,369 |
   | `ti_state_lkp` | 664 MB | 2 |
   | **`ti_heartbeat`** | **1078 MB** | **810** |
   
   `task_instance_heartbeat_timeout_detection_interval` defaults to 10 s, so the
   zombie scan runs at least 8,640 times/day. `ti_heartbeat` records 810 scans —
   these are autovacuum index passes, not query plans. Real executions land on
   `ti_state`, which is exactly the predicate set the query needs.
   
   **3. The index is heavily bloated; the heap is not.**
   
   Estimated from size arithmetic (a healthy btree entry for a single 
`timestamptz`
   is ~20 B, ~366 entries/page after fillfactor): a clean `ti_heartbeat` 
covering
   2,329,384 rows should be ~52 MB. It is 1078 MB, i.e. ~20x, holding on the 
order of
   48 million dead entries — consistent with ~500k beats/day never being 
reclaimed
   since the 3.x upgrade.
   
   `pgstattuple` is not available on Cloud SQL, so this is an estimate rather 
than an
   exact `dead_tuple_count`.
   
   The heap, by contrast, is 2.05 GiB (`relpages = 268676`, `reltuples = 
2329384`)
   with only ~27 % dead space — a normal figure for an append-heavy table. **The
   bloat is in the index, not in the heap**, which means `VACUUM` alone does not
   address it; only `REINDEX` or dropping does.
   
   ### How other job queues avoid this
   
   | project | heartbeat strategy |
   | --- | --- |
   | River (Go) | no per-job heartbeat; time-based rescue |
   | Oban (Elixir) | no per-job heartbeat |
   | pgqueuer | heartbeat on an **unindexed** column |
   | pg-boss | heartbeat on an **unindexed** column |
   | Airflow 3.4 | heartbeat on an **indexed** column, every 5 s |
   
   Three of four peers deliberately avoid the pattern. This is a design choice 
with a
   known alternative, not an inherent trade-off.
   
   Reference: TaskQ hit the identical MVCC problem and documented it —
   https://github.com/AZX-PBC-OSS/TaskQ/issues/227
   ("lease renewal is a non-HOT update on two indexed columns per running row 
per
   beat").
   
   ### Proposed change, in detail
   
   **Step 1 — threshold-gate the heartbeat write.**
   
   ```python
   # api_fastapi/execution_api/routes/task_instances.py — ti_heartbeat()
   timeout_secs = conf.getint("scheduler", "task_instance_heartbeat_timeout")  
# 300
   threshold = timeout_secs // 2                                               
# 150
   
   update(TI)
   .where(
       TI.id == task_instance_id,
       TI.state == TaskInstanceState.RUNNING,
       TI.hostname == ti_payload.hostname,
       TI.pid == ti_payload.pid,
       TI.last_heartbeat_at < timezone.utcnow() - timedelta(seconds=threshold),
   )
   .values(last_heartbeat_at=timezone.utcnow())
   ```
   
   1 write per 150 s instead of 1 per 5 s → **30x fewer writes**, with no 
change to
   `task_instance_heartbeat_timeout`, so no task is ever falsely declared dead.
   
   Implementation caveat: with the current fast-path logic a `rowcount == 0` is
   treated as "fast path missed" and falls through to the `SELECT … FOR UPDATE`
   branch, which would be *more* expensive than today. The cheap shape is a
   lightweight `SELECT last_heartbeat_at` followed by a conditional `UPDATE` — 
reads
   create no dead tuples and no WAL.
   
   **Step 2 — remove the index and leave room for HOT.**
   
   ```python
   # models/taskinstance.py, __table_args__
   -        Index("ti_heartbeat", last_heartbeat_at),
   ```
   
   plus a migration `drop_index("ti_heartbeat")`, and removal of the 
now-pointless
   `USE INDEX (ti_state)` hint in `scheduler_job_runner.py`.
   
   Dropping alone makes the update HOT-eligible but not necessarily HOT: HOT 
also
   requires free space on the same page, and `task_instance` runs at the default
   `fillfactor = 100`. Airflow currently sets `fillfactor` on no table at all, 
so this
   would be new:
   
   ```sql
   ALTER TABLE task_instance SET (fillfactor = 90);
   ```
   
   **Risk assessment for step 2.** The only consumer is
   `_find_task_instances_without_heartbeats`, which already resolves to 
`ti_state`.
   `ti_state` holds every row currently in `RUNNING`/`RESTARTING` — i.e. 
exactly the
   concurrent task count — so it stays small and selective. The caveat is 
deployments
   carrying many orphaned `RUNNING` rows (common with `databaseCleanup` 
disabled),
   where `ti_state` becomes less selective; those should be cleaned first.
   
   ### Interim workarounds
   
   None of these require a code change.
   
   1. Raise `[workers] min_heartbeat_interval` (5 → 15) and lower
      `[workers] max_failed_heartbeats` (30 → 10), keeping the
      `interval x max_failed` failure budget constant at 150 s.
   2. `DROP INDEX CONCURRENTLY task_instance.ti_heartbeat;` after confirming the
      `EXPLAIN` above shows `ti_state`.
   3. `REINDEX INDEX CONCURRENTLY` on the other bloated indexes, and
      `ALTER TABLE task_instance SET (fillfactor = 90)`.
   
   Note that (2) has to be repeated for any environment created from scratch, 
because
   migration 0045 recreates the index.
   
   ### Deployment note
   
   This is not Cloud Composer. The deployment is self-managed Airflow 3.4.0 on 
GKE
   using the Apache Helm chart (forked), with a Cloud SQL for PostgreSQL 
metadata
   database. The image is a custom build, but every file cited above is 
unmodified
   upstream code at tag 3.4.0. The measurements come from 
`pg_stat_user_indexes`,
   `pg_stat_user_tables` and Cloud Monitoring on that metadata instance.
   
   ### Are you willing to submit PR?
   
   - [ ] Yes I am willing to submit a PR!
   
   ### Code of Conduct
   
   - [x] I agree to follow this project's [Code of 
Conduct](https://github.com/apache/airflow/blob/main/CODE_OF_CONDUCT.md)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to