Bird
Raised Fist0
Apache Airflowdevops~5 mins

Sharing data between tasks effectively in Apache Airflow - Commands & Configuration

Choose your learning style10 modes available
Introduction
When you run multiple tasks in Airflow, sometimes one task needs to give information to another. Sharing data between tasks helps them work together smoothly without repeating work or losing important details.
When a task processes data and the next task needs that processed data to continue.
When you want to pass small results like file names or counts from one task to another.
When you want to avoid storing data outside Airflow and keep it inside the workflow.
When tasks run in sequence and depend on each other's outputs.
When you want to keep your workflow clean by sharing only necessary data between tasks.
Config File - my_dag.py
my_dag.py
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.utils.dates import days_ago

def task_one(ti):
    data = 'Hello from task one'
    ti.xcom_push(key='message', value=data)

def task_two(ti):
    message = ti.xcom_pull(key='message', task_ids='task_one')
    print(f'Received message: {message}')

default_args = {
    'owner': 'airflow',
    'start_date': days_ago(1),
}

dag = DAG(
    'example_xcom_dag',
    default_args=default_args,
    schedule_interval=None,
    catchup=False
)

task_one = PythonOperator(
    task_id='task_one',
    python_callable=task_one,
    dag=dag
)

task_two = PythonOperator(
    task_id='task_two',
    python_callable=task_two,
    dag=dag
)

task_one >> task_two

This DAG defines two tasks using PythonOperator. task_one pushes a message using ti.xcom_push. task_two pulls that message with ti.xcom_pull and prints it. The tasks run in order, so task_two receives data from task_one.

Commands
List all available DAGs to confirm your DAG file is loaded by Airflow.
Terminal
airflow dags list
Expected OutputExpected
example_xcom_dag
Trigger the DAG to start running the tasks and share data between them.
Terminal
airflow dags trigger example_xcom_dag
Expected OutputExpected
Created <DagRun example_xcom_dag @ 2024-06-01T12:00:00+00:00: manual__2024-06-01T12:00:00+00:00, externally triggered: True>
Check the logs of task_two to see the message it received from task_one.
Terminal
airflow tasks logs example_xcom_dag task_two --execution-date 2024-06-01T12:00:00+00:00
Expected OutputExpected
Received message: Hello from task one [2024-06-01 12:00:10,000] {logging_mixin.py:112} INFO - Running <TaskInstance: example_xcom_dag.task_two manual__2024-06-01T12:00:00+00:00 [success]>
→
--execution-date - Specify the exact run time of the DAG to get logs for that run
Key Concept

If you remember nothing else from this pattern, remember: use XComs to push data in one task and pull it in another to share information inside Airflow workflows.

Common Mistakes
Trying to share large files or big data directly through XComs.
XComs are meant for small pieces of data; large data can cause performance issues or failures.
Store large data in external storage like S3 or a database and pass only references or file paths via XComs.
Not specifying the correct task_id when pulling data with ti.xcom_pull.
If the task_id is wrong, the data won't be found and the task will get None or fail.
Always use the exact task_id of the task that pushed the data when calling ti.xcom_pull.
Assuming data pushed in one DAG run is available in another DAG run.
XCom data is tied to a specific DAG run and execution date; it does not persist across runs.
Use external storage or variables if you need data to persist beyond a single DAG run.
Summary
Define tasks that push and pull data using ti.xcom_push and ti.xcom_pull.
Trigger the DAG and verify data sharing by checking task logs.
Use XComs for small data sharing within the same DAG run and task sequence.

Practice

(1/5)
1. What is the primary purpose of using Airflow Variables when sharing data between tasks?
easy
A. To execute tasks in parallel
B. To monitor task execution logs
C. To schedule DAG runs automatically
D. To store small pieces of data accessible across different tasks

Solution

  1. Step 1: Understand Airflow Variables role

    Airflow Variables are designed to hold small data values that can be shared between tasks.
  2. Step 2: Identify the correct use case

    Sharing data between tasks requires a storage mechanism accessible by all tasks, which Airflow Variables provide.
  3. Final Answer:

    To store small pieces of data accessible across different tasks -> Option D
  4. Quick Check:

    Airflow Variables = data sharing [OK]
