Apache Airflow
A workflow orchestration platform
A workflow orchestration platform
Apache Airflow is an open-source workflow management platform for authoring, scheduling, and monitoring data pipelines programmatically. Development began at Airbnb in 2014, it became an Apache Foundation incubator project in 2016, and it is now established as a standard tool in data engineering.
The core of Airflow is the DAG (Directed Acyclic Graph) concept. Each workflow is represented as a directed acyclic graph, where nodes represent individual tasks and edges represent dependencies between tasks. DAGs are defined in pure Python code, enabling dynamic pipeline generation, conditional execution, and the use of loops.
The architecture consists of the Scheduler, Executor, Worker, Web Server, and Metadata Database. The Scheduler parses DAGs and coordinates task execution, and the Executor determines how tasks are actually run (Local, Celery, Kubernetes, etc.). The Web Server provides a UI for monitoring and management.
Airflow has a rich Operator ecosystem. These range from general-purpose Operators such as BashOperator and PythonOperator to Operators dedicated to cloud services such as AWS, GCP, and Azure, and Operators for integrating with big data tools such as Spark and Hadoop. Hooks and Connections also manage authentication with external systems securely.
# dags/ml_training_pipeline.py
# ML ๋ชจ๋ธ ํ์ต ํ์ดํ๋ผ์ธ DAG
from datetime import datetime, timedelta
from airflow.decorators import dag, task
from airflow.providers.amazon.aws.operators.s3 import S3CreateObjectOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.operators.trigger_dagrun import TriggerDagRunOperator
from airflow.utils.trigger_rule import TriggerRule
# TaskFlow API๋ฅผ ์ฌ์ฉํ ํ๋์ ์ธ DAG ์์ฑ
@dag(
dag_id='ml_training_pipeline',
schedule_interval='@weekly',
start_date=datetime(2024, 1, 1),
catchup=False,
default_args={
'owner': 'ml-team',
'retries': 2,
'retry_delay': timedelta(minutes=10),
},
tags=['ml', 'training'],
)
def ml_training_pipeline():
@task
def prepare_training_data(execution_date: str) -> dict:
"""ํ์ต ๋ฐ์ดํฐ ์ค๋น"""
import pandas as pd
from sklearn.model_selection import train_test_split
# ๋ฐ์ดํฐ ๋ก๋ (์์)
s3_hook = S3Hook(aws_conn_id='aws_default')
data_key = f'raw/features/{execution_date}/data.parquet'
# ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ
# df = pd.read_parquet(...)
# X_train, X_test, y_train, y_test = train_test_split(...)
return {
'train_path': f's3://ml-bucket/processed/{execution_date}/train.parquet',
'test_path': f's3://ml-bucket/processed/{execution_date}/test.parquet',
'feature_count': 150,
'train_samples': 100000,
}
@task
def train_model(data_info: dict) -> dict:
"""๋ชจ๋ธ ํ์ต"""
import mlflow
from sklearn.ensemble import RandomForestClassifier
mlflow.set_tracking_uri('http://mlflow:5000')
mlflow.set_experiment('weekly-training')
with mlflow.start_run():
# ๋ชจ๋ธ ํ์ต
model = RandomForestClassifier(n_estimators=100)
# model.fit(X_train, y_train)
# ๋ฉํธ๋ฆญ ๊ธฐ๋ก
mlflow.log_params({
'n_estimators': 100,
'feature_count': data_info['feature_count'],
})
mlflow.log_metrics({
'accuracy': 0.95,
'f1_score': 0.93,
})
# ๋ชจ๋ธ ์ ์ฅ
model_uri = mlflow.sklearn.log_model(model, 'model').model_uri
return {
'model_uri': model_uri,
'accuracy': 0.95,
'f1_score': 0.93,
}
@task
def evaluate_model(model_info: dict) -> dict:
"""๋ชจ๋ธ ํ๊ฐ ๋ฐ ๊ฒ์ฆ"""
# A/B ํ
์คํธ์ฉ ๊ธฐ์ค ๋ชจ๋ธ๊ณผ ๋น๊ต
baseline_accuracy = 0.90
if model_info['accuracy'] > baseline_accuracy:
return {
'approved': True,
'model_uri': model_info['model_uri'],
'improvement': model_info['accuracy'] - baseline_accuracy,
}
else:
raise ValueError(f"Model accuracy {model_info['accuracy']} below baseline {baseline_accuracy}")
@task.branch
def check_deployment_decision(evaluation: dict) -> str:
"""๋ฐฐํฌ ์ฌ๋ถ ๊ฒฐ์ """
if evaluation['approved'] and evaluation['improvement'] > 0.02:
return 'deploy_to_production'
elif evaluation['approved']:
return 'deploy_to_staging'
else:
return 'notify_failure'
@task
def deploy_to_production(evaluation: dict):
"""ํ๋ก๋์
๋ฐฐํฌ"""
import mlflow.sagemaker
print(f"Deploying model {evaluation['model_uri']} to production")
# mlflow.sagemaker.deploy(...)
@task
def deploy_to_staging(evaluation: dict):
"""์คํ
์ด์ง ๋ฐฐํฌ"""
print(f"Deploying model {evaluation['model_uri']} to staging")
@task(trigger_rule=TriggerRule.ONE_FAILED)
def notify_failure():
"""์คํจ ์๋ฆผ"""
from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook
hook = SlackWebhookHook(slack_webhook_conn_id='slack_ml_alerts')
hook.send(text="ML Training Pipeline Failed!")
@task(trigger_rule=TriggerRule.ONE_SUCCESS)
def notify_success(**context):
"""์ฑ๊ณต ์๋ฆผ"""
from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook
hook = SlackWebhookHook(slack_webhook_conn_id='slack_ml_alerts')
hook.send(text=f"ML Training Pipeline Completed! Run: {context['run_id']}")
# DAG ํ๋ฆ ์ ์
data_info = prepare_training_data(execution_date='{{ ds }}')
model_info = train_model(data_info)
evaluation = evaluate_model(model_info)
decision = check_deployment_decision(evaluation)
# ์กฐ๊ฑด๋ถ ๋ถ๊ธฐ
prod_deploy = deploy_to_production(evaluation)
staging_deploy = deploy_to_staging(evaluation)
failure_notify = notify_failure()
success_notify = notify_success()
decision >> [prod_deploy, staging_deploy, failure_notify]
[prod_deploy, staging_deploy] >> success_notify
# DAG ์ธ์คํด์ค ์์ฑ
dag = ml_training_pipeline()
PM: "We're getting a lot of complaints that the daily morning data report comes out late."
Data engineer: "I checked Airflow and an upstream task failed at 3 a.m. and was being retried automatically. If we had set an SLA and received an alert, we could have responded quickly."
Tech lead: "Let's add SLA Miss alerts to the key DAGs and set it up so that failures notify the on-call person via PagerDuty."
Interviewer: "Explain the TaskFlow API in Airflow 2.x."
Candidate: "You can define a Python function directly as a task using the @task decorator. XCom data passing is handled implicitly, making the code much more concise, and type hints are supported. It can also be mixed with existing Operators."
Interviewer: "If you have experience operating large-scale DAGs, please share it."
Candidate: "I operated more than 500 DAGs, and optimizing DAG file parsing time was important. I minimized dynamic DAG generation, deferred heavy imports, and tuned dag_dir_list_interval."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Reviewer: "This DAG has depends_on_past=True set. Is there a reason it's needed?"
Developer: "Incremental calculation needs the previous day's data."
Reviewer: "Then I think wait_for_downstream should be set to True too. Also, it can become a bottleneck during backfill, so consider loading the initial data first with a manual trigger on the first run."