Airflow & Orchestration
Airflow in Production - What the Documentation Does Not Tell You
Running Airflow Locally Is Straightforward. Running It Reliably in Production Is a Different Problem Entirely.

TL;DR
- Connections created in the Airflow UI are stored in the metadata database — they are not version controlled, not auditable, and disappear when you redeploy; define connections as code or environment variables
- Airflow Variables are stored plaintext in the metadata database by default — do not put secrets there; use a secrets backend like AWS SSM, HashiCorp Vault, or GCP Secret Manager
TriggerDagRunOperatorcan create invisible coupling when used with its defaultwait_for_completion=Falsebehavior—the triggering task succeeds without waiting for the downstream DAG; when you need execution-state propagation, usewait_for_completion=Truewith explicitallowed_statesandfailed_states, or useExternalTaskSensorwhen a sensor-based dependency is a better fit.- SLA misses do not alert anyone by default — they appear in the UI but require explicit callback configuration to fire an alert
- DAG parsing time is the Airflow scheduler’s hidden bottleneck — a DAG file that takes 2 seconds to parse on a scheduler with 200 DAGs adds 400 seconds of parsing overhead per cycle
The Airflow documentation teaches you how to build DAGs. It does not teach you how to keep them running.
The daily revenue pipeline had been running for eight months. Every morning at 6 AM, green.
One Tuesday, the database connection credentials rotated. The connection in the Airflow UI was not updated. The pipeline failed silently — the task showed failed, but no alert fired because the SLA callback had never been configured.
The stakeholder found out at 9 AM when the dashboard hadn’t updated. By then, three hours of decisions had been made on yesterday’s data.
The fix was two minutes: update the connection, rerun the task. The discovery took three hours.
Both problems — unmanaged connections and missing alerts — are mentioned nowhere in the Airflow getting-started guide.
Connection Management That Does Not Break
The UI Connection Problem
The Airflow UI connection manager is convenient for development. In production it has four problems that compound over time.
Connections are stored in the metadata database. When you redeploy Airflow with a fresh database, the connections are gone. When you migrate to a new Airflow instance, you have to recreate them manually. When credentials rotate, you update them by hand in the UI with no audit trail.
Connections created in the UI are also invisible to version control. There is no record of when a connection was created, who created it, or what it previously pointed to. If a connection breaks, the only way to know what it looked like before is to remember or check database backups.
Defining Connections as Code
The production pattern: define connections in environment variables or in code, never in the UI.
# Environment variable pattern — Airflow parses these automatically
# Format: AIRFLOW_CONN_{CONN_ID} = connection_uri
export AIRFLOW_CONN_MY_POSTGRES="postgresql://user:password@host:5432/dbname"
export AIRFLOW_CONN_MY_S3="aws://access_key:secret_key@/?region_name=us-east-1"
export AIRFLOW_CONN_MY_SNOWFLAKE="snowflake://user:password@account/database/schema"These live in your infrastructure configuration (Helm values, Kubernetes secrets, ECS task definitions) - version controlled, auditable, and automatically available on every deployment.
For more complex connection configurations:
# connections.py — define connections programmatically
# Run this as part of your deployment pipeline
from airflow.models import Connection
from airflow import settings
def upsert_connection(conn_id: str, conn_type: str, **kwargs):
session = settings.Session()
existing = session.query(Connection).filter(
Connection.conn_id == conn_id
).first()
if existing:
for key, val in kwargs.items():
setattr(existing, key, val)
else:
conn = Connection(conn_id=conn_id, conn_type=conn_type, **kwargs)
session.add(conn)
session.commit()
session.close()
upsert_connection(
conn_id="prod_postgres",
conn_type="postgres",
host=os.environ["DB_HOST"],
login=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
schema=os.environ["DB_NAME"],
port=5432
)Run this during deployment. Connections are always in sync with your infrastructure configuration. Credential rotation becomes an environment variable update, not a UI visit.
Testing Connections Before They Fail in Production
# Test a connection programmatically — use in CI or deployment verification
from airflow.hooks.base import BaseHook
def verify_connection(conn_id: str) -> bool:
try:
hook = BaseHook.get_connection(conn_id)
print(f"Connection {conn_id}: host={hook.host}, schema={hook.schema}")
return True
except Exception as e:
print(f"Connection {conn_id} failed: {e}")
return False
# Run after deployment
assert verify_connection("prod_postgres"), "Database connection failed post-deploy"
assert verify_connection("prod_s3"), "S3 connection failed post-deploy"This catches the credential rotation problem before the scheduler does.
Variables and Secrets Done Correctly
Why Airflow Variables Are Not a Secrets Store
Airflow Variables are a convenient key-value store accessible from any DAG. They are also stored plaintext in the metadata database by default. Anyone with database access can read them. They are logged in task logs when accessed with Variable.get(). They appear in the Airflow UI to any user with Variable read permission.
For configuration values — environment names, non-sensitive parameters, feature flags — Variables are fine. For secrets — API keys, database passwords, connection strings — they are not appropriate.
# Fine: non-sensitive configuration
from airflow.models import Variable
env = Variable.get("environment", default_var="production")
batch_size = int(Variable.get("ingestion_batch_size", default_var="1000"))
# Not fine: secrets
api_key = Variable.get("stripe_api_key") # plaintext in DB and logsThe Secrets Backend Pattern
Airflow’s secrets backend integrates with external secret managers so that Variable.get() and Connection.get() transparently fetch from your secret store instead of the metadata database.
# airflow.cfg or environment variable configuration
# AWS SSM Parameter Store
[secrets]
backend = airflow.providers.amazon.aws.secrets.systems_manager.SystemsManagerParameterStoreBackend
backend_kwargs = {"connections_prefix": "/airflow/connections", "variables_prefix": "/airflow/variables", "profile_name": null}
# HashiCorp Vault
[secrets]
backend = airflow.providers.hashicorp.secrets.vault.VaultBackend
backend_kwargs = {"connections_path": "connections", "variables_path": "variables", "mount_point": "airflow", "url": "http://vault:8200"}With the secrets backend configured, Variable.get("stripe_api_key") fetches from SSM or Vault — never stored in the metadata database, never logged, rotatable without an Airflow restart.
Environment Variables as the Simplest Safe Option
For teams without an existing secrets manager, environment variables are the next best option:
import os
# Read secrets from environment - never from Airflow Variables
stripe_api_key = os.environ["STRIPE_API_KEY"]
db_password = os.environ["DB_PASSWORD"]
# Inject these via your infrastructure layer:
# Kubernetes Secrets → envFrom
# AWS ECS → secrets in task definition
# Docker Compose → env_fileThe environment variable pattern is simpler than a secrets backend and meaningfully more secure than Airflow Variables for secret values.
DAG Dependencies That Work at Scale
The TriggerDagRunOperator Trap
TriggerDagRunOperator starts another DAG. With its default wait_for_completion=False, the triggering task succeeds after triggering the downstream DAG without waiting for its final state. If the downstream DAG subsequently fails, that failure does not make the already-completed trigger task fail.
# This task succeeds as soon as it fires the trigger
# It does NOT wait for pipeline_b to complete
trigger = TriggerDagRunOperator(
task_id="trigger_pipeline_b",
trigger_dag_id="pipeline_b",
wait_for_completion=False, # default behavior
)
trigger = TriggerDagRunOperator(
task_id="trigger_pipeline_b",
trigger_dag_id="pipeline_b",
wait_for_completion=True,
allowed_states=["success"],
failed_states=["failed", "upstream_failed"],
)With wait_for_completion=True, the trigger task waits for the triggered DAG to reach a terminal state. allowed_states defines which states are treated as successful, while failed_states defines which states cause the trigger task to fail.
The result: pipeline_a shows green while pipeline_b is still running or has failed. If downstream tasks in pipeline_a depend on the output of pipeline_b, they will run before pipeline_b has produced that output.
Setting wait_for_completion=True fixes the propagation problem, but introduces a different trade-off: the trigger task remains active while it waits for the downstream DAG. In high-concurrency environments, long-running waits can increase resource or pool pressure, so this pattern should be evaluated against the executor and concurrency configuration.
ExternalTaskSensor With Timeout
The more robust pattern for cross-DAG dependencies:
from airflow.sensors.external_task import ExternalTaskSensor
from datetime import timedelta
# Wait for a specific task in another DAG to complete
# before proceeding in this DAG
wait_for_upstream = ExternalTaskSensor(
task_id="wait_for_pipeline_b",
external_dag_id="pipeline_b",
external_task_id="final_validation",
execution_delta=timedelta(hours=0), # same execution date
timeout=3600, # fail after 1 hour of waiting
poke_interval=60, # check every 60 seconds
mode="reschedule", # release worker slot between checks
soft_fail=False, # hard fail if timeout reached
)Critical configuration points:
mode="reschedule" releases the worker slot between pokes — without this, the sensor holds a slot for its entire wait duration and can starve other tasks of workers.
timeout is non-optional in production. A sensor without a timeout will wait indefinitely if the upstream DAG never completes — silently blocking downstream work and consuming a slot forever.
execution_delta must match the scheduling relationship between DAGs. If pipeline_a runs at 6 AM and depends on pipeline_bwhich ran at 5 AM, execution_delta=timedelta(hours=1).
Datasets as a Decoupled Dependency Signal
Airflow 2.4+ introduced Datasets as a first-class dependency mechanism. A DAG declares which datasets it produces (outlets) and which it consumes (inlets). Airflow schedules the consuming DAG automatically when all its inlet datasets have been updated.
from airflow.datasets import Dataset
# Producer DAG
transactions_dataset = Dataset("s3://bucket/transactions/")
with DAG("pipeline_b", schedule=timedelta(hours=1)) as dag:
process = PythonOperator(
task_id="process_transactions",
python_callable=run_processing,
outlets=[transactions_dataset]
)
# Consumer DAG - scheduled automatically when transactions_dataset updates
with DAG("pipeline_a", schedule=[transactions_dataset]) as dag:
analyze = PythonOperator(
task_id="analyze_results",
python_callable=run_analysis,
)Datasets decouple the scheduling relationship from execution time — pipeline_a runs when its data is ready, not on a fixed schedule that may or may not align with pipeline_b's completion time. This is more robust than time-based ExternalTaskSensor for pipelines with variable execution duration.
Monitoring Setup That Actually Alerts
SLA Misses Without Callbacks Are Silent
An SLA miss in Airflow appears as an orange indicator in the UI and an entry in the SLA Misses table. It does not send an email, trigger a webhook, or fire a PagerDuty alert by default.
The number of teams who have configured SLA on their DAGs without configuring the callback — and discovered this when a missed SLA caused a stakeholder incident — is large.
from datetime import timedelta
with DAG(
dag_id="revenue_pipeline",
schedule_interval="0 6 * * *",
sla_miss_callback=None, # ← this is the default - silent
) as dag:
...SLA Callback Configuration
from airflow.models import TaskInstance, SlaMiss
from airflow.utils.email import send_email
import logging
def sla_miss_alert(
dag,
task_list,
blocking_task_list,
slas: list[SlaMiss],
blocking_tis: list[TaskInstance]
):
"""Called by Airflow when an SLA is missed."""
dag_id = dag.dag_id
details = "\n".join([
f" Task: {sla.task_id} | Execution: {sla.execution_date}"
for sla in slas
])
# Option 1: email
send_email(
to=["data-team@company.com"],
subject=f"SLA MISS: {dag_id}",
html_content=f"<pre>SLA missed:\n{details}</pre>"
)
# Option 2: Slack via webhook
import requests
requests.post(
os.environ["SLACK_WEBHOOK_URL"],
json={"text": f"SLA MISS: `{dag_id}`\n```{details}```"}
)
logging.warning(f"SLA miss on {dag_id}: {details}")
with DAG(
dag_id="revenue_pipeline",
schedule_interval="0 6 * * *",
sla_miss_callback=sla_miss_alert, # ← now it actually alerts
default_args={
"sla": timedelta(hours=2) # task must complete within 2 hours
}
) as dag:
...Task-Level Alerting
SLA misses catch latency violations. Task-level callbacks catch failures:
def task_failure_alert(context):
"""Called on any task failure."""
task_id = context["task_instance"].task_id
dag_id = context["task_instance"].dag_id
exec_date = context["execution_date"]
log_url = context["task_instance"].log_url
import requests
requests.post(
os.environ["SLACK_WEBHOOK_URL"],
json={
"text": (
f"TASK FAILED: `{dag_id}.{task_id}`\n"
f"Execution: {exec_date}\n"
f"Logs: {log_url}"
)
}
)
# Apply to all tasks via default_args
default_args = {
"on_failure_callback": task_failure_alert,
"retries": 2,
"retry_delay": timedelta(minutes=5),
}The combination of SLA callbacks (latency violations) and failure callbacks (task errors) covers the two primary failure modes. Neither is configured by default.
The Scheduler — What Goes Wrong and Why
DAG Parsing Time
The Airflow scheduler parses every DAG file on a configurable interval. If DAG parsing is slow, the scheduler falls behind — it may take minutes to pick up new DAG runs or respond to manual triggers.
The most common causes of slow parsing:
- Database queries at import time (a DAG file that queries a database to generate task lists)
- Heavy imports at module level (importing large libraries for every parse cycle)
- Complex dynamic DAG generation logic
# WRONG — database call at import time, runs on every parse cycle
from mydb import get_table_list
tables = get_table_list() # ← called every 30 seconds by the scheduler
for table in tables:
with DAG(f"process_{table}", ...) as dag:
...
# BETTER - read from a static config file or environment variable
import json
with open("/opt/airflow/config/tables.json") as f:
tables = json.load(f)
# Or use the @dag decorator with deferred evaluationMonitor DAG parsing time in the Airflow metrics or logs:
# Check parsing time in Airflow logs
grep "DAG File.*dag.py" airflow-scheduler.log | tail -20
# Look for lines like: DAG File Processing Stats: ... duration=2.3s
# Any DAG file taking over 1 second to parse is a performance riskA DAG file that takes 2 seconds to parse on a scheduler with 100 DAGs adds 200 seconds of overhead per parsing cycle. This compounds silently — the scheduler just appears slow.
Zombie Tasks
A zombie task is a task that is marked as running in the metadata database but whose worker process has died. The scheduler detects and clears zombie tasks on a configurable interval, but until it does, the task slot is occupied and downstream tasks cannot start.
# airflow.cfg settings that affect zombie detection
[scheduler]
zombie_detection_interval = 10 # seconds between zombie checks (default: 10)
zombie_threshold = 300 # seconds before a task is considered zombie (default: 300)Zombie tasks are most common when:
- Workers are killed abruptly (OOM kills, node failures, spot instance termination)
- Tasks exceed their memory limit without raising an exception
- Network failures prevent the worker from communicating its status to the scheduler
If you see tasks stuck in “running” state for longer than their expected duration, zombie detection is the first thing to check.
The Airflow Production Checklist
Connections
□ No connections created manually in the UI
□ Connections defined via environment variables or code
□ Connection verification runs as part of deployment
□ Credential rotation procedure documented and tested
Secrets
□ Airflow Variables not used for secrets
□ Secrets backend configured (SSM, Vault, or env vars)
□ Secret access audited — only DAGs that need a secret can access it
DAG dependencies
□ TriggerDagRunOperator with wait_for_completion=False audited
□ ExternalTaskSensor configured with timeout and mode="reschedule"
□ Cross-DAG dependencies documented — failure cascade paths mapped
Monitoring
□ SLA miss callback configured and tested
□ Task failure callback configured on all critical DAGs
□ DAG parsing time monitored — alert if >1 second per file
□ Zombie detection interval appropriate for workload
Scheduler health
□ No database queries at DAG file import time
□ Dynamic DAGs use static config, not runtime DB queries
□ Worker pool sized for peak concurrency — not average
Documentation
□ On-call runbook covers: stuck tasks, SLA misses, scheduler lag
□ Credential rotation procedure tested before the first rotation
□ DAG ownership documented — every DAG has a named owner
Final Takeaway
Airflow’s documentation teaches you how to write DAGs. Production teaches you everything else — connection management that survives deployments, secrets handling that doesn’t log credentials, dependency patterns that propagate failures correctly, and alerting that actually alerts.
Each of the problems above is predictable and preventable. None of them are obscure edge cases. They are the things that break in the first six months of any production Airflow deployment.
Core Principle
Airflow will run your DAGs.
It will not protect you from
silent failures, unmanaged connections,
plaintext secrets, or missing alerts.
That is your job.
Configure it accordingly.Next in Series
Debugging Spark Failures Systematically - A Repeatable Process
Your pipelines are scheduled and running.
Next: what to do when they fail — a systematic debugging process for Spark jobs that finds the root cause every time. Reading the Spark UI effectively, interpreting executor logs, distinguishing the actual failure from the cascade of secondary failures it triggers, and the specific patterns that point to each failure class.