Airflow in practice

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 08:20, and the ticket says: "the payments DAG is stuck again". Last night's file landed hours ago, and its tasks are still waiting for a worker. Nora sends you the DAG file: sixty lines of operators, a sensor, connection ids and something called XCom. "Read it first," she says. "Then find out who is holding the slots."

You'll learn to

  • Name Airflow's parts and what each one does
  • Read a DAG file: operators, sensors, TaskFlow, XCom and connections
  • Pass small messages between tasks and say where they are stored
  • Choose how a sensor waits by who holds a slot meanwhile

Learn

Five programs and one database

Before the file, the machine that reads it. Airflow is a few programs sharing one metadata database (usually Postgres), which records every DAG run and task instance.

  • The DAG processor reads (parses) the DAG files. In Airflow 2 this was part of the scheduler; Airflow 3 runs it on its own.
  • The scheduler decides which runs and tasks are due, and queues them.
  • The executor decides how queued tasks run.
  • Workers run the task code. A worker has a fixed number of slots: one task per slot.
  • The web UI (an API server in Airflow 3) shows runs, logs and buttons.

Teams often rent all of this managed: Astronomer, Amazon MWAA, Google Cloud Composer.

From a file to a running task

Four steps in a row: the DAG processor reads the DAG files, the scheduler decides what is due, the executor decides how queued tasks run, and a worker runs the task code in a slot.

Read it in order: a task passes through all four. Each program writes what it did to the metadata database, and the UI shows you that record. Lesson 9.6 opens every box.

dags/swiftkart_payments.py

Runs in Airflow:

"""SwiftKart: load the shop's nightly payments export into the warehouse."""
from datetime import datetime, timedelta

from airflow.sdk import dag, task
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.amazon.aws.sensors.s3 import S3KeySensor
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator
from airflow.timetables.interval import CronDataIntervalTimetable

default_args = {"owner": "data-eng", "retries": 2, "retry_delay": timedelta(minutes=5)}


@dag(
    dag_id="swiftkart_payments",
    schedule=CronDataIntervalTimetable("0 2 * * *", timezone="UTC"),
    start_date=datetime(2025, 6, 1),
    catchup=False,
    max_active_runs=1,
    default_args=default_args,
    tags=["swiftkart", "payments"],
)
def swiftkart_payments():
    # 1. wait for the night's file (a sensor)
    wait_for_file = S3KeySensor(
        task_id="wait_for_file",
        bucket_name="swiftkart-landing",
        bucket_key="payments/{{ ds }}.jsonl",
        aws_conn_id="aws_landing",
        mode="reschedule",        # free the worker between checks
        poke_interval=300,        # look every 5 minutes
        timeout=6 * 60 * 60,      # give up after 6 hours
    )

    # 2. stage it, and return a small summary (an XCom)
    @task
    def stage(ds=None):
        hook = S3Hook(aws_conn_id="aws_landing")
        text = hook.read_key(f"payments/{ds}.jsonl", bucket_name="swiftkart-landing")
        lines = text.splitlines()
        # ... write the lines to the staging table ...
        return {"file": f"payments/{ds}.jsonl", "rows": len(lines)}

    # 3. merge staging into the fact table (templated SQL in a file)
    merge = SQLExecuteQueryOperator(
        task_id="merge",
        conn_id="warehouse",
        sql="sql/merge_payments.sql",
    )

    # 4. fail loudly if the file was empty, using stage's XCom
    @task
    def check(summary):
        if summary["rows"] == 0:
            raise ValueError(f"{summary['file']} was empty")

    summary = stage()
    wait_for_file >> summary >> merge >> check(summary)


swiftkart_payments()

Read it top to bottom once. Four numbered comments mark the four tasks. The next cards take them one at a time.

Four tasks, one at a time

The graph Airflow builds from the file, one task per step: the S3 sensor, the stage task, the merge operator and the check task, ending with a dashed edge from stage to check that carries the XCom summary.

  1. 1. Wait for the file. wait_for_file is a sensor: a task that only checks, again and again, until last night's file is in the bucket. It looks every 5 minutes and gives up after 6 hours.

  2. 2. Stage it. stage is a plain Python function with @task on top. That style is called TaskFlow. It reads the file through the connection aws_landing and returns a small dict: the file name and its row count.

  3. 3. Merge it. merge is an operator: a ready-made task. This one runs the SQL file sql/merge_payments.sql in the warehouse, which it reaches through the connection named warehouse.

  4. 4. Check it. check receives summary, the dict that stage returned, and fails loudly if the file was empty. Airflow carries the dict between the two tasks as an XCom, and draws the dashed arrow itself.

