🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Complex Multi-DAG Orchestration in Airflow

đŸŸĸ Free Lesson

Complex Multi-DAG Orchestration

Multi-DAG Orchestration PatternsParent DAGOrchestratorTriggerDagRunFires child DAGCallbackon_failure_callbackExternalTaskCross-DAG waitSensorPolls stateCross-DAG FlowSource DAG {'->'} TriggerDagRun {'->'} Child DAG {'->'} ExternalTaskSensorCoordination PatternsTrigger {'>'} Sensor {'>'} Callback {'>'} Event-basedUse ExternalTaskSensor for dependency; TriggerDagRun for independent execution

Architecture Diagram

Formal Definitions

Detailed Explanation

Multi-DAG Orchestration Patterns

PatternMechanismWait TypeComplexityBest For
TriggerDagRunOperatorCreates child dag_runBlocking or non-blockingLowSimple parent-child
ExternalTaskSensorPolls child task stateReschedule mode recommendedMediumImplicit dependencies
Callback-basedDAG failure/success hooksAsynchronous notificationMediumAlerting and logging
Dynamic DAGsCode-generated dependenciesVariableHighMulti-team coordination
Fan-Out/Fan-InParallel triggers + consolidated waitParallel with barrierMediumMulti-region/multi-table

When to Use Each Pattern

  • TriggerDagRunOperator: When you need to trigger a child DAG and optionally wait for completion
  • ExternalTaskSensor: When you need to wait for a specific task in another DAG to complete
  • Callbacks: When you need to be notified of child DAG success/failure without polling
  • Fan-Out/Fan-In: When you need to process multiple datasets in parallel and consolidate results

Pattern 1: TriggerDagRunOperator

The simplest way to invoke a child DAG from a parent. The parent triggers the child and can optionally wait for completion.

python
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.operators.python import PythonOperator

with DAG(
    dag_id='parent_orchestrator',
    start_date=datetime(2024, 1, 1),
    schedule_interval='@daily',
    catchup=False,
    tags=['orchestration', 'parent'],
) as parent_dag:

    def preprocess(**context):
        """Prepare data before child DAG execution."""
        context['ti'].xcom_push(key='record_count', value=15000)
        context['ti'].xcom_push(key='source_date', value=context['ds'])

    trigger_etl = TriggerDagRunOperator(
        task_id='trigger_etl_pipeline',
        trigger_dag_id='child_etl_pipeline',
        conf={
            'source_date': '{{ ds }}',
            'record_count': '{{ ti.xcom_pull(task_ids="preprocess", key="record_count") }}',
        },
        wait_for_completion=True,
        execution_timeout=timedelta(hours=2),
    )

    trigger_quality = TriggerDagRunOperator(
        task_id='trigger_data_quality',
        trigger_dag_id='child_data_quality',
        conf={'source_date': '{{ ds }}'},
        wait_for_completion=True,
    )

    def post_process(**context):
        """Run after all children complete."""
        import logging
        logger = logging.getLogger(__name__)
        logger.info('All child DAGs completed successfully')

    process = PythonOperator(task_id='preprocess', python_callable=preprocess)
    post = PythonOperator(task_id='post_process', python_callable=post_process)

    process >> trigger_etl >> trigger_quality >> post

Pattern 2: ExternalTaskSensor

Wait for a specific task in another DAG to reach a terminal state. This creates implicit inter-DAG dependencies.

python
from datetime import datetime, timedelta
from airflow import DAG
from airflow.sensors.external_task import ExternalTaskSensor
from airflow.operators.python import PythonOperator


with DAG(
    dag_id='reporting_pipeline',
    start_date=datetime(2024, 1, 1),
    schedule_interval='0 6 * * *',
    catchup=False,
    tags=['reporting'],
) as report_dag:

    wait_for_etl = ExternalTaskSensor(
        task_id='wait_for_etl_complete',
        external_dag_id='etl_pipeline',
        external_task_id='load_to_warehouse',
        execution_delta=timedelta(hours=1),
        timeout=timedelta(hours=4).total_seconds(),
        mode='reschedule',
        poke_interval=300,
    )

    wait_for_quality = ExternalTaskSensor(
        task_id='wait_for_quality_checks',
        external_dag_id='data_quality_checks',
        external_task_id='validate_tables',
        execution_delta=timedelta(hours=1),
        timeout=timedelta(hours=4).total_seconds(),
        mode='reschedule',
    )

    generate_reports = PythonOperator(
        task_id='generate_reports',
        python_callable=lambda: print('Generating reports...'),
    )

    [wait_for_etl, wait_for_quality] >> generate_reports

