home
diamond Go Premium
Data Engineering Path  ·  Airflow
Apache Airflow Logo

Dynamic Task Mapping

🔄 Creating Tasks Dynamically at Runtime (Airflow 2.3+)

Dynamic Task Mapping allows you to create multiple task instances from a single task definition at runtime. This is perfect when you don't know ahead of time how many items you need to process.


The Problem: Unknown Number of Items

# ❌ Without dynamic mapping — hardcoded file list
process_file_1 = PythonOperator(task_id="process_file_1", ...)
process_file_2 = PythonOperator(task_id="process_file_2", ...)
process_file_3 = PythonOperator(task_id="process_file_3", ...)
# What if there are 100 files? Or the count changes daily?

The Solution: .expand()

# ✅ With dynamic mapping — files are discovered at runtime
@task()
def get_files():
    """Discover files to process."""
    import boto3
    s3 = boto3.client('s3')
    response = s3.list_objects_v2(Bucket='data-bucket', Prefix='input/')
    return [obj['Key'] for obj in response['Contents']]

@task()
def process_file(file_key: str):
    """Process a single file. This runs once per file!"""
    print(f"Processing {file_key}")
    # Process the file...
    return {"file": file_key, "status": "done"}

@task()
def summarize(results: list):
    """Aggregate all results."""
    print(f"Processed {len(results)} files total")

# Magic: expand() creates one task instance per file
files = get_files()
results = process_file.expand(file_key=files)
summarize(results)
graph TD
    A["get_files()"] --> B["process_file[0]<br/>file_1.csv"]
    A --> C["process_file[1]<br/>file_2.csv"]
    A --> D["process_file[2]<br/>file_3.csv"]
    A --> E["process_file[N]<br/>file_N.csv"]
    B --> F["summarize()"]
    C --> F
    D --> F
    E --> F
    style A fill:#017cee,stroke:#015bb5,color:#fff
    style B fill:#4CAF50,stroke:#388E3C,color:#fff
    style C fill:#4CAF50,stroke:#388E3C,color:#fff
    style D fill:#4CAF50,stroke:#388E3C,color:#fff
    style E fill:#4CAF50,stroke:#388E3C,color:#fff
    style F fill:#9C27B0,stroke:#7B1FA2,color:#fff
💡 Tip
Dynamic Task Mapping is one of the most powerful features added to Airflow 2.x. It replaces the old pattern of generating tasks with Python loops at DAG parse time, which was fragile and created static DAGs.
lock

This content is reserved for Premium Members.

Upgrade to Premium

Entity Details

Create New Item

help

Submit Technical Query

Have a question or run into an issue? Describe it below, upload an optional screenshot, and our engineering team will answer it!

image Attach image (optional)

Submit Feedback

build Free Developer Utility Free Tool
gavel

Privacy & Legal Disclaimer

1. Client-Side Browser Processing

All utility tools on DeepEngineerHub (including Image to PDF, Text Formatters, JSON Converters, and Encryptors) execute 100% locally within your client browser using WebAssembly and JavaScript. No uploaded images, text, or documents are transmitted, collected, or stored on remote servers.

2. Limitation of Liability ("As-Is" Provision)

Tools and services are provided free of charge for convenience and educational purposes "as-is" without warranties of any kind. DeepEngineerHub shall not be held liable for any data loss, formatting inconsistencies, or indirect damages resulting from tool usage.

3. Open Source & Third-Party Software

Certain utilities utilize open-source client libraries (such as jsPDF, Mermaid.js, Pyodide) licensed under MIT, Apache, or BSD open licenses. All intellectual property remains with their respective copyright holders.