Hint: Variables store shared data between tasks easily [OK]
Common Mistakes:
  • Confusing Variables with task scheduling
  • Thinking Variables execute tasks
  • Using Variables for logging
2. Which of the following is the correct way to set an Airflow Variable named my_var with value 123 inside a PythonOperator task?
easy
A. Variable.set('my_var', 123)
B. Variable.set(my_var, '123')
C. Variable.get('my_var', 123)
D. Variable.create('my_var', 123)

Solution

  1. Step 1: Recall Variable.set syntax

    The correct method to set a variable is Variable.set(key, value) where key is a string and value is the data.
  2. Step 2: Check option correctness

    Variable.set('my_var', 123) uses Variable.set with key 'my_var' and value 123 correctly as a string key and integer value.
  3. Final Answer:

    Variable.set('my_var', 123) -> Option A
  4. Quick Check:

    Set variable = Variable.set(key, value) [OK]
Hint: Use Variable.set('key', value) to store data [OK]
Common Mistakes:
  • Using Variable.get instead of set to store data
  • Not quoting the variable name key
  • Using a non-existent method like Variable.create
3. Given the following code snippet in two tasks, what will be printed by task_b?
from airflow.models import Variable

def task_a():
    Variable.set('shared_key', 'hello')

def task_b():
    value = Variable.get('shared_key')
    print(value)
medium
A. None
B. hello
C. shared_key
D. Error: Variable not found

Solution

  1. Step 1: Analyze task_a behavior

    task_a sets the Variable 'shared_key' with value 'hello'.
  2. Step 2: Analyze task_b behavior

    task_b retrieves the Variable 'shared_key' and prints its value, which is 'hello'.
  3. Final Answer:

    hello -> Option B
  4. Quick Check:

    Set then get Variable = 'hello' [OK]
Hint: Get returns the stored value by key [OK]
Common Mistakes:
  • Expecting the key name instead of value
  • Assuming Variable.get returns None if set
  • Forgetting to set the Variable before getting
4. You wrote this code in task_b to get a Variable set by task_a:
value = Variable.get('my_var')
But you get an error: KeyError: 'Variable my_var does not exist'. What is the best fix?
medium
A. Set a default value in Variable.get like Variable.get('my_var', default_var='default')
B. Change Variable.get to Variable.set
C. Remove the Variable.get call
D. Restart Airflow scheduler

Solution

  1. Step 1: Understand the error cause

    The error means 'my_var' was not set before getting it, so Variable.get fails.
  2. Step 2: Use default value to avoid error

    Variable.get supports a default_var parameter to return if key missing, preventing KeyError.
  3. Final Answer:

    Set a default value in Variable.get like Variable.get('my_var', default_var='default') -> Option A
  4. Quick Check:

    Use default_var to avoid missing key error [OK]
Hint: Add default_var to Variable.get to prevent errors [OK]
Common Mistakes:
  • Using Variable.set instead of get to read data
  • Ignoring missing Variable errors
  • Restarting scheduler without fixing code
5. You want to share a list of user IDs between two tasks in Airflow. Which approach is best to share this data effectively?
hard
A. Write the list to a local file and read it in the next task
B. Pass the list directly as a Python variable between tasks
C. Use XComs to push and pull the list between tasks
D. Serialize the list as JSON string and store it in an Airflow Variable

Solution

  1. Step 1: Understand data sharing options

    Airflow Variables are for small strings; passing Python variables directly is not possible between tasks.
  2. Step 2: Identify best practice for complex data

    XComs are designed to share data like lists between tasks efficiently and safely.
  3. Final Answer:

    Use XComs to push and pull the list between tasks -> Option C
  4. Quick Check:

    XComs = best for task-to-task data sharing [OK]
Hint: Use XComs for complex data sharing between tasks [OK]
Common Mistakes:
  • Trying to pass Python variables directly
  • Using Variables for large or complex data
  • Using local files which break portability
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard