How Airflow works inside
Part of the free LogicWiz Data Engineering course, Module 9: Orchestration. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Monday, 02:40. Forty tasks sit in scheduled while most worker slots are free. The UI says the scheduler is healthy. A DAG that was merged on Friday still has not appeared. Nothing has failed, so nothing has alerted. Nora says: "Follow one task from its file to a worker. The place where it stops is your answer."
You'll learn to
- Follow a task from its DAG file to a finished task instance
- Work out what DAG parsing costs and why a DAG is late
- Tell which limit holds a task in scheduled or queued
- Explain deferral, and what Airflow 3 moved
Learn
Programs that never talk to each other
Think of a kitchen where the cooks never speak. Every order and every finished plate goes on one board on the wall.
Airflow works like that: its programs never call each other. The board is the metadata database (Postgres or MySQL), which holds every DAG, run, task instance, XCom, trigger and pool.
- The DAG processor parses DAG files from a DAG bundle and writes each DAG to the database in serialised form.
- The scheduler reads those serialised DAGs, creates runs and decides which task instances may start. The executor is part of the scheduler process; it hands task instances to workers.
- A worker starts a fresh subprocess for each task instance.
- The triggerer runs the triggers of deferred tasks.
- The API server serves the UI and the REST API.
One task, from its file to a green square
A graph of Airflow 3: DAG files, the DAG processor, the metadata database, the scheduler, the triggerer, the API server and a worker; step by step the file is parsed, a run is created, the task is handed to a worker, the worker reports to the API server, and the state is written.
1. The file is parsed. The DAG processor imports the DAG file as Python and writes the result, a serialised DAG, to the metadata database.
2. A run is created. The scheduler reads the serialised DAG, never your file. It creates the run that is due and marks the task instances that are ready
scheduled.3. The task is handed over. When every limit has room, the scheduler marks the task instance
queued, and its executor hands it to a worker.4. The task runs. The worker starts a fresh subprocess for this one task instance. In Airflow 3 that subprocess talks only to the API server, through its Execution API, never to the database.
5. The state is written. The API server writes
successto the database. The scheduler sees it on its next pass, and the UI shows a green square.
Follow the blue boxes: they are the programs doing something at that step. The dashed arrow is the only way from task code into Airflow 3. In Airflow 2 the worker held database credentials and wrote states itself, so any task could read or change any DAG's rows.
First clue: the DAG that never appeared
A DAG merged on Friday is still not in the UI. Step 1 of the trip is where it stopped.
Parsing a DAG file means importing it as Python. So every top-level line runs: that API call, that database query. The DAG processor lists the bundle's files every 300 seconds ([dag_processor] refresh_interval). It parses each file again at most every 30 seconds (min_file_process_interval), 2 files at a time (parsing_processes).
There is also a hard limit. An import slower than 30 seconds ([core] dagbag_import_timeout) fails, and the DAG shows an import error.
The result of a parse, the serialised DAG, is all the scheduler reads. It never imports your file. A worker imports it again, but only to find and run its one task.
What 400 DAG files cost
files, parse_s, processes = 400, 1.5, 2
min_interval = 30 # [dag_processor] min_file_process_interval
one_pass = files * parse_s / processes
print(f"one pass over {files} files: {one_pass:.0f} s")
print(f"so each file is re-parsed every {max(one_pass, min_interval):.0f} s, not every {min_interval} s")
api_call_s = 2.0 # a requests.get(...) at the top of every file
slow_pass = files * (parse_s + api_call_s) / processes
calls_per_day = files * 86400 / max(slow_pass, min_interval)
print(f"with a top-level API call: {slow_pass:.0f} s a pass and {calls_per_day:,.0f} calls a day")
The interval is a minimum, not a promise: when a pass takes 300 s, a fix merged now appears up to five minutes later. Find the slow files with airflow dags report, move work out of top-level code, then raise parsing_processes if the CPU allows.
One pass over 400 DAG files
Three bars of seconds: the 30-second minimum interval the setting names, the 300 seconds one pass over 400 files really takes with two processes, and 700 seconds when every file makes a 2-second API call at the top.
Each bar is the time for one pass over the DAG files. A change you merge waits up to one pass before the scheduler can see it. The red bar also means 49,371 API calls a day that no task asked for.
One loop, three jobs
With the DAG parsed, the scheduler takes over. It runs one loop, over and over. An empty pass sleeps for 1 second (scheduler_idle_sleep_time).
- Create runs that are due, for up to 10 DAGs a pass.
- Examine up to 20 active runs. Task instances whose upstream tasks satisfy their trigger rule become
scheduled. Finished runs become success or failed. - The critical section: lock the rows of the pool table, take up to 16
scheduledtask instances in priority order, check every limit, mark the ones that fitqueuedand give them to the executor.
That lock is how several schedulers can run at once for high availability, on Postgres 12+ or MySQL 8+, with no other coordination: only one at a time is inside the critical section.
One pass of the scheduler
Four steps in a loop: create due runs, examine active runs to mark ready task instances scheduled, the locked critical section that checks limits and queues task instances, and the executor heartbeat that sends and tracks work.
Read it in order, then follow the loop arrow back to the start. Priority is priority_weight, by default summed over the task's downstream tasks (weight_rule="downstream"), so tasks with long chains behind them go first when slots are short.
Second clue: forty tasks in scheduled
Now the forty tasks. To read a stuck task, ask which program moves it out of each state:
nonetoscheduled: the scheduler, once the upstream tasks satisfy the trigger rule. If they cannot, it becomesupstream_failedorskipped.scheduledtoqueued: the critical section, when every limit has room.queuedtorunning: a worker starts it.runningtosuccessorfailed, or to one of three waiting states:up_for_retry(failed with tries left),up_for_reschedule(a sensor between checks) ordeferred(handed to the triggerer).- The three waiting states go back to
scheduledwhen their time or event comes.
So a task stuck in scheduled is waiting for a limit. One stuck in queued is waiting for a worker.
Task instance states
A state graph: none goes to scheduled or to upstream_failed and skipped; scheduled goes to queued, queued to running; running ends in success or failed, or waits in up_for_retry, up_for_reschedule or deferred, each of which returns to scheduled.
Follow the arrows from none. up_for_reschedule also returns to scheduled once its poke_interval is over. Only scheduled leads to queued: every road back to work passes through the critical section and its limits again.
A scheduler loop you can run
from collections import Counter
PARALLELISM, MAX_ACTIVE_TASKS, MAX_TIS_PER_QUERY = 6, 3, 16
POOLS = {'default_pool': 128, 'partner_api': 2}
# three runs of one DAG, three independent tasks each; call_api tasks share the partner_api pool
tis = [{'run': run, 'task': task, 'pool': 'partner_api' if task == 'call_api' else 'default_pool',
'priority': 2 if task == 'call_api' else 1, 'state': 'scheduled', 'loops_left': 2}
for run in ('06-01', '06-02', '06-03') for task in ('call_api', 'extract', 'audit')]
def critical_section():
"""Queue scheduled task instances, highest priority first, while every limit has room.
Returns what held back the ones left in scheduled."""
active = [ti for ti in tis if ti['state'] in ('queued', 'running')]
in_pool, in_run, total = Counter(ti['pool'] for ti in active), Counter(ti['run'] for ti in active), len(active)
held = Counter()
ready = sorted((ti for ti in tis if ti['state'] == 'scheduled'), key=lambda ti: (-ti['priority'], ti['run']))
for ti in ready[:MAX_TIS_PER_QUERY]:
if total >= PARALLELISM:
held['parallelism'] += 1
elif in_pool[ti['pool']] >= POOLS[ti['pool']]:
held[f"pool {ti['pool']}"] += 1
elif in_run[ti['run']] >= MAX_ACTIVE_TASKS:
held['max_active_tasks'] += 1
else:
ti['state'] = 'queued'
total, in_pool[ti['pool']], in_run[ti['run']] = total + 1, in_pool[ti['pool']] + 1, in_run[ti['run']] + 1
return dict(held)
def executor_and_workers():
"""Queued task instances start on a worker; a running one succeeds after two loops."""
for ti in tis:
if ti['state'] == 'running':
ti['loops_left'] -= 1
if ti['loops_left'] == 0:
ti['state'] = 'success'
elif ti['state'] == 'queued':
ti['state'] = 'running'
loop = 0
while any(ti['state'] != 'success' for ti in tis):
loop += 1
held = critical_section()
executor_and_workers()
states = dict(sorted(Counter(ti['state'] for ti in tis).items()))
print(f"loop {loop}: {states} held back: {held}")
Loop 1: the call_api tasks of 1 and 2 June take both partner_api slots, so 3 June's waits for the pool; six task instances then reach parallelism, so 3 June's other two wait as well. Slots free in loop 3, after that pass's critical section, so they are queued only in loop 4. Set PARALLELISM = 32, then MAX_ACTIVE_TASKS = 2, and see which limit binds.
Nine task instances, six places
Three runs with three task instances each, loop by loop: in loop 1 six start and three are held by the pool and by parallelism, in loops 2 and 3 the three still wait, in loop 4 they start, and by loop 6 all nine have succeeded.
Loop 1. By priority, the
call_apitasks go first. Two get the pool's 2 slots and the third is held by the pool. Four more tasks fit, and thenparallelism6 is reached.Loops 2 and 3. Six are still active, so the pass stops at
parallelismfor all three of 3 June's tasks. Nothing is wrong. They wait.Loop 4. The first six finished during loop 3, after that pass's critical section. Now there is room, so 3 June's three tasks are queued and start.
Loop 6. All nine have succeeded. They took six loops because of two limits, not because the workers were slow.
Each column is one run and each small box one task instance, with its state after that loop. Compare it with the lines the code printed.
Where a stuck task waits, and what holds it
| Stuck in | It means | Look at |
|---|---|---|
| scheduled | ready, but the critical section found no room | pool slots (airflow pools list), maxactivetasks, maxactivetisperdag, [core] parallelism |
| queued | given to the executor, no worker has started it | are workers alive? the Celery broker, workerconcurrency, Kubernetes pods stuck Pending; after 600 s, taskqueuedtimeout |
| upforretry | failed, waiting out its retry delay | the failed try's log |
| deferred | waiting in a triggerer | is a triggerer running? its capacity (1,000 by default), its log |
| no task instance at all | the run was never created | maxactiveruns, a paused DAG, catchup, an import error in the file |
The executor.open_slots metric says how many more tasks the executor will take. Zero open slots with work in queued points at the workers; free slots with work in scheduled points at a limit.
Remember: scheduled means a limit has no room. queued means no worker has picked it up. Find the limit that is binding before you turn a dial.
Executors: where a task actually runs
| Executor | A task runs in | Start-up cost | Good for |
|---|---|---|---|
| LocalExecutor (the default) | a process started by the scheduler, on its machine | lowest | small deployments; no extra machines |
| CeleryExecutor | long-lived workers that pull from a broker (Redis or RabbitMQ), workerconcurrency slots each (16 by default) | low: the worker is already up | many short tasks, a steady load |
| KubernetesExecutor | a new pod per task instance | seconds or more: schedule the pod, pull the image | isolation, a different image or size per task, bursty load |
| Several at once (Airflow 2.10+) | [core] executor = CeleryExecutor,KubernetesExecutor, then executor= on a task | per task | most tasks on Celery, the heavy ones in their own pod |
Whichever executor, the worker starts a new subprocess for each task instance. Module 10 lesson 4 covers what happens to that pod's memory.
Waiting without a worker
Lesson 9.4 said a deferrable sensor waits in the triggerer and holds no slot. Here is how, because it is one more way a task can look stuck.
The idea is a hand-off. The task stops, leaves a small description of what it is waiting for, called a trigger, and frees its worker. A separate program, the triggerer, keeps up to 1,000 triggers going at once in a single process: one asyncio event loop that they all share. When a trigger fires, the task is scheduled again and a worker finishes it.
A deferrable sensor waits for the payments file
A sequence: the worker raises TaskDeferred and frees its slot, the trigger is stored, a triggerer claims it and polls asynchronously, the event comes hours later, and the scheduler sends the task back to a worker to finish.
1. The task gives up its slot. The operator calls
self.defer(trigger=..., method_name=...), which raisesTaskDeferred. The try ends and the worker slot is free. Local variables are lost: onlymethod_nameand its keyword arguments carry state.2. The trigger is stored. Its class path and arguments are written, encrypted, to the
triggertable. The task instance becomesdeferred. By default it holds no pool slot.3. A triggerer takes over. It claims the trigger and runs its async
run()in the event loop, next to the others. Several triggerers share the work, and a dead one's triggers move to the rest.4. The event. Three hours later the file lands, and
run()yields an event. The task instance goes back toscheduled.5. The task resumes. It passes the critical section and its limits again. A worker resumes it in
method_name, with the event, and it finishes.
Read it top to bottom. Between the second message and the event, no worker holds anything for this task: forty such sensors cost forty small coroutines in one process. That is also why a trigger must never block. A time.sleep() or a synchronous HTTP call inside run() stalls every trigger on that triggerer.
What Airflow 3 moved, and why
Look back at the first picture and its dashed arrow: the biggest change in Airflow 3.
In Airflow 2, every worker held the database credentials and wrote task states itself. So any task could read or change any DAG's rows, and every worker kept its own database connections.
Airflow 3 splits that apart. Task code runs against the Task SDK (airflow.sdk). Its subprocess talks to the API server through the Execution API, with short-lived credentials for its own task instance, and the API server writes the state. The DAG processor became a separate, required program, and the old webserver became the API server.
For DAG authors: a task that opened a database session (settings.Session(), TaskInstance queries) no longer works. Use the REST API through the Airflow Python client.
Airflow 2 against Airflow 3
| Airflow 2 | Airflow 3 |
|---|---|
| Webserver for the UI | API server: the UI, the REST API and the Execution API |
| DAG parsing inside the scheduler by default | The DAG processor, started on its own with airflow dag-processor |
| Task code may open a database session | Task code talks only to the API server, through the Task SDK |
| maxactivetasks limits a whole DAG | maxactivetasks limits each run |
| SequentialExecutor, SubDAGs, task SLAs | Removed: use LocalExecutor, TaskGroups, deadline alerts (3.1) |
| airflow dags backfill runs in the CLI process | airflow backfill create: the scheduler runs it |
| A cron string gets data intervals; catchup on | A cron string gets a trigger timetable; catchup off |
The metadata database is the bottleneck nobody sizes. Every state change, heartbeat, XCom and UI page goes through it. When it is slow, scheduler passes slow down, tasks sit in scheduled with free slots, and the UI times out, all with no error anywhere. Keep XComs small, purge old rows on a schedule with airflow db clean --clean-before-timestamp ..., put a connection pooler such as PgBouncer in front of Postgres, and watch DAG parse times.
Numbers to remember
| Setting | Default | What it is |
|---|---|---|
| [dagprocessor] refreshinterval | 300 s | how often the bundle's files are listed (Airflow 2: dagdirlistinterval) |
| minfileprocessinterval | 30 s | the least time between two parses of one file |
| parsingprocesses | 2 | files parsed at the same time |
| [core] dagbagimporttimeout | 30 s | a slower import fails with an import error |
| dagfileprocessortimeout | 50 s | a processor stuck longer than this is killed |
| scheduleridlesleeptime | 1 s | the sleep after an empty pass |
| maxdagrunstocreateperloop | 10 | DAGs that get new runs in one pass |
| maxdagrunsperlooptoschedule | 20 | active runs examined in one pass |
| maxtisperquery | 16 | scheduled task instances the critical section takes, under roughly SELECT FROM slotpool FOR UPDATE NOWAIT |
| [scheduler] taskqueuedtimeout | 600 s | a task left in queued this long is retried or failed |
| taskinstanceheartbeattimeout | 300 s | a running task silent this long is failed or retried: the "zombie" of Lesson 9.2 |
| Triggers per triggerer | 1,000 | all in one asyncio event loop |
In Airflow 2 the parsing settings sat in [scheduler], and parsing ran inside the scheduler unless standalone_dag_processor was on. On Amazon MWAA, Google Cloud Composer or Astronomer you do not run these programs, but you still size them: schedulers, workers, the database tier, a second triggerer. The signals are the ones in this lesson: parse time per file, open executor slots, tasks in scheduled and queued.
What changed at SwiftKart
Both clues from 02:40 had their answer on the trip from file to worker.
The Friday DAG called an API at the top of its file. The import took more than 30 seconds, so every parse ended in an import error and the DAG never appeared. You moved the call into a task.
The forty tasks all belonged to the pool warehouse: 8 slots, 8 tasks running. The critical section found no room, so they waited in scheduled beside free workers. Nobody raised parallelism. The pool was doing its job.
That ends Module 9. Your pipeline runs on a schedule, survives a bad night and can rerun the past. Module 10 is about working like an engineer, and it starts with Git for pipelines.
In one line
Airflow's programs meet only in the metadata database: the DAG processor parses files, the scheduler's critical section queues what the limits allow, a worker runs each task and reports through the API server, and the triggerer holds the tasks that wait.
Interview corner
Walk me through what happens between a DAG file and a finished task in Airflow 3.
The DAG processor imports the file from its bundle (every top-level line runs), serialises the DAG and writes it to the metadata database. The scheduler reads the serialised DAG, creates the run when its time comes, marks task instances scheduled when their trigger rules are met, and in its critical section (holding row locks on the pool table) queues the ones that fit the pools, max_active_tasks and parallelism. The executor hands each to a worker, which starts a subprocess that imports the file again, runs the task, and reports state and XComs to the API server through the Execution API; the API server writes them to the database.
Tasks are stuck. How do you tell a scheduler problem from a worker problem?
By the state they are stuck in. In scheduled, the critical section found no room: a full pool, max_active_tasks per run, a task-level limit or parallelism, or a slow database making passes slow. In queued, the executor has them and no worker has started them: dead Celery workers or broker, worker_concurrency used up, Kubernetes pods Pending; after task_queued_timeout (600 s) they are retried or failed. I check airflow pools list, the executor.open_slots metric and the worker or pod logs accordingly.
How does a deferrable operator work, and when would you not use one?
It calls self.defer(), which raises TaskDeferred; the trigger is stored in the database, the task becomes deferred and frees its worker and, by default, its pool slot. A triggerer runs the trigger's async run() in an event loop with up to 1,000 others; when it yields an event, the task is scheduled again and resumes on a worker in method_name. I would not bother for waits of a few seconds, where the defer and resume cost more than they save, or where no async client exists, because a blocking call in a trigger stalls every trigger on that triggerer.
What changed architecturally in Airflow 3, and why does it matter to a data engineer?
Workers and task code lost direct database access: tasks use the Task SDK and talk to the API server's Execution API with short-lived credentials, and the API server, which replaced the webserver, writes the state. The DAG processor became a separate, required service. For DAG authors that means no ORM queries or Session() in tasks (use the REST API), imports from airflow.sdk, max_active_tasks counted per run, cron strings getting trigger timetables, catchup off by default, and SLAs replaced by deadline alerts in 3.1.