Follow the arrows from the sensor to the check. The dashed arrow is the one the file never wrote with >>: passing summary into check(...) makes check read stage's XCom, so Airflow adds the dependency itself.

Three kinds of task

Every task in that file is one of three kinds.

An operator is a ready-made kind of task: BashOperator, PythonOperator, SQLExecuteQueryOperator, DatabricksRunNowOperator, and hundreds more in provider packages for AWS, Azure, Google, Snowflake and dbt.

A sensor is an operator that waits until something is true: a file exists, a partition landed, another DAG finished.

TaskFlow (@task) turns a plain Python function into a task. Most new DAGs mix TaskFlow for Python logic with operators for outside systems.

The table below is a key to the rest of the file.

What each part of the file does

In the fileWhat it isWhy it is there
defaultargssettings for every taskretries and an owner, written once
schedule, catchup=False, maxactiveruns=1the DAG's timing02:00 daily with data intervals (lesson 1), so {{ ds }} is the day before; no history; one run at a time
S3KeySensor(..., mode="reschedule")a sensorwaits for the file without holding a worker
@task def stagea TaskFlow taskplain Python; its return value becomes an XCom
awsconnid, connid="warehouse"connectionscredentials live in Airflow, not in the file
SQLExecuteQueryOperatoran operatora ready-made task: run templated SQL in the warehouse
waitforfile summary merge check(summary)dependenciesthe graph; passing summary also adds an edge

XCom: a note passed between tasks

Look at task 4 again. check needs to know how many rows stage found. But tasks can run on different machines, so they cannot share Python variables.

So Airflow lets a task leave a small note for the tasks after it. The note is called an XCom ("cross-communication"). A TaskFlow task's return value becomes one automatically.

Use it for small things: a row count, a file path, a batch id, a watermark. The data itself goes to storage (a file in S3 or ADLS, a staging table), and the XCom says where it is. In miniflow, every task's return value is in ctx['xcom'].

Pass the path, not the data

import duckdb
import miniflow as mf

dag = mf.DAG('swiftkart_orders', start_date='2025-06-01', schedule='@daily')

@dag.task()
def extract(ctx):
    path = f"orders_{ctx['ds']}.parquet"
    duckdb.sql(f"""
        copy (select * from 'data/orders.csv'
              where order_ts >= '{ctx['data_interval_start']}' and order_ts < '{ctx['data_interval_end']}')
        to '{path}' (format parquet)
    """)
    rows = duckdb.sql(f"select count(*) from '{path}'").fetchone()[0]
    return {'path': path, 'rows': rows}          # the XCom: where the data is, and how much

@dag.task()
def load(ctx):
    info = ctx['xcom']['extract']                # like ti.xcom_pull(task_ids='extract')
    n = duckdb.sql(f"select count(*) from '{info['path']}'").fetchone()[0]
    assert n == info['rows'], 'the file changed between the two tasks'
    print(f"    load {n} rows from {info['path']}")

extract >> load
dag.run_until('2025-06-02')
dag.run_until('2025-06-03')

The XCom is a few bytes; the orders stay in the Parquet file. The assert is a cheap check that the two tasks agree, the same habit as counting both sides in Module 1.

Where the note is kept

Why small? Because of where a note lives. An XCom is a row in the metadata database's xcom table. Its address is the DAG, the run, the task, a map index and a key (return_value for a TaskFlow return), and its value is stored as JSON.

In Airflow 3, task code never opens a database session. The Task SDK sends each XCom read and write to the API server, and the API server writes the row. So every XCom is a network call, a database write, and a row that airflow db clean has to purge one day.

The scheduler depends on that same database. Two million orders in a note would make it huge and slow.

The note in the database, the data in storage

Two boxes: the metadata database holding one small XCom row with a file path and a row count, and storage holding the Parquet file with the orders themselves.

The left box holds a few bytes that say where the data is and how much there is. The right box holds the data. load reads the note, then opens the file.

Wait for the file, do not assume it

Now the sensor. The shop drops landing/orders/<day>.csv every night, usually by 01:00, sometimes at 04:00. A load that assumes the file is there fails. Or worse, it loads nothing and succeeds.

A sensor checks first, and waits.

