📊Data Engineering

Data Pipeline

Data Pipeline

An automated workflow that collects, transforms, and stores data. Forms the ETL/ELT process.

Detailed Explanation

A Data Pipeline is an automated workflow that extracts data from a source, transforms it, and stores it in a destination. It is implemented with the ETL (Extract-Transform-Load) or ELT (Extract-Load-Transform) pattern, and supports both batch processing and real-time streaming. As a core infrastructure of data engineering, it is essential for data warehouses, data lakes, and generating ML training data.

The core concept of a pipeline is the DAG (Directed Acyclic Graph). Tasks and their dependencies are defined as a directed acyclic graph, specifying which task must be completed before the next task can run. This makes parallel processing, retries, and backfill possible. Apache Airflow is the de facto standard, and there are also modern alternatives such as Prefect and Dagster.

ETL is the traditional approach, transforming before loading, while ELT uses the powerful compute of cloud data warehouses (Snowflake, BigQuery) to transform after loading. Recently, separating the Transform layer with dbt and integrating data quality validation through Great Expectations have become commonplace. Streaming pipelines are implemented with Kafka, Flink, and Spark Streaming.

A good pipeline is idempotent, atomic, and monitorable. Idempotency guarantees the same result even when run multiple times on the same input. It is essential for retries on failure to be safe. Data engineering teams must continuously improve the reliability, efficiency, and maintainability of pipelines.

Code Example

Apache Airflow DAG
# Apache Airflow 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.snowflake.operators.snowflake import SnowflakeOperator
from airflow.providers.slack.operators.slack_webhook import SlackWebhookOperator
from airflow.utils.task_group import TaskGroup

# DAG 기본 설정
default_args = {
    'owner': 'data-engineering',
    'depends_on_past': False,
    'email_on_failure': True,
    'email': ['alerts@company.com'],
    'retries': 3,
    'retry_delay': timedelta(minutes=5),
    'execution_timeout': timedelta(hours=2),
}

dag = DAG(
    dag_id='daily_sales_pipeline',
    default_args=default_args,
    description='일별 매출 데이터 ETL 파이프라인',
    schedule_interval='0 2 * * *',  # 매일 02:00 UTC
    start_date=datetime(2024, 1, 1),
    catchup=False,
    tags=['sales', 'etl', 'daily'],
    max_active_runs=1,
)

# 1. 데이터 추출 (Extract)
def extract_from_api(**context):
    """API에서 매출 데이터 추출"""
    import requests
    execution_date = context['ds']
    response = requests.get(
        f"https://api.internal/sales/{execution_date}",
        headers={"Authorization": "Bearer {{ var.value.api_token }}"}
    )
    data = response.json()
    # XCom으로 다음 태스크에 전달
    context['ti'].xcom_push(key='record_count', value=len(data['records']))
    return len(data['records'])

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

# 2. 데이터 품질 검증 (Validation)
validate_task = BashOperator(
    task_id='validate_data_quality',
    bash_command='''
    cd /opt/data-quality && \
    great_expectations checkpoint run sales_checkpoint \
    --data-asset-name raw_sales_{{ ds_nodash }} \
    || exit 1
    ''',
    dag=dag,
)

# 3. Transform + Load (dbt 활용)
with TaskGroup(group_id='transform_load', dag=dag) as transform_group:
    # Staging 모델
    dbt_staging = BashOperator(
        task_id='dbt_staging',
        bash_command='''
        cd /opt/dbt/sales_project && \
        dbt run --select staging.stg_sales \
        --vars '{"run_date": "{{ ds }}"}'
        ''',
    )

    # Mart 모델
    dbt_marts = BashOperator(
        task_id='dbt_marts',
        bash_command='''
        cd /opt/dbt/sales_project && \
        dbt run --select marts.fct_daily_sales marts.dim_products \
        --vars '{"run_date": "{{ ds }}"}'
        ''',
    )

    # dbt 테스트
    dbt_test = BashOperator(
        task_id='dbt_test',
        bash_command='''
        cd /opt/dbt/sales_project && \
        dbt test --select staging marts
        ''',
    )

    dbt_staging >> dbt_marts >> dbt_test

