๐Ÿ“Š Data Engineering

Airflow

Apache Airflow

A workflow orchestration platform. Defines pipelines as DAGs.

Detailed Explanation

Apache Airflow is an open-source platform for programmatically authoring, scheduling, and monitoring workflows. Developed at Airbnb and donated to the Apache Foundation in 2016, it is currently the most widely used workflow orchestration tool in the data engineering field.

The core concept of Airflow is the DAG (Directed Acyclic Graph). A DAG represents the dependencies between tasks as a directed acyclic graph and is defined in Python code. This allows the execution order, retry policies, and alert settings of complex data pipelines to be managed as code, which makes version control and collaboration easier.

Airflow provides a rich set of Operators for integrating with various systems. From basic Operators such as BashOperator and PythonOperator to Operators dedicated to cloud services such as BigQueryOperator and S3ToRedshiftOperator, you can easily build pipelines that connect various data sources and destinations.

As execution environments, it supports SequentialExecutor (for development), LocalExecutor (small-scale), CeleryExecutor (distributed processing), KubernetesExecutor (container-based), and others. Managed services such as AWS MWAA, Google Cloud Composer, and Astronomer are also available, which can reduce the operational burden.

Code Example

Python Click to copy
# dags/etl_pipeline.py
# ์ผ์ผ ETL ํŒŒ์ดํ”„๋ผ์ธ DAG ์˜ˆ์ œ

from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.operators.bash import BashOperator
from airflow.providers.google.cloud.operators.bigquery import (
    BigQueryCreateEmptyTableOperator,
    BigQueryInsertJobOperator
)
from airflow.providers.google.cloud.transfers.gcs_to_bigquery import (
    GCSToBigQueryOperator
)
from airflow.utils.task_group import TaskGroup
from airflow.models import Variable

# DAG ๊ธฐ๋ณธ ์„ค์ •
default_args = {
    'owner': 'data-team',
    'depends_on_past': False,
    'email': ['data-alerts@company.com'],
    'email_on_failure': True,
    'email_on_retry': False,
    'retries': 3,
    'retry_delay': timedelta(minutes=5),
    'execution_timeout': timedelta(hours=2),
}