miniflow has no sensor class. But a sensor is only a check that is tried again until it passes or its time runs out. So a task that raises while the file is missing, with retries, behaves the same way. The next card runs it over four nights. The drop for 8 June never arrives.

A sensor, made of a check and retries

import os
import miniflow as mf

dag = mf.DAG('swiftkart_orders', start_date='2025-06-05', schedule='@daily')

@dag.task(retries=2)
def wait_for_file(ctx):
    path = f"landing/orders/{ctx['ds']}.csv"
    if not os.path.exists(path):
        raise FileNotFoundError(f'{path} has not arrived')
    return path

@dag.task()
def load(ctx):
    print('    loading', ctx['xcom']['wait_for_file'])

wait_for_file >> load
for day in ['2025-06-06', '2025-06-07', '2025-06-08', '2025-06-09']:
    dag.run_until(day)
dag.grid()

The run for 8 June fails at the sensor and load never runs: no half-empty load, and a clear signal to whoever is on call. In Airflow the same sensor would check every few minutes until its timeout.

Who holds a slot while nothing happens?

Back to the ticket. A sensor spends hours doing nothing. Nora's question is what it holds while it does nothing. A sensor can wait in three ways.

  • poke (the default): one long try that checks, sleeps poke_interval, and checks again. It holds a worker slot and a pool slot for the whole wait.
  • reschedule: each check is a short try. Between checks the task sits in the state up_for_reschedule and holds no slot.
  • deferrable (deferrable=True where the operator supports it): the task hands its wait to a separate program, the triggerer, which watches many waits at once. The task's state is deferred. It holds no worker slot and, by default, no pool slot. When the wait is over, the task goes back to a worker to finish.

Four hours of waiting for one file

A timeline of 240 minutes: a poke sensor holds a worker slot the whole time, a reschedule sensor holds it only for brief checks every 30 minutes, and a deferrable sensor holds it only to defer and to resume while the triggerer waits.

Read each row as one way of waiting: a bar means something is held. It is drawn with a 30-minute poke_interval so the checks are visible. The deferrable task needs a worker only to start (and defer) and to resume after the trigger fires.

Forty sensors on 32 slots

sensors, wait_h = 40, 4                  # one sensor per partner feed, each waits 4 hours
poke_interval_s, check_s = 300, 2        # a check every 5 minutes takes 2 seconds
slots = 2 * 16                           # two Celery workers, worker_concurrency = 16 each

poke_slot_h = sensors * wait_h
checks = wait_h * 3600 // poke_interval_s
reschedule_slot_h = sensors * checks * check_s / 3600

print(f"poke:       {poke_slot_h} slot-hours; {min(sensors, slots)} of {slots} slots busy, {max(0, sensors - slots)} sensors waiting")
print(f"reschedule: {reschedule_slot_h:.2f} slot-hours ({checks} checks of {check_s} s each)")
print(f"deferrable: no worker slot while waiting; {sensors} of the triggerer's 1,000 trigger slots")

In poke mode the sensors take every slot, so the loads that should run when a file lands are stuck in queued behind sensors that are only sleeping: a slot deadlock. That is the ticket. worker_concurrency = 16 is the Celery default.

The same 32 slots, three ways to wait

Two workers with 16 slots each, a queue and a triggerer: in poke mode sleeping sensors hold every slot and other tasks queue; in reschedule mode the slots are free between checks; with deferrable sensors the waits sit in the triggerer and all slots are free.

  1. Poke. Thirty-two sensors hold all 32 slots while they sleep. Eight more sensors and the payments tasks sit in queued. Nothing is broken, and nothing can start.

  2. Reschedule. Each sensor takes a slot for a 2-second check every 5 minutes, then gives it back. The slots are free almost all the time, so the payments tasks start as soon as their file lands.

  3. Deferrable. The sensors hold no slot at all. Forty small triggers wait in the triggerer, which has room for 1,000 by default. Every slot is free for real work.

The four boxes are the same in every step: two workers, the queue of tasks with no slot, and the triggerer. Watch where the forty waiting sensors sit.

Remember: poke holds a slot while it sleeps. Reschedule holds one only while it checks. Deferrable holds none. If many tasks wait for hours, defer them.

Passwords stay out of the file

One last thing the file teaches by what it leaves out. It says conn_id="warehouse". It never says the host, the user or the password.

Those live in an Airflow connection, set in the UI, by an environment variable, or (best) in a secrets backend such as HashiCorp Vault, AWS Secrets Manager or Azure Key Vault. Small settings go in variables.

