Data Pipeline
Data Pipeline
An automated workflow that collects, transforms, and stores data. Forms the ETL/ELT process.
Data Pipeline
An automated workflow that collects, transforms, and stores data. Forms the ETL/ELT process.
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.
# 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
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free