Pattern 3: Cross-DAG XCom with Dynamic DAGs

python
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.slack.operators.slack_webhook import SlackWebhookOperator


def check_downstream_status(**context):
    """Query metadata DB for downstream DAG status."""
    from airflow.models import DagRun, TaskInstance
    from airflow import settings
    from airflow.utils.state import State

    session = settings.Session()
    downstream_dags = ['etl_pipeline', 'quality_checks', 'reporting']

    statuses = {}
    for dag_id in downstream_dags:
        runs = session.query(DagRun).filter(
            DagRun.dag_id == dag_id,
            DagRun.execution_date >= context['execution_date'] - timedelta(hours=1),
        ).all()

        statuses[dag_id] = {
            'run_count': len(runs),
            'latest_state': runs[-1].state if runs else 'no_runs',
        }

    context['ti'].xcom_push(key='downstream_statuses', value=statuses)
    return statuses


with DAG(
    dag_id='multi_dag_monitor',
    start_date=datetime(2024, 1, 1),
    schedule_interval='*/15 * * * *',
    catchup=False,
    tags=['monitoring'],
) as monitor_dag:

    check = PythonOperator(
        task_id='check_downstream_status',
        python_callable=check_downstream_status,
    )

    alert = SlackWebhookOperator(
        task_id='alert_on_failure',
        slack_webhook_conn_id='slack_webhook',
        message=(
            'Downstream DAGs status:\n'
            '{{ ti.xcom_pull(task_ids="check_downstream_status", key="downstream_statuses") }}'
        ),
    )

    check >> alert

Pattern 4: Callback-Driven Coordination

python
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator
import json
import logging

logger = logging.getLogger(__name__)


def on_child_failure(context):
    """Callback triggered when child DAG fails."""
    dag_run = context.get('dag_run')
    task_instance = context.get('task_instance')

    logger.error(
        f'Child DAG failed: {dag_run.dag_id}, '
        f'run_id: {dag_run.run_id}'
    )

    # Send alert
    from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook
    hook = SlackWebhookHook(slack_webhook_conn_id='slack_webhook')
    hook.send(
        f'Child DAG Failure Alert\n'
        f'DAG: {dag_run.dag_id}\n'
        f'Run: {dag_run.run_id}\n'
        f'Task: {task_instance.task_id}'
    )


def on_child_success(context):
    """Callback triggered when child DAG succeeds."""
    dag_run = context.get('dag_run')
    logger.info(f'Child DAG completed: {dag_run.dag_id}')


with DAG(
    dag_id='callback_orchestrator',
    start_date=datetime(2024, 1, 1),
    schedule_interval='@daily',
    catchup=False,
    tags=['callbacks'],
) as callback_dag:

    from airflow.operators.trigger_dagrun import TriggerDagRunOperator

    trigger_pipeline = TriggerDagRunOperator(
        task_id='trigger_pipeline',
        trigger_dag_id='data_pipeline',
        on_success_callback=on_child_success,
        on_failure_callback=on_child_failure,
        wait_for_completion=True,
    )

    trigger_pipeline

Pattern 5: Fan-Out / Fan-In with Multiple DAGs

python
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.sensors.external_task import ExternalTaskSensor
from airflow.operators.python import PythonOperator


with DAG(
    dag_id='fanout_fanin_orchestrator',
    start_date=datetime(2024, 1, 1),
    schedule_interval='@daily',
    catchup=False,
    tags=['fanout', 'fanin'],
) as orchestrator:

    # Fan-out: trigger multiple child DAGs in parallel
    regions = ['us-east-1', 'eu-west-1', 'ap-southeast-1']
    triggers = []

    for region in regions:
        trigger = TriggerDagRunOperator(
            task_id=f'trigger_{region.replace("-", "_")}',
            trigger_dag_id='region_etl',
            conf={'region': region},
            wait_for_completion=False,
        )
        triggers.append(trigger)

    # Fan-in: wait for all children to complete
    sensors = []
    for region in regions:
        sensor = ExternalTaskSensor(
            task_id=f'wait_{region.replace("-", "_")}',
            external_dag_id='region_etl',
            external_task_id='complete',
            mode='reschedule',
            poke_interval=60,
            execution_delta=timedelta(minutes=5),
        )
        sensors.append(sensor)

    consolidate = PythonOperator(
        task_id='consolidate_results',
        python_callable=lambda: print('All regions processed'),
    )

    triggers >> sensors >> consolidate