So the same DAG file runs in dev and in prod against different databases, and no password ever reaches Git.

Where to look in the Airflow UI

View or actionShows or doesUse it to
Gridruns as columns, tasks as rows, coloured by statespot the failed day and task (what dag.grid() prints)
Graphthe DAG's tasks and arrowssee what depends on what
Task logseverything a task instance printed, per tryread the error
Task durationshow long each task tookfind the slow step
Clearreruns a task (and downstream) for a runrecover after a fix (lesson 2)
Trigger DAGstarts a run now, optionally with a configa one-off run

Start with the Grid when a ticket says "stuck": the state of each task tells you where to look next.

Top-level code runs all the time. Airflow reads every DAG file again every 30 seconds by default (min_file_process_interval). A database query or an API call at the top of the file, outside any task, runs on every read: thousands of times a day, slowing the scheduler and hammering the source. Keep top-level code to imports and the DAG definition; do the work inside tasks.

Numbers to remember

NameNumber or valueWhat it means
minfileprocessinterval30 show often a DAG file is read again, top-level code included
workerconcurrency (Celery)16task slots on one worker
Triggers per triggerer1,000 by defaultall waiting in one asyncio event loop
A task that defersraises TaskDeferredits trigger is stored in the metadata database; when the trigger fires, the task is scheduled again and resumes on a worker
A sensor's timeoutcounts the whole waitpast it, AirflowSensorTimeout fails the task without retrying
[operators] defaultdeferrableTrueoperators that support it defer by default; run two triggerers for high availability
XCom key of a TaskFlow returnreturnvalueone row in the xcom table, value stored as JSON
[core] xcombackendairflow.providers.common.io.xcom.backend.XComObjectStorageBackendkeeps any value above [common.io] xcomobjectstoragethreshold bytes in S3, GCS or ADLS and stores only a reference in the table

The object storage backend moves the bytes; it does not make 2 million rows a good message. Teams on Amazon MWAA, Google Cloud Composer or Astronomer mostly use the providers' deferrable versions, such as S3KeySensor(..., deferrable=True) and DatabricksRunNowOperator(..., deferrable=True).

What changed at SwiftKart

The payments file was never the problem. Its sensor already waited in reschedule mode. The slots were held by forty partner-feed sensors in other DAGs, all in poke mode, all asleep.

You set deferrable=True on them. The next night they wait in the triggerer, the 32 slots stay free, and stage starts within minutes of the payments file landing. Nora closes the ticket.

You can now read a DAG file. Lesson 9.5 moves to Azure Data Factory, where the same ideas have other names and the problem is 50 tables to copy every night.

In one line

A DAG file wires operators, sensors and TaskFlow tasks; tasks pass small XComs and keep data in storage, credentials live in connections, and a long wait should hold no worker slot: reschedule it or defer it.

Interview corner

Walk me through Airflow's architecture.

DAG files are Python in a folder that Airflow parses (the DAG processor does it; in Airflow 2 it was part of the scheduler). The scheduler decides which DAG runs and task instances are due and queues them; the executor (Local, Celery or Kubernetes) hands them to workers that run the code. Every state change is stored in the metadata database, and the web UI or API server shows runs, logs and controls on top of it.

What is XCom, and what should not go in it?

XCom is a small key-value message a task stores in the metadata database for later tasks; TaskFlow return values become XComs automatically. Use it for metadata such as row counts, file paths, ids and watermarks. Large data should be written to storage or a staging table, with only its location passed by XCom.

What is a sensor, and what is the difference between poke and reschedule mode?

A sensor is an operator that waits until a condition is true, such as a file existing or another DAG finishing, with a poke interval and a timeout. In poke mode it holds its worker slot while it sleeps; in reschedule mode it releases the slot between checks. Deferrable operators go further and wait in a lightweight triggerer process.

Your workers are full of sensors and real work is stuck in queued. What do you do?

Poke-mode sensors sleep inside their try and keep the slot, so 40 of them on 32 slots block everything behind them. I would make them deferrable where the provider supports it (deferrable=True, or [operators] default_deferrable = True): they wait in the triggerer, which runs up to 1,000 triggers in one asyncio loop, and hold no worker or pool slot. Where that is not available, reschedule mode with a sensible poke_interval and a timeout. If the file lands at a known time, an event-driven trigger or a later schedule is cheaper than waiting at all.