AIRFLOW

Airflow XComs: Sharing Data Between Tasks

Airflow tasks run in complete isolation, thats why a variable created in one task disappears when it finishes. XComs solve this by giving tasks a small shared storage layer to leave values for each other. You'll learn how return values get pushed to XCom automatically and how downstream tasks pull them by task ID.

XComs: Cross-Communication

XCom stands for Cross-Communication. It is a small storage layer inside Airflow's metadata where tasks can leave values for other tasks to pick up. When a function used by a Python operator returns a value, Airflow automatically pushes it to XCom.

Creating the DAG

Create a new file called xcom.py in the DAGs folder.

from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime

Create an extract function that returns a value:

def extract():
    record_count = 42
    print(f"Extracted {record_count} records")
    return record_count

Create a transform function that pulls the value from extract:

def transform(ti):
    count = ti.xcom_pull(task_ids='extract')
    print(f"Transforming {count} records")
    return count * 2

Define the DAG and tasks:

with DAG(
    'xcom_dag',
    start_date=datetime(2023, 1, 1),
    schedule='@daily',
    catchup=False
) as dag:

    extract_task = PythonOperator(
        task_id='extract',
        python_callable=extract
    )

    transform_task = PythonOperator(
        task_id='transform',
        python_callable=transform
    )

    extract_task >> transform_task

Save the file.

Running the DAG

In the Airflow UI, go to the DAGs section. Search for xcom_dag. Click on it and trigger a single run.

For the extract task, go to the XCom section and see the value is 42. For the transform task, the XCom value is 84, confirming that the data was shared between tasks.


What's next

Now go and try this out in a live environment — boot a fresh cluster and play with the manifests above.

Start Airflow
Spec 4 CPU / 8 GiB ·Disk 25 GiB
Sign in to launch this environment
Required 1 VM · 4 CPU · 8 GB · 25 GiB disk
Available 1 VM · 1 CPU · 2 GB · 10 GiB disk
Sign in

Suggested tutorials

Keep the momentum going, pick a related topic.