Airflow Callbacks and Alerts

Callbacks are small functions that Airflow runs when something happens to a task or a DAG, such as a failure or a success. Alerts use callbacks to tell people about problems by email or chat. Good alerts mean you hear about a failure within minutes instead of the next morning.

The Smoke Alarm Picture

A smoke alarm does nothing until smoke appears. Then it makes noise and alerts the household. A callback waits quietly and fires only when a chosen event occurs.

 Task runs ──► fails ──► on_failure_callback ──► message to team chat
                  │
                  └──► success ──► on_success_callback (optional)

Available Callbacks

CallbackFires When
on_failure_callbackA task or DAG run fails
on_success_callbackA task or DAG run succeeds
on_retry_callbackA task goes up for retry
on_skipped_callbackA task ends as skipped
on_execute_callbackA task is about to execute

A Basic Failure Callback

from datetime import datetime
from airflow import DAG
from airflow.operators.python import PythonOperator


def notify_failure(context):
    task_id = context["task_instance"].task_id
    dag_id  = context["task_instance"].dag_id
    error   = context.get("exception")
    print(f"ALERT: task {task_id} in DAG {dag_id} failed. Error: {error}")


def risky_job():
    raise ValueError("Source file is missing")


with DAG("alert_demo", start_date=datetime(2024, 1, 1),
         schedule="@daily", catchup=False) as dag:

    job = PythonOperator(
        task_id="risky_job",
        python_callable=risky_job,
        on_failure_callback=notify_failure,
    )

Airflow passes a context dictionary to the callback. It holds the task instance, the DAG run, the date values, and the exception.

Apply Callbacks to Every Task

Place the callback in default_args to cover all tasks in a DAG.

default_args = {
    "owner": "data_team",
    "retries": 2,
    "on_failure_callback": notify_failure,
}

with DAG("orders_daily", default_args=default_args,
         start_date=datetime(2024, 1, 1), schedule="@daily") as dag:
    ...

DAG-Level Callbacks

A DAG-level callback fires once per run, not once per task. Use it for a single summary message.

with DAG(
    "orders_daily",
    start_date=datetime(2024, 1, 1),
    schedule="@daily",
    on_failure_callback=notify_failure,
    on_success_callback=announce_success,
) as dag:
    ...

Email Alerts

Airflow sends email when you configure an SMTP server in airflow.cfg and set the options on a task.

default_args = {
    "email": ["team@example.com"],
    "email_on_failure": True,
    "email_on_retry": False,
}

Chat Alerts

Provider packages for Slack, Microsoft Teams, and other tools offer notifier classes. A notifier replaces hand-written callback code.

from airflow.providers.slack.notifications.slack import send_slack_notification

default_args = {
    "on_failure_callback": send_slack_notification(
        slack_conn_id="slack_alerts",
        text="Task {{ ti.task_id }} failed in {{ ti.dag_id }}",
        channel="#data-alerts",
    )
}

Install the Slack provider package first and create the connection named slack_alerts.

Alert Design Tips

  • Include the DAG name, task name, date, and a link to the log.
  • Alert on failures only. Alerts on every success train people to ignore messages.
  • Send the message to a shared channel, not to one person.
  • Keep callback code short and wrap it in a try block, so a broken alert never hides the real failure.

Where Callbacks Run

 Task callback      →  runs in the worker or the DAG processor, near the task
 DAG callback       →  runs in the DAG processor after the run ends
 Slow callback code →  can delay other work, so keep it light

Retries and Alerts Together

A task with three retries fails three times before Airflow calls on_failure_callback. Use on_retry_callback for early warnings on important tasks.

Key Takeaways

  • Callbacks are functions that fire on task or DAG events.
  • The context dictionary carries all details about the event.
  • Email, Slack, and similar tools deliver the alert.
  • Short, precise alerts get action. Noisy alerts get ignored.