Airflow Dynamic Task Mapping
Dynamic task mapping creates many copies of one task at run time, based on the data that an earlier task produces. You write the task once. Airflow decides how many copies to run when the DAG executes. This fits jobs such as "process every file in a folder", where the file count changes each day.
The Cashier Lanes Picture
A supermarket opens cashier lanes based on the crowd. Ten shoppers open two lanes. Fifty shoppers open eight lanes. The shop does not build a fixed number of lanes in advance. Dynamic task mapping opens as many task lanes as the data requires.
list_files ──► ["a.csv", "b.csv", "c.csv"]
│
┌─────────────┼─────────────┐
▼ ▼ ▼
process(a.csv) process(b.csv) process(c.csv) ← mapped copies
└─────────────┼─────────────┘
▼
summary
Why Not Use a Loop?
A Python loop in the DAG file runs when the scheduler parses the file. The scheduler cannot know today's file list at that moment. Dynamic task mapping waits until run time, reads the real list, and creates the copies then.
A First Example
from datetime import datetime
from airflow import DAG
from airflow.decorators import task
with DAG("mapping_demo", start_date=datetime(2024, 1, 1),
schedule="@daily", catchup=False) as dag:
@task
def list_files():
return ["a.csv", "b.csv", "c.csv"]
@task
def process(file_name):
print(f"Processing {file_name}")
return len(file_name)
@task
def summary(sizes):
print(f"Processed {len(sizes)} files, total {sum(sizes)}")
files = list_files()
results = process.expand(file_name=files)
summary(results)
How It Works
list_filesreturns a list.process.expand(file_name=files)creates one task instance per list item.- Each copy runs on its own, with its own state, log, and retries.
summaryreceives all results as one collection.
The Key Methods
| Method | Purpose |
|---|---|
.expand() | Creates one copy per value in a list or dictionary |
.partial() | Sets values that stay the same in every copy |
.expand_kwargs() | Maps over a list of full argument sets |
.zip() | Pairs several lists item by item |
Mix Fixed and Changing Values
@task
def upload(file_name, bucket):
print(f"Uploading {file_name} to {bucket}")
upload.partial(bucket="company-data").expand(file_name=files)
The bucket stays the same for every copy. The file name changes per copy.
Mapping Classic Operators
from airflow.operators.bash import BashOperator
BashOperator.partial(task_id="show").expand(
bash_command=["echo north", "echo south", "echo east"]
)
Mapped Tasks in the UI
The Grid view shows a mapped task with a count, such as "process [3]". Click it to see each copy listed by its map_index number: 0, 1, 2. Each copy keeps a separate log, and you can clear one failed copy without touching the others.
process [3] ├── map_index 0 → success ├── map_index 1 → failed ← clear and rerun only this one └── map_index 2 → success
Limits and Care
- Airflow caps the copies of one task with
max_map_length, 1024 by default. - Each copy is a full task instance. Ten thousand copies add scheduler load.
- Group small items into batches when the list is very large.
- Mapped values travel through XComs, so keep them small, such as file names and ids.
Batching Example
@task
def make_batches(items, size=100):
return [items[i:i + size] for i in range(0, len(items), size)]
process_batch.expand(batch=make_batches(all_ids))
Mapping or Dynamic DAGs?
| Need | Better Choice |
|---|---|
| Copies depend on data found at run time | Dynamic task mapping |
| Copies depend on a fixed config known at parse time | Dynamic DAG generation with a loop |
Key Takeaways
expandcreates copies from run-time data.partialsets the shared values.- Each copy has its own state, log, and retries.
- Batching keeps large jobs manageable.
