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
On this page
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.
@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
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_lengthinstances (1,024 by default). Fan out over thousands of items in batches instead. max_active_tis_per_dagruncaps how many instances of a mapped task run at once, so 500 loads do not open 500 connections to the warehouse.
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?"
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?"
Scenario"A mapped load over 800 files overwhelms the warehouse. What do you change?"
Trap"If the upstream returns an empty list, the mapped task runs once with no input."
Check yourself
3 questionsWhen 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 readTask groups, setup and teardown
Organise a large DAG into groups, and pair resources with their clean-up.
Related lessons
XCom: passing data between tasksAirflow · 5 min read
Sensors and deferrable operators
Previous: Sensors and deferrable operators
Primary sources: Dynamic task mapping