Lab: Retries, Sensors, Assets and Alerts
Make an Airflow 3 pipeline survive the real world: a deferrable sensor that waits in the triggerer for a partner file, an API call that hangs and then fails until an execution timeout and retries get it through, an asset that triggers a downstream DAG, and failure callbacks that post alerts to a local receiver you can read.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Start a local alert receiver
- Step 2: Write the producer DAG
- Step 3: Write the consumer DAG and restart Airflow
- Step 4: Trigger a run and watch the sensor wait
- Step 5: Drop the file and watch the retries
- Step 6: See the asset trigger the report
- Step 7: Break it and receive an alert
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Pipeline Orchestration
- What an Orchestrator Should and Should Not Do Concept · 20 min
- Lab: A First Airflow 3 DAG with the TaskFlow API Lab · 30 min
- Logical Dates, Partitions and Backfills Worked example · 25 min
- Lab: Retries, Sensors, Assets and Alerts Lab · 25 min
- The Asset-Centric Alternative: Dagster Worked example · 20 min
- Check: Orchestration Failure Scenarios Knowledge check · 8 questions
What you will learn
- Configure retries, timeouts, failure alerts, sensors and asset-based triggers, passing only small metadata (not datasets) between tasks.
Prerequisites: ETL/ELT Pipeline Design
01. Goal and setup
A partner sends a CSV file of orders each day, at no fixed time. Your pipeline must wait for it, convert the amounts with an exchange rate from the partner's API, which sometimes hangs and sometimes returns errors, and publish a small summary that a report DAG picks up as soon as it changes. When something fails for good, a person must hear about it. You will watch each of these happen: a sensor that waits without holding a worker, a retry after a timeout and after an error, an asset that triggers a second DAG, and an alert delivered to a small HTTP receiver on your machine.
You need the lab from the first Airflow lab: the orch-pg container, env.sh, wait_for_runs.sh and Airflow 3.4.0 running with airflow standalone. This lab uses three terminals, all in orchestration-lab. First add two settings to env.sh: a file-system connection whose path extra is the folder partner files land in, and the address alerts are posted to.
cat >> env.sh <<'END'
# Lesson 4: the folder partner files land in, and where alerts are posted
export AIRFLOW_CONN_PARTNER_FILES="fs://?path=$PWD/data/incoming"
export ALERT_URL=http://127.0.0.1:8099/alerts
END02. Step 1: Start a local alert receiver
In production an alert goes to Slack, email or a paging service; Airflow providers include notifiers for many of them. Here a 20-line HTTP server stands in for that service. It prints one line per alert and keeps every alert in alerts.jsonl, so you can check exactly what was sent. Save it as alert_receiver.py and start it in a third terminal.
"""A tiny local alert endpoint: prints and stores every alert it receives."""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
alert = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
with open("alerts.jsonl", "a") as log:
log.write(json.dumps(alert) + "\n")
print("ALERT {event} {dag_id}.{task_id} try={try_number} {error_type}".format(
**alert), flush=True)
self.send_response(204)
self.end_headers()
def log_message(self, *args): # silence the default access log
pass
HTTPServer(("127.0.0.1", 8099), Handler).serve_forever()cd orchestration-lab && source env.sh
python alert_receiver.py03. Step 2: Write the producer DAG
Save this as airflow/dags/partner_feed.py. It has three tasks: wait for the file, fetch the rate, publish the summary. You trigger each run yourself in this lab, with schedule=None, so that nothing else runs while you watch; in production it would have a daily timetable as in the first lab.
"""Wait for a partner file, call a flaky API, publish an asset, alert on trouble."""
import json
import os
import time
import urllib.request
from datetime import timedelta
from pathlib import Path
import pendulum
from airflow.providers.standard.sensors.filesystem import FileSensor
from airflow.sdk import Asset, dag, task
from airflow.sdk.exceptions import AirflowFailException
DATA = Path(os.environ["LAB_DATA"])
PARTNER_TOTALS = Asset("partner_totals")
def alert(event):
"""Build a callback that posts one small JSON alert to ALERT_URL."""
def callback(context):
ti, error = context["ti"], context.get("exception")
payload = {"event": event, "dag_id": ti.dag_id, "task_id": ti.task_id,
"run_id": ti.run_id, "try_number": ti.try_number,
"error_type": type(error).__name__, "error": str(error)}
request = urllib.request.Request(
os.environ["ALERT_URL"], data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"})
urllib.request.urlopen(request, timeout=5)
return callback
@dag(
schedule=None, # in this lab you trigger each run yourself
start_date=pendulum.datetime(2026, 11, 1, tz="UTC"),
default_args={"on_retry_callback": alert("retry"),
"on_failure_callback": alert("failed")},
)
def partner_feed():
wait = FileSensor(
task_id="wait_for_file",
fs_conn_id="partner_files", # base folder: AIRFLOW_CONN_PARTNER_FILES
filepath="orders_{{ ds }}.csv", # templated with the run's date
deferrable=True, # wait in the triggerer, not in a worker
poke_interval=10,
timeout=3600,
)
@task(retries=2, retry_delay=timedelta(seconds=5),
execution_timeout=timedelta(seconds=15))
def fetch_rate(*, ti) -> float:
"""A partner API that hangs on try 1 and returns 503 on try 2."""
print(f"fetch_rate try {ti.try_number}")
if ti.try_number == 1:
time.sleep(600) # a hung call: only the timeout stops it
if ti.try_number == 2:
raise ConnectionError("partner API returned 503")
return 0.92 # USD -> EUR
@task(outlets=[PARTNER_TOTALS])
def publish(rate: float, *, ds, outlet_events) -> dict:
lines = (DATA / "incoming" / f"orders_{ds}.csv").read_text().splitlines()[1:]
if not lines:
raise AirflowFailException(f"orders_{ds}.csv has a header but no rows")
total = round(sum(float(line.split(",")[1]) for line in lines) * rate, 2)
summary = {"day": ds, "rows": len(lines), "total_eur": total}
out = DATA / "clean" / f"partner_totals_{ds}.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(summary))
outlet_events[PARTNER_TOTALS].extra = summary # small metadata on the event
return summary
rate = fetch_rate()
wait >> rate # sensor first, then the API call
publish(rate)
partner_feed()- The sensor is deferrable. A sensor is a task that waits for a condition. In the default
pokemode it holds a worker slot for its whole wait;mode="reschedule"frees the slot between checks. Withdeferrable=Truethe sensor hands its wait to the triggerer, a separate process that runs many small asynchronous waits in one event loop, and holds no worker slot until the file appears.timeout=3600fails the sensor if the file never arrives. - A timeout turns a hang into a failure. A retry happens only after an attempt fails, and an attempt that hangs never fails by itself.
execution_timeoutstops an attempt after 15 seconds, thenretries=2andretry_delaygive it two more tries.fetch_rateuses the attempt number to hang on try 1 and raise a 503 error on try 2, so you see both. For a real API you might addretry_exponential_backoff=Trueso that the waits grow. - Callbacks send the alerts.
on_retry_callbackfires after each failed attempt that will be retried,on_failure_callbackwhen a task fails for good. Both post only small metadata.AirflowFailExceptionfails a task at once, without retries, because an empty file will not fill itself. - The asset carries the news, not the data.
outlets=[PARTNER_TOTALS]declares thatpublishupdates the assetpartner_totals. When the task succeeds, Airflow records an asset event, andoutlet_eventsattaches a small dictionary to it. The summary itself is in a file.
04. Step 3: Write the consumer DAG and restart Airflow
Save the consumer as airflow/dags/partner_report.py. schedule=[PARTNER_TOTALS] is data-aware scheduling: the DAG has no timetable and runs whenever the asset gets a new event. The asset is matched by its name, so both files define the same Asset("partner_totals"). triggering_asset_events gives the run the events that triggered it.
"""Runs whenever partner_feed updates the partner_totals asset."""
import pendulum
from airflow.sdk import Asset, dag, task
PARTNER_TOTALS = Asset("partner_totals")
@dag(schedule=[PARTNER_TOTALS], start_date=pendulum.datetime(2026, 11, 1, tz="UTC"))
def partner_report():
@task
def report(*, triggering_asset_events):
for event in triggering_asset_events[PARTNER_TOTALS]:
print(f"report: partner totals updated {event.extra}")
report()
partner_report()The scheduler, triggerer and workers read the new variables only at start-up, so restart Airflow: press Ctrl+C in terminal 2, then start it again. Back in terminal 1, parse the new files and unpause both DAGs.
source env.sh # picks up the two new variables
airflow standalonemkdir -p data/incoming
airflow dags reserialize > /dev/null 2>&1
airflow dags unpause partner_feed > /dev/null
airflow dags unpause partner_report > /dev/null
airflow dags list -o plain | awk '/partner/ {print $1, $4}'partner_feed False
partner_report False05. Step 4: Trigger a run and watch the sensor wait
Trigger a run for 10 November with a readable run ID, wait until the sensor is deferred, and list the task states. The last command confirms that a triggerer is alive; without one, deferred tasks just wait until their timeout.
airflow dags trigger partner_feed --logical-date 2026-11-10T00:00:00+00:00 \
--run-id feed_2026-11-10 > /dev/null 2>&1
until airflow tasks state partner_feed wait_for_file feed_2026-11-10 2>/dev/null \
| grep -q deferred; do sleep 5; done
airflow tasks states-for-dag-run partner_feed feed_2026-11-10 -o plain \
| awk 'NR > 1 {print $3, $4}' | sed 's/ *$//' | sort
airflow jobs check --job-type TriggererJobfetch_rate
publish
wait_for_file deferred
Found one alive job.deferred means the sensor checked once, found no file, and handed the wait to the triggerer. No worker is busy with it, and the downstream tasks have no state yet.
06. Step 5: Drop the file and watch the retries
Create the partner file. Within one poke_interval the trigger sees it and the sensor succeeds. Then fetch_rate hangs, is stopped by its timeout, fails with a 503 and succeeds on the third try. The loop at the end prints the key log events of each attempt.
printf 'order_id,amount_usd\nP-1,40.00\nP-2,25.50\nP-3,12.25\n' \
> data/incoming/orders_2026-11-10.csv
./wait_for_runs.sh partner_feed feed_ 1
LOGS=airflow/logs/dag_id=partner_feed/run_id=feed_2026-11-10/task_id=fetch_rate
for f in "$LOGS"/attempt=*.log; do
echo "$(basename "$f"):"
grep -o '"event":"[^"]*"' "$f" | grep -E 'try [0-9]|timed out|failed|Returned'
donepartner_feed: 1 finished run(s) whose id starts with feed_
attempt=1.log:
"event":"fetch_rate try 1"
"event":"Process timed out"
"event":"Task failed with exception"
attempt=2.log:
"event":"fetch_rate try 2"
"event":"Task failed with exception"
attempt=3.log:
"event":"fetch_rate try 3"
"event":"Done. Returned value was: 0.92"ALERT retry partner_feed.fetch_rate try=1 AirflowTaskTimeout
ALERT retry partner_feed.fetch_rate try=2 ConnectionErrorEach failed attempt produced a retry alert, and the run still succeeded. In a real deployment you might send retry notices to a log channel and page a person only on final failure.
07. Step 6: See the asset trigger the report
When publish succeeded, its asset event queued a run of partner_report. Wait for it, list the assets Airflow knows, and read the report's output.
./wait_for_runs.sh partner_report asset_triggered__ 1
airflow assets list -o plain
grep -ho 'report: [^"]*' airflow/logs/dag_id=partner_report/*/task_id=report/*.logpartner_report: 1 finished run(s) whose id starts with asset_triggered__
name uri group extra
partner_totals partner_totals asset {}
report: partner totals updated {'day': '2026-11-10', 'rows': 3, 'total_eur': 71.53}The report received three numbers through the asset event, not the data. Its run ID starts with asset_triggered__, followed by a timestamp, so it differs on your machine.
08. Step 7: Break it and receive an alert
Now send a file with a header and no rows for 11 November. The file exists, so the sensor passes; fetch_rate retries as before; publish raises AirflowFailException, which fails the task without a retry and calls on_failure_callback.
printf 'order_id,amount_usd\n' > data/incoming/orders_2026-11-11.csv
airflow dags trigger partner_feed --logical-date 2026-11-11T00:00:00+00:00 \
--run-id feed_2026-11-11 > /dev/null 2>&1
./wait_for_runs.sh partner_feed feed_ 2
airflow dags list-runs partner_feed -o plain | awk 'NR > 1 {print $2, $3}' | sort
tail -n 1 alerts.jsonl | python -m json.tool
airflow dags list-runs partner_report -o plain | grep -c asset_triggered__partner_feed: 2 finished run(s) whose id starts with feed_
feed_2026-11-10 success
feed_2026-11-11 failed
{
"event": "failed",
"dag_id": "partner_feed",
"task_id": "publish",
"run_id": "feed_2026-11-11",
"try_number": 1,
"error_type": "AirflowFailException",
"error": "orders_2026-11-11.csv has a header but no rows"
}
1ALERT retry partner_feed.fetch_rate try=1 AirflowTaskTimeout
ALERT retry partner_feed.fetch_rate try=2 ConnectionError
ALERT retry partner_feed.fetch_rate try=1 AirflowTaskTimeout
ALERT retry partner_feed.fetch_rate try=2 ConnectionError
ALERT failed partner_feed.publish try=1 AirflowFailExceptionThe failed alert names the DAG, task, run and error, which is what a person needs to start. Because publish failed, no asset event was recorded, and the report did not run a second time: still one asset-triggered run. Stop the receiver with Ctrl+C when you are done. When you have finished the Airflow lessons, stop Airflow and remove the database with docker rm -f -v orch-pg; -v also deletes its data volume.
09. Check your understanding
10. Apply it
This completes the failure path of the skill practice. In your own pipeline:
- give every task that calls an external system an
execution_timeout, retries with a delay, and a clear reason to fail fast withAirflowFailException; - replace the receiver with a real notifier, for example the Slack or SMTP notifier from a provider, and send final failures to a person;
- make your transform publish an asset, and schedule your data test or report DAG on it, passing only paths and counts in the event.
11. Review prompt
Without looking back, explain: how poke, reschedule and deferrable sensors differ in what they hold while waiting; why a retry needs a timeout to rescue a hung call; the difference between on_retry_callback and on_failure_callback; what an asset event is and when it is recorded; and why the event carries a summary rather than the data.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.