Moving Airflow Sensors to Async Execution

Our nightly batch sometimes detected finished jobs over an hour late, because 2,500 waiting sensors competed for 100 Worker slots. I moved them onto Airflow's async Triggerer in a staged rollout, so waiting no longer takes a Worker slot.
BeforeAfter
Worker slots held by waiting sensors100 (always full)0 (used only to start and resume)
Scheduling delays (1 hour+)3–4 per month0 (June 3 – November 2026)
Compute task slots available~100~200

Airflow 2.6.2, LocalExecutor (Scheduler = Worker), parallelism 200, Triggerer ×3 (capacity 1,000 each). 3,500 custom sensors, about 2,500 of which run during the nightly batch. They detect task completion from the Airflow metadata DB ("Meta DB") and Sqoop completion from an in-house Sqoop status table.


Problem

100 of the 200 Worker slots were reserved for sensors. In reschedule mode a sensor releases its slot between pokes, but with 2,500 sensors behind 100 slots the pool was always full. This caused two problems:

Sensor log — 1 hour+ scheduling gap
2026-05-04: rescheduled at 01:10:31, next run at 02:18:38.
Sqoop actual finish time
Sqoop finished at 01:16:43, detected an hour later.
AlternativeWhy not
More Worker slotsSpends Worker processes on tasks that only wait.
CeleryExecutorTakes load off the scheduler, but every poke still takes a Worker slot.

A sensor only waits, so it should not need a Worker at all. The Triggerer runs waiting logic as asyncio coroutines, so one process holds on the order of a thousand waits (capacity 1,000 each here): self.defer() releases the slot, the wait runs in a trigger's run(), and the task returns to a Worker only to finish.


Stabilizing the Triggerer

The Triggerer runs coroutines on an async thread, but all DB work and the heartbeat share one synchronous main loop (airflow/jobs/triggerer_job_runner.py):

[Triggerer Process] ├─ async thread: runs each trigger's run() coroutine → TriggerEvent into a deque └─ main thread: _run_trigger_loop() → DB reads/writes, events, heartbeat
def _run_trigger_loop(self):            # main thread, synchronous
    while not self.trigger_runner.stop:
        Trigger.clean_unused()
        self.load_triggers()             # → Trigger.bulk_fetch()
        self.handle_events()
        self.handle_failed_triggers()
        perform_heartbeat(self.job, ...)
        time.sleep(1)

Heartbeat blocked by bulk_fetch. The Triggerer stopped heartbeating while its coroutines kept running. SHOW PROCESSLIST on the Meta DB showed one query still running at 205s when I stopped watching, which I traced to Trigger.bulk_fetch. In 2.6.2, TaskInstance.dag_run is declared model-wide as lazy="joined", innerjoin=True, so this query joins dag_run even though it never uses it. Because load_triggers() runs before perform_heartbeat in that loop, it pushed the last heartbeat almost 10 minutes back, far past the 30 seconds after which other Triggerers take over its triggers. Applying lazyload to that join fixed it.

Tasks stuck in deferred. Some tasks stayed deferred with triggers assigned but no coroutine running; I could not reproduce the cause. I added a liveness check that restarts the process when assigned triggers exist but nothing is running or queued, and required 5 consecutive hits to avoid false positives while triggers were still registering.


Reducing DB Load First

Once off the 100-slot pool, all 2,500 sensors would query the Sqoop status table freely. Two changes before migrating:

DB CPU Before
Before caching: peaks at 70%
DB CPU After
After caching: peaks around 10%

Migration

Added a trigger that runs the existing poke logic as a coroutine, with the old sync path kept behind a flag (pseudocode):

class CustomTaskSensor(BaseSensorOperator):
    def execute(self, context):
        if not self.use_async:
            return super().execute(context)          # original reschedule path
        self.defer(
            trigger=CustomTaskCompletionTrigger(
                self.target_task_id, self.poke_interval
            ),
            method_name="on_complete",
        )

class CustomTaskCompletionTrigger(BaseTrigger):
    async def run(self):
        try:
            while not await self._check_task_completion():
                await asyncio.sleep(self.poke_interval)
            yield TriggerEvent({"status": "completed"})
        except Exception as e:
            yield TriggerEvent({"status": "error", "message": str(e)})

Test cluster. A separate cluster with the same setup read the production Meta DB and Sqoop status table (read-only), with every non-sensor task replaced by EmptyOperator. From May it ran alongside the real nightly batch; I compared detections with the sync sensors and watched for event-loop blocking, memory leaks, and missed triggers.

Timeout. In reschedule mode each poke is a new execution, so execution_timeout restarts every time and never fired. A deferred task gets trigger_timeout = start_date + execution_timeout once, with start_date kept across resumes, so the clock runs from the first start. Sensors waiting for hours timed out while working correctly. (The sensor's own timeout was not the issue: it counts from the first TaskReschedule of the try, so it behaves the same in both modes.) I removed execution_timeout from deferred sensors and rely on a separate SLA check for stuck ones.

Rollout. A sensor went async when its DAG hash mod 100 was below a target percentage: 25 → 50 → 75 → 100%, with 0 as instant fallback to reschedule mode. Completed June 3, 2026, after which the sensor pool's 100-slot reservation was lifted. Reviewed with my team and the DBA team throughout.

Logs. Triggerer logs only appeared after a task finished, because the log URL used the Triggerer pod's name, which DNS could not resolve for a Deployment. Setting hostname_callable to airflow.utils.net:get_host_ip_address registers the pod IP instead and restored live logs.


Upstream

Airflow 3 split the Triggerer into a supervisor and a subprocess. Reading it, I found another path to the stuck-deferred symptom: the supervisor can keep a trigger in running_triggers while nothing runs it in the subprocess. My patch compares the trigger ids the supervisor tracks against the ones the subprocess actually runs each sync cycle and drops only the stranded ids so they are rebuilt, instead of restarting the whole Triggerer, with a triggers.state_mismatch metric and tests (apache/airflow#68792, merged for Airflow 3.5.0).

Apache Airflow 2.6.2 / Python asyncio / Triggerer