Skip to content
Silver 4 min read · Scale

Dynamic task mapping

Some pipelines must fan out over a list known only when the run starts: today's files, the tables that changed. Dynamic task mapping creates one task per item at run time. This lesson shows how, and how to collect the results.

Pipelines in production · Airflow · Silver · Scaling a DAG, lesson 1 of 2

Read first: XCom: passing data between tasks (skip if you know it)

In plain words first

A teacher does not know how many homework sheets will be handed in until the bell rings. Once they see the pile, they hand one sheet to each marker. The number of markers is decided by the pile, not in advance.

Dynamic tasktask: One step of a DAG, such as running a query or calling an API. Each run of a task for one date is a task instance. Learn more → mapping is that: one task copy per item in a list produced at run time.

One task per input, decided at run time

Some pipelines fan out over a list that is only known when the run starts: today's new files, the labels that sent statements, the tables changed upstream. Writing a for loop in the DAGDAG: A pipeline in Airflow: a set of tasks and the order they run in, defined in a Python file and run on a schedule. Learn more → file would fix the list at parse time. Dynamic task mapping creates the task instancestask instance: One run of one task for one DAG run, with its own state (queued, running, success, failed) and its own log. Learn more → when the run reaches that task, one per element.

Python · one load per file that arrived
@task
def list_statements(ds=None):
    # e.g. 3 files today, 40 tomorrow
    return list_files(f"s3://landing/label_statements/{ds}/")

@task
def load_statement(path, ds=None):
    load(path, day=ds)
    return path

@task
def report(loaded):
    print(f"loaded {len(list(loaded))} statements")

report(load_statement.expand(path=list_statements()))

In the grid each mapped task shows as one task with a number of mapped instances, indexed from 0 (map_index), each with its own state, tries and logs. A downstream task that takes the mapped output receives all the results, in order.

partial() for the fixed arguments

Python · fixed and mapped arguments
BashOperator.partial(task_id="convert", retries=2).expand(
    bash_command=["convert a.csv", "convert b.csv", "convert c.csv"]
)

load_statement.partial(ds="{{ ds }}").expand(path=list_statements())

# several arguments that vary together
@task
def copy_table(src, dst):
    ...   # copy table src to dst

copy_table.expand_kwargs(
    [{"src": "plays", "dst": "plays_bak"}, {"src": "users", "dst": "users_bak"}]
)

expand with two lists creates the cross product (every combination); expand_kwargs takes one dict of arguments per instance when they vary together.

Empty lists and limits

  • An empty list creates no instances: the mapped task is skipped, and the skip travels downstream under the default trigger ruletrigger rule: The condition that lets a task start, based on its upstream tasks: all succeeded (the default), one failed, all done, and so on. Learn more →. Decide whether "no files today" should skip the report or not.
  • A mapped task can have at most max_map_length instances (1,024 by default). Fan out over thousands of items in batches instead.
  • max_active_tis_per_dagrun caps how many instances of a mapped task run at once, so 500 loads do not open 500 connections to the warehouse.
Tip: map over references (paths, table names, ids), not data. The list itself travels through XComXCom: Cross-communication: small values one task saves for later tasks to read, like a file path or a row count. Not for the data itself. Learn more →, so a list of 1,000 paths is fine and a list of 1,000 records is not.

Common mistakes

  • A for loop over today's files in the DAG file — The list is fixed when the file is parsed, not when the run happens.
  • Mapping over the records themselves — The list goes through XCom; map over paths or ids.
  • No concurrency limit on a wide fan-out — Hundreds of instances hit one system at once.
  • Forgetting that an empty list skips downstream — A report silently never runs on quiet days.

Key takeaways

  • expand() creates one task instance per element, at run time.
  • partial() fixes the arguments that do not vary; expand_kwargs maps argument sets.
  • An empty list skips the mapped task.
  • Limit fan-out with max_active_tis_per_dagrun; map over references, not data.

Interview prep

THE QUESTION

"Each day a different number of partner files arrives. How do you process each file as its own task?"

Dynamic task mapping: a task lists the files for the run's date and returns their paths, and the load task is expanded over that list, load.expand(path=list_files()), with partial() for the fixed arguments. Each file gets its own task instance with retries and logs, so one bad file does not hide the others. I would cap parallelism with max_active_tis_per_dagrun, decide what an empty day should do (the mapped task is skipped), and batch if files can exceed max_map_length.

Avoid: a for loop over today's files in the DAG file. The loop runs at parse time, so the task list follows the files present when the file was parsed, not when the run happens.

Follow-ups · answer out loud, then open

Follow-up"What is the difference between expand(a=[1, 2], b=[3, 4]) and expand_kwargs?"
expand with two lists creates the cross product: four instances. expand_kwargs takes a list of argument dicts and creates one instance per dict, for arguments that vary together.
Scenario"A mapped load over 800 files overwhelms the warehouse. What do you change?"
Cap concurrency with max_active_tis_per_dagrun (and a pool shared with other DAGs), or batch the files so each instance loads a group. Keep the list itself small: map over paths, not file contents.
Trap"If the upstream returns an empty list, the mapped task runs once with no input."
It creates no instances and is skipped, and under default trigger rules the skip carries on downstream.

Check yourself

3 questions

When is the number of mapped instances decided?

Show the answer

When the run reaches the task. Mapping expands over the input available at run time.

A mapped task gets an empty list. What happens?

Show the answer

It is skipped. No instances are created and the task is skipped.

Which setting limits how many mapped instances run at the same time?

Show the answer

max_active_tis_per_dagrun. It caps concurrent instances of that task in one run.

Keep going

Up next · Scaling a DAG · lesson 2 of 2 · 5 min read
Task groups, setup and teardown
Organise a large DAG into groups, and pair resources with their clean-up.

Related lessons

Previous: Sensors and deferrable operators

Primary sources: Dynamic task mapping