Skip to content
7 min readintermediate

Airflow Triggerer: why waiting shouldn't cost a worker

How deferrable operators and the Triggerer let Airflow wait on thousands of external events without tying up worker slots, and where it breaks.

  • Data Platform
  • ML Platform
  • Apache Airflow · triggerer

The problem

It’s 2 a.m. and your nightly pipeline has 300 tasks. Forty of them are waiting: for a partner’s file to land in S3, for a Spark job on EMR to finish, for an upstream DAG in another team’s Airflow. None of them is doing any work, but every one of them holds a worker slot.

Your Celery workers have 32 slots in total. The waiting tasks fill every slot, the tasks that actually transform data sit in queued, and the pipeline that normally finishes at 5 a.m. finishes at 9. Nothing failed, but everything is late.

This is the problem the Triggerer solves. Waiting is cheap if you do it in the right place, and a worker slot (a whole process sitting idle) is the wrong place.

Compare

Each waiting task runs a while not done: sleep(60) loop inside a worker process. Every wait = one occupied slot, each one a full Python process mostly sleeping.

The task hands its wait to the Triggerer and frees its slot. One Triggerer process runs hundreds of waits as coroutines on a single asyncio event loop. Real work gets the slots.

Didn’t mode="reschedule" already fix this?

Partly. A sensor in reschedule mode doesn’t hold its slot between checks: it checks once, and if the condition isn’t met it exits with state up_for_reschedule, and the scheduler runs it again later. Slots are freed, but every check is a full task run: the scheduler queues it, a worker starts a process, the DAG file is parsed, the task’s code runs once, and the process exits. For a check every 30 seconds across hundreds of sensors, that adds a lot of load on the scheduler and the database.

Deferral gives you the slot savings of reschedule and cheap, frequent checks.

Real-world analogy

Architecture

The Triggerer is a separate Airflow component (airflow triggerer), alongside the scheduler, the workers and the webserver/API server. It talks to everything else through the metadata database.

Where the Triggerer sitsThe scheduler sends tasks to workers. A worker defers a task by writing a trigger to the metadata DB. The Triggerer runs triggers and writes events back. The scheduler then reschedules the task.

queue task

defer: write trigger row,
state = deferred

load assigned triggers

event fired:
state = scheduled

Scheduler

Worker slot

Metadata DB

Triggerer
asyncio loop

Where the Triggerer sitsThe scheduler sends tasks to workers. A worker defers a task by writing a trigger to the metadata DB. The Triggerer runs triggers and writes events back. The scheduler then reschedules the task.

queue task

defer: write trigger row,
state = deferred

load assigned triggers

event fired:
state = scheduled

Scheduler

Worker slot

Metadata DB

Triggerer
asyncio loop

The scheduler sends tasks to workers. A worker defers a task by writing a trigger to the metadata DB. The Triggerer runs triggers and writes events back. The scheduler then reschedules the task.

Where the Triggerer sits

Three ideas make it work:

  1. A task can pause itself. Inside execute(), a deferrable operator calls self.defer(trigger=..., method_name="execute_complete"). This raises a special TaskDeferred exception, Airflow serializes the trigger (its class path and keyword arguments) into the trigger table, sets the task to the deferred state, and the worker slot is released.
  2. Triggers are small async coroutines. A trigger is a class with an async def run() that yields a TriggerEvent when the condition is met. Because it’s async, one process can run hundreds or thousands of them concurrently on a single event loop. While one trigger awaits a network response, the others keep running.
  3. Resumption is a fresh start on a worker. When the event fires, the task goes back to scheduled, gets picked up by a worker, and Airflow calls the method you named (execute_complete) with the event payload. Local variables from the first run are gone; anything you need must travel in the trigger’s event or the method’s kwargs.

A minimal deferrable sensor looks like this:

from datetime import timedelta

from airflow.sensors.base import BaseSensorOperator
from airflow.triggers.temporal import TimeDeltaTrigger


class WaitOneHour(BaseSensorOperator):
    def execute(self, context):
        # Hand the wait to the Triggerer; this worker slot is freed immediately.
        self.defer(
            trigger=TimeDeltaTrigger(timedelta(hours=1)),
            method_name="execute_complete",
        )

    def execute_complete(self, context, event=None):
        # Runs on a worker (maybe a different one) after the trigger fires.
        return None

And a custom trigger:

