Skip to main content

How to Chain Tasks with chain() in Apache Airflow®

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

Writing a >> b >> c >> d gets long once an Apache Airflow® Dag has many steps. chain() takes the tasks in order and sets the same dependencies in one call. It also does something >> can't: give it two lists of the same length next to each other and it pairs them up, first with first and second with second. This guide builds a six-task Dag with chain() on Airflow 3.4.0.

Syntax​

Syntax
from airflow.sdk import chain

chain(<task>, <task>, <task>)
chain(<task>, [<task a1>, <task b1>], [<task a2>, <task b2>], <task>)
PartWhat it means
from airflow.sdk import chainThe function, from Airflow 3's Task SDK
<task>A task: an operator, or what a TaskFlow task function returns when you call it
chain(<task>, <task>, <task>)Each argument runs after the one before it
[<task a1>, <task b1>], [<task a2>, <task b2>]Two lists of the same length side by side: a1 runs before a2, and b1 before b2

Airflow's Dags documentation shows chain(op1, op2, op3, op4) as a replacement for op1 >> op2 >> op3 >> op4, and says "Chain can also do pairwise dependencies for lists the same size".

The Example​

A Dag called make_fruit_salad buys fruit, peels the apples and the pears, chops them, and mixes the salad. The apples can be chopped as soon as they're peeled, without waiting for the pears, and the other way round.

Prerequisites​

  • Apache Airflow® running, for example with airflow standalone, and its dags folder in your AIRFLOW_HOME.

Step 1: Write the Tasks​

Create dags/make_fruit_salad.py, and import chain along with dag and task:

dags/make_fruit_salad.py
from airflow.sdk import chain, dag, task


@dag(schedule=None, tags=["demo"])
def make_fruit_salad():
@task
def buy_fruit():
print("Buying fruit")

@task
def peel_apples():
print("Peeling apples")

@task
def peel_pears():
print("Peeling pears")

@task
def chop_apples():
print("Chopping apples")

@task
def chop_pears():
print("Chopping pears")

@task
def mix():
print("Mixing the salad")

Step 2: Put Them in Order with chain()​

Still inside the Dag function, call each task function where it belongs in the order:

dags/make_fruit_salad.py
chain(
buy_fruit(),
[peel_apples(), peel_pears()],
[chop_apples(), chop_pears()],
mix(),
)
  • buy_fruit() comes first.
  • The first list holds the two peel tasks. Both wait for buy_fruit.
  • The second list has the same length, so chain() pairs it with the first by position: chop_apples waits for peel_apples, and chop_pears for peel_pears.
  • mix() waits for both chop tasks.

The complete file, with the call to the Dag function at the end:

dags/make_fruit_salad.py
from airflow.sdk import chain, dag, task


@dag(schedule=None, tags=["demo"])
def make_fruit_salad():
@task
def buy_fruit():
print("Buying fruit")

@task
def peel_apples():
print("Peeling apples")

@task
def peel_pears():
print("Peeling pears")

@task
def chop_apples():
print("Chopping apples")

@task
def chop_pears():
print("Chopping pears")

@task
def mix():
print("Mixing the salad")

chain(
buy_fruit(),
[peel_apples(), peel_pears()],
[chop_apples(), chop_pears()],
mix(),
)


make_fruit_salad()

The make_fruit_salad.py Dag file in an editor window: six @task functions and one chain() call with buy_fruit, a list of the two peel tasks, a list of the two chop tasks, and mix.

Step 3: Check the Pairs in the Graph View​

Trigger the Dag, open it and choose the Graph view:

The Graph view of make_fruit_salad after a successful run: buy_fruit, then peel_pears and peel_apples, then chop_pears and chop_apples, then mix, with each peel task joined only to the chop task of the same fruit.

Each peel task has one line going on, to the chop task of the same fruit: chain() paired the two lists instead of joining every peel task to every chop task. Both chop tasks lead into mix, and every task succeeded.

Common Mistakes​

MistakeWhat happensDo this instead
Two lists of different lengths side by side, such as [a, b], [c, d, e]ValueError: Chain not supported for different length Iterable. Got 2 and 3.Give side-by-side lists the same length, or put a single task between them
Expecting every task in one list to run before every task in the nextchain() pairs them by position insteadUse cross_downstream, which the documentation describes as different from chain's pairs
Importing it from Airflow 2's path, airflow.models.baseoperatorIt still works in 3.4.0, with a warning: The `airflow.models.baseoperator.chain` attribute is deprecated.Import it from airflow.sdk

Troubleshooting​

SymptomLikely causeFix
ValueError: Chain not supported for different length IterableTwo lists next to each other have different lengthsCount the tasks in each list
A task waits for more tasks than you expectedIt sits after a single task or a list that isn't paired with its ownCheck the Graph view, and pair the lists or split the chain
Two tasks you chained run at the same timeThey're in the same listPut them in separate arguments

FAQ​

When is chain() better than >>?​

When the order is long, or built from a list in a loop: the documentation's example chain(*[EmptyOperator(task_id=f"op{i}") for i in range(1, 6)]) chains five tasks made in a loop. For a few tasks, >> and << read just as well.

How do I make every peel task run before every chop task?​

Use cross_downstream([peel_apples, peel_pears], [chop_apples, chop_pears]), imported from airflow.sdk. The Dags documentation shows it replacing [op1, op2] >> op3 and [op1, op2] >> op4.

Conclusion​

One chain() call set the order of six tasks: buy_fruit, the two peel tasks, the two chop tasks paired one to one with them, and mix. Use chain() for long orders, and give lists that sit side by side the same length.

Additional Resources​

Apache®, Apache Airflow and Airflow® are either registered trademarks or trademarks of The Apache Software Foundation in the United States and/or other countries. No endorsement by The Apache Software Foundation is implied by the use of these marks.