Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 2

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

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.

Terminal 1
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
END

02. 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.

Python · alert_receiver.py
"""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()
Terminal 3
cd orchestration-lab && source env.sh
python alert_receiver.py

03. 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.

Python · airflow/dags/partner_feed.py
"""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 poke mode it holds a worker slot for its whole wait; mode="reschedule" frees the slot between checks. With deferrable=True the 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=3600 fails 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_timeout stops an attempt after 15 seconds, then retries=2 and retry_delay give it two more tries. fetch_rate uses 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 add retry_exponential_backoff=True so that the waits grow.
  • Callbacks send the alerts. on_retry_callback fires after each failed attempt that will be retried, on_failure_callback when a task fails for good. Both post only small metadata. AirflowFailException fails 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 that publish updates the asset partner_totals. When the task succeeds, Airflow records an asset event, and outlet_events attaches 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.

Python · airflow/dags/partner_report.py
"""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.

Terminal 2 (after Ctrl+C)
source env.sh        # picks up the two new variables
airflow standalone
Terminal 1
mkdir -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}'
Expected output
partner_feed False
partner_report False

05. 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.

Terminal 1
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 TriggererJob
Expected output
fetch_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.

Terminal 1
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'
done
Expected output
partner_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"
Expected output (terminal 3)
ALERT retry partner_feed.fetch_rate try=1 AirflowTaskTimeout
ALERT retry partner_feed.fetch_rate try=2 ConnectionError

Each 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.

Terminal 1
./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/*.log
Expected output
partner_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.

Terminal 1
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__
Expected output
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"
}
1
Expected output (terminal 3, all lines so far)
ALERT 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 AirflowFailException

The 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

Practice check · 3 questions

Sensors, retries, assets and alerts

Each question changes one detail of partner_feed or its setup.

Q1. You run only the scheduler, the DAG processor and the API server, without a triggerer, and trigger `partner_feed`. What happens to `wait_for_file`?
Q2. You change `fetch_rate` to `retries=1`, keeping the timeout. What happens in a run for 10 November, and which alerts arrive?
Q3. `publish` fails for 11 November and is then fixed and cleared, and it succeeds on the rerun. How many `partner_report` runs exist now?
Practice only: not graded, not saved, not evidence.

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 with AirflowFailException;
  • 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check