# DAG ์ •์˜
with DAG(
    dag_id='daily_sales_etl',
    default_args=default_args,
    description='์ผ์ผ ๋งค์ถœ ๋ฐ์ดํ„ฐ ETL ํŒŒ์ดํ”„๋ผ์ธ',
    schedule_interval='0 2 * * *',  # ๋งค์ผ ์˜ค์ „ 2์‹œ
    start_date=datetime(2024, 1, 1),
    catchup=False,
    tags=['etl', 'sales', 'production'],
    max_active_runs=1,
) as dag:

    # 1. ๋ฐ์ดํ„ฐ ์ถ”์ถœ ํƒœ์Šคํฌ
    def extract_sales_data(**context):
        """์†Œ์Šค ์‹œ์Šคํ…œ์—์„œ ๋งค์ถœ ๋ฐ์ดํ„ฐ ์ถ”์ถœ"""
        import pandas as pd
        from google.cloud import storage

        execution_date = context['ds']

        # API์—์„œ ๋ฐ์ดํ„ฐ ์ถ”์ถœ (์˜ˆ์‹œ)
        # sales_data = fetch_from_api(execution_date)

        # GCS์— ์ €์žฅ
        bucket_name = Variable.get('gcs_bucket')
        blob_path = f'raw/sales/{execution_date}/data.parquet'

        print(f"Extracted sales data for {execution_date}")
        return blob_path

    extract_task = PythonOperator(
        task_id='extract_sales_data',
        python_callable=extract_sales_data,
        provide_context=True,
    )

    # 2. ๋ฐ์ดํ„ฐ ๊ฒ€์ฆ ํƒœ์Šคํฌ ๊ทธ๋ฃน
    with TaskGroup(group_id='data_validation') as validation_group:

        def validate_row_count(**context):
            """ํ–‰ ์ˆ˜ ๊ฒ€์ฆ"""
            ti = context['ti']
            blob_path = ti.xcom_pull(task_ids='extract_sales_data')
            # ์‹ค์ œ ๊ฒ€์ฆ ๋กœ์ง
            print(f"Validating row count for {blob_path}")

        def validate_schema(**context):
            """์Šคํ‚ค๋งˆ ๊ฒ€์ฆ"""
            ti = context['ti']
            blob_path = ti.xcom_pull(task_ids='extract_sales_data')
            print(f"Validating schema for {blob_path}")

        row_count_check = PythonOperator(
            task_id='check_row_count',
            python_callable=validate_row_count,
        )

        schema_check = PythonOperator(
            task_id='check_schema',
            python_callable=validate_schema,
        )

        [row_count_check, schema_check]

    # 3. BigQuery ๋กœ๋“œ ํƒœ์Šคํฌ
    load_to_bigquery = GCSToBigQueryOperator(
        task_id='load_to_bigquery',
        bucket='{{ var.value.gcs_bucket }}',
        source_objects=['raw/sales/{{ ds }}/data.parquet'],
        destination_project_dataset_table='analytics.raw_sales',
        source_format='PARQUET',
        write_disposition='WRITE_APPEND',
        create_disposition='CREATE_IF_NEEDED',
    )

    # 4. ๋ณ€ํ™˜ ์ฟผ๋ฆฌ ์‹คํ–‰
    transform_query = """
    INSERT INTO `analytics.sales_daily_summary`
    SELECT
        DATE('{{ ds }}') as report_date,
        product_category,
        SUM(amount) as total_sales,
        COUNT(DISTINCT customer_id) as unique_customers,
        COUNT(*) as transaction_count
    FROM `analytics.raw_sales`
    WHERE DATE(created_at) = '{{ ds }}'
    GROUP BY product_category
    """

    transform_task = BigQueryInsertJobOperator(
        task_id='transform_data',
        configuration={
            'query': {
                'query': transform_query,
                'useLegacySql': False,
            }
        },
    )

    # 5. dbt ์‹คํ–‰ (์„ ํƒ์ )
    run_dbt = BashOperator(
        task_id='run_dbt_models',
        bash_command='cd /opt/dbt && dbt run --models sales_marts --target prod',
    )

    # 6. ์™„๋ฃŒ ์•Œ๋ฆผ
    def send_completion_notification(**context):
        """Slack ์•Œ๋ฆผ ์ „์†ก"""
        from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook

        slack_hook = SlackWebhookHook(
            slack_webhook_conn_id='slack_webhook'
        )
        slack_hook.send(
            text=f"Daily Sales ETL completed for {context['ds']}"
        )

    notify_task = PythonOperator(
        task_id='send_notification',
        python_callable=send_completion_notification,
        trigger_rule='all_success',
    )

    # ํƒœ์Šคํฌ ์˜์กด๊ด€๊ณ„ ์ •์˜
    extract_task >> validation_group >> load_to_bigquery >> transform_task >> run_dbt >> notify_task

How It's Used in Practice

Data Engineer: "We now have more than 50 batch jobs managed with cron, so it's hard to keep track of the dependencies."

Tech Lead: "If you migrate to Airflow, you can see the status of the entire pipeline at a glance in the DAG UI. Failed tasks are also retried automatically."

Data Engineer: "How would we operate it? Do we have to install it ourselves?"

Tech Lead: "If you use Cloud Composer, you can operate it conveniently as a managed service. If you just upload the DAG code to GCS, it is deployed automatically."

Interviewer: "What should you be careful about when processing a large number of tasks in parallel in Airflow?"

Candidate: "You need to tune settings such as parallelism, dag_concurrency, and max_active_runs. It is also a good idea to configure Pools while taking the external system's Rate Limit into account."

Interviewer: "What about cautions for Backfill?"

Candidate: "If depends_on_past is True, runs execute sequentially and may take a long time, and when catchup=True is set, DAG Runs are created for every date starting from the past, so it must be used carefully."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "This DAG has a heavy library import inside the PythonOperator. It can affect scheduler performance."

Developer: "How can we improve it?"

Reviewer: "It's better to move the import inside the function, or to separate heavy work into KubernetesPodOperator. Also, add an execution_timeout setting to prevent tasks from running indefinitely."

Cautions

Related Terms

Learn More