import asyncio

from airflow.triggers.base import BaseTrigger, TriggerEvent


class FileLandedTrigger(BaseTrigger):
    def __init__(self, path: str, poke_interval: float = 30.0):
        super().__init__()
        self.path = path
        self.poke_interval = poke_interval

    def serialize(self):
        # How Airflow stores this trigger in the DB and rebuilds it in the Triggerer.
        return ("my_pkg.triggers.FileLandedTrigger", {"path": self.path, "poke_interval": self.poke_interval})

    async def run(self):
        while not await file_exists(self.path):  # must be a non-blocking, async check
            await asyncio.sleep(self.poke_interval)
        yield TriggerEvent({"path": self.path})

Walkthrough

Follow one deferred task through its whole lifecycle:

Lifecycle of a deferred task
run tasktrigger rowtrigger ⇄ eventscheduledSchedulerWorkerslotTriggerer(asyncio)Metadata DB

1/6The scheduler finds the task ready and queues it. A worker picks it up and starts execute(). The task now holds a slot.

All steps (text version)
  1. The scheduler finds the task ready and queues it. A worker picks it up and starts execute(). The task now holds a slot.
  2. execute() calls self.defer(...). Airflow writes the serialized trigger to the trigger table, sets the task state to deferred, and the worker process exits. The slot is free for other tasks.
  3. The Triggerer polls the DB for unassigned triggers, claims this one, rebuilds it from its classpath and kwargs, and starts its run() coroutine on the event loop.
  4. The trigger waits alongside hundreds of others. Each one spends nearly all its time in await, so one process handles them all.
  5. The condition is met: run() yields a TriggerEvent. The Triggerer stores the event payload on the task instance, sets its state back to scheduled, and cleans up the trigger.
  6. The scheduler sees a scheduled task and queues it again. A worker (maybe a different one) calls execute_complete(context, event) and the task finishes.

The task’s states over its lifetime:

Task states with deferral

self.defer()

TriggerEvent

timeout

scheduled

queued

running

deferred

failed

success

Task states with deferral

self.defer()

TriggerEvent

timeout

scheduled

queued

running

deferred

failed

success

Task states with deferral

Failure modes & trade-offs

Setting Default When to change
[triggerer] default_capacity (Airflow 2; capacity in 3) 1000 Lower it if triggers are CPU-heavy; run more Triggerers instead of raising it a lot
[operators] default_deferrable False Set True once a Triggerer is deployed and monitored
defer(timeout=...) none Always set one, so a wait on something that will never happen eventually fails
Sensor poke_interval (deferrable mode) 60 s Lower is cheap now, but respect the external API’s rate limits

When not to defer. Short waits (a few seconds) aren’t worth the round trip through the database and the scheduler. Work that needs the worker’s CPU, memory or local disk should stay on a worker. Deferral is for waiting, not for working.

Test yourself

Why can't a sensor simply sleep inside the worker?easy

It can, but every sleeping sensor holds a worker slot (a whole process), so long waits starve real work and force you to over-provision workers. Deferral moves the waiting into a cheap coroutine in the Triggerer and frees the slot.

How is deferrable different from reschedule mode?medium

Both free the slot between checks. In reschedule mode every check is a full task run (schedule, queue, start a process, parse the DAG, run, exit), which is expensive at short intervals. With deferral the check is a coroutine in the Triggerer, so frequent checks are cheap, and the task only goes back to a worker once, when the event fires.

What happens to deferred tasks if the Triggerer crashes?medium

Triggers are persisted in the metadata DB and assigned to a Triggerer that heartbeats. If it stops heartbeating, another Triggerer (or the restarted one) claims its triggers and restarts them from scratch. This is why triggers must be idempotent, and why you run at least two Triggerers in production.

A trigger works in testing but in production every deferred task gets slow. What do you suspect?hard

A blocking call inside some trigger’s run(): a sync HTTP client, time.sleep, or a sync SDK. It blocks the shared event loop, so every trigger in that process stalls. Check the Triggerer logs for blocked-thread warnings, find the trigger, and switch it to an async client or asyncio.to_thread.

What state is lost when a task resumes after deferral?hard

Everything in memory. The resumed run is a new process that calls method_name with the event payload and any kwargs passed to defer(). Instance attributes set during the first execute() and local variables don’t survive. Anything needed later must be serializable and passed explicitly.

Further reading