# 4. 집계 테이블 업데이트 (Snowflake MERGE)
aggregate_task = SnowflakeOperator(
    task_id='update_aggregates',
    snowflake_conn_id='snowflake_prod',
    sql='''
    MERGE INTO gold.daily_sales_summary target
    USING (
        SELECT
            sale_date,
            SUM(amount) as total_sales,
            COUNT(*) as transaction_count,
            COUNT(DISTINCT customer_id) as unique_customers
        FROM gold.fct_daily_sales
        WHERE sale_date = '{{ ds }}'
        GROUP BY sale_date
    ) source
    ON target.sale_date = source.sale_date
    WHEN MATCHED THEN UPDATE SET
        total_sales = source.total_sales,
        transaction_count = source.transaction_count,
        unique_customers = source.unique_customers,
        updated_at = CURRENT_TIMESTAMP()
    WHEN NOT MATCHED THEN INSERT (
        sale_date, total_sales, transaction_count, unique_customers, updated_at
    ) VALUES (
        source.sale_date, source.total_sales,
        source.transaction_count, source.unique_customers, CURRENT_TIMESTAMP()
    );
    ''',
    dag=dag,
)

# 5. 완료 알림
success_alert = SlackWebhookOperator(
    task_id='slack_success_alert',
    slack_webhook_conn_id='slack_webhook',
    message='''
:white_check_mark: *일별 매출 파이프라인 완료*
- 실행일: {{ ds }}
- 처리 건수: {{ ti.xcom_pull(task_ids='extract_sales_data', key='record_count') }}
- 소요 시간: {{ task_instance.duration }}초
    ''',
    dag=dag,
)

# DAG 의존성 정의 (ETL 흐름)
extract_task >> validate_task >> transform_group >> aggregate_task >> success_alert

Practical Conversation

PM: The daily pipeline failed yesterday. What was the cause?
Data Engineer: A timeout occurred in the extract stage due to API server maintenance. It failed after 3 retries, and we recovered it with a backfill this morning. We met the SLA.
PM: How can we prevent this kind of situation?
Data Engineer: I'll set up a channel for sharing maintenance schedules with the API team, and add graceful degradation logic to the pipeline. The approach is to proceed with empty data and catch up in the next run.
Interviewer: What is the difference between ETL and ELT, and when do you use each?
Candidate: ETL transforms before loading, and is suitable when data warehouse capacity/cost is limited. ELT transforms after loading, and uses the powerful compute of cloud DWs such as Snowflake/BigQuery. In modern stacks, the ELT + dbt combination is common.
Interviewer: Why is idempotency important?
Candidate: It guarantees the same result even when run multiple times on the same input. Data consistency can be maintained even for retries after failure, backfills, and duplicate runs. It is implemented with MERGE/UPSERT and partition overwrite patterns.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Developer: If I set catchup=True, will past data also be processed automatically?
Senior: Yes, but be careful. It runs for every date from start_date to the present, so if misconfigured, thousands of tasks pile up in the queue. Limit it with max_active_runs=1, and set it to True only when necessary.
Developer: When is depends_on_past used?
Senior: Use it when you want the next date's run to execute only if the previous date's run succeeded. It's useful for cumulative aggregations or sequential dependencies. But once one run fails, all subsequent runs get blocked, so use it carefully.

Cautions

  • Ensure idempotency. Data duplication or inconsistency must not occur during retries or backfills.
  • When using catchup=True, set start_date carefully. The entire past period may be executed.
  • Do not pass large data through XCom. Because it is stored in the metadata DB, pass only paths or keys.
  • Integrate data quality validation into the pipeline. Using Great Expectations and dbt tests is recommended.
  • Set up failure alerts and SLA monitoring. This minimizes the impact of data delays on the business.

Learn More