Where Cross-DAG Wiring Breaks

Two DAGs are parsed, scheduled and retried independently, so failures surface in the parent even when the fault sits in the child. The commonest break is an execution-date mismatch: ExternalTaskSensor looks up the child task instance at its own logical date, so a reporting DAG that runs at 06:00 waits for an ETL task stamped 06:00 while the ETL only ever runs at 02:00. execution_delta=timedelta(hours=4) shifts that lookup backwards, and for unrelated timetables a callback passed as execution_date_fn computes the expected date on each poke.

The second break is a child run that never exists. TriggerDagRunOperator writes a dag_run row that the scheduler picks up on its next pass, so a paused child, a mistyped trigger_dag_id, or an undeployed DAG file leaves the parent waiting until execution_timeout expires. The third break is asymmetric retries: a retried trigger starts a second child run while the first is still writing to the same tables, so give each run an idempotency key through conf.

SymptomRoot causeFix
Sensor pokes for hours with no child log lineslogical dates do not line upset execution_delta or supply execution_date_fn
Triggered run never appears in the Grid viewpaused child, typo in trigger_dag_idverify pause state and spelling before the trigger fires
Parent fails while the child is still healthyparent execution_timeout shorter than child runtimeraise the timeout or use wait_for_completion=False plus a sensor
Child reprocesses the same date after a parent retryno idempotency guard on the triggered runpass a key through conf and skip work already done

Timeout and Slot Budgets

A sensor in poke mode holds one worker slot for the whole wait. A four-hour ExternalTaskSensor at a 300-second poke_interval issues 48 pokes while occupying that slot, so ten parallel sensors can drain a small Celery deployment. In reschedule mode the slot is released after every poke and re-acquired at the next interval, costing one extra metadata query per cycle.

Budget a parent DAG around three numbers. timeout is the sensor's hard stop and should be at least twice the longest child runtime observed. execution_timeout on the trigger must exceed timeout plus the parent's remaining work, so the sensor fails first with a message that names the missing dependency instead of killing the parent mid-flight. retry_delay then decides how long the chain waits after that failure.

SettingExample valueWhat it controls
poke_interval300 secondshow often the sensor queries the metadata database
timeout14400 secondswhen a waiting sensor declares the child lost
execution_timeout16200 secondswhen the parent gives up on its own task

Performance Metrics

MetricTriggerDagRunExternalTaskSensorCallbacks
Latency to trigger<1sN/A (polling)Immediate
Worker slot during waitReleased (if wait=False)Held (unless reschedule)N/A
ScalabilityHighMedium (sensor overhead)High
Error handlingTask failureSensor timeoutEvent-driven

Best Practices

Pattern Selection

  1. Use mode='reschedule' on ExternalTaskSensor to avoid holding worker slots during waits.
  2. Set execution_delta or execution_date_fn to match the child DAG's execution schedule.
  3. Implement wait_for_completion=True on TriggerDagRunOperator when downstream tasks depend on child completion.

Communication and Monitoring

  1. Use callbacks for alerting and logging — they fire independently of task state transitions.
  2. Avoid deep inter-DAG chains — they create fragile, hard-to-debug dependencies.
  3. Use XCom sparingly across DAGs — prefer external state stores for large data.

Operational Guidelines

  1. Tag orchestration DAGs distinctly from child DAGs for monitoring clarity.
  2. Set execution_timeout on sensors and triggers to prevent indefinite hangs.

Common Pitfalls

PitfallProblemSolution
Deep dependency chainsHard to debug, fragileKeep to 2-3 levels max
Missing timeoutsSensors hang indefinitelyAlways set execution_timeout
Blocking sensorsWastes worker slotsUse mode='reschedule'
XCom for large dataDatabase bloatUse external storage (S3, GCS)

See Also

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Airflow Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement