When things fail
Part of the free LogicWiz Data Engineering course, Module 9: Orchestration. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:05 on Wednesday 4 June. Tess opens the revenue dashboard and 3 June is exactly twice what it should be. The run grid is green from end to end. At 03:10 the warehouse had dropped its connection for a moment, and the load task did what it was told to do: it tried again.
You'll learn to
- Tell a failure worth retrying from one that needs a person
- Make a load safe to run twice, so retries cannot double it
- Alert once, then recover a half-finished run by clearing it
- Spread retries with backoff, and choose a timeout or a deadline alert
Learn
Some failures fix themselves
Start with what happened at 03:10. The warehouse dropped a connection. Nobody did anything, and a few minutes later it worked again.
Most pipeline failures are like that. The network blips, an API answers 429 (too many requests) or 503, a table is locked, a file has not arrived yet. These are transient failures: the same task, run again a few minutes later, works.
Others are permanent: a column was renamed, a password expired, your code has a bug, the data is bad. Trying those again fails again, more slowly.
So an orchestrator lets you say "try again". retries=3 allows four tries in all. A good pipeline retries the first kind of failure, and stops to tell a human about the second.
So why is 3 June doubled?
The load task had retries=1, and the retry worked. That is why the grid is green. Nora asks the question that cracks the case: "When the connection dropped, had the insert already happened?"
Here is the night again, in miniflow. The load inserts the orders of its interval. On 3 June the first try fails after the insert.
The night again: fail after the insert
import duckdb
import miniflow as mf
duckdb.sql("create table fct_orders (order_id int, order_date date)")
dag = mf.DAG('daily_orders', start_date='2025-06-01', schedule='@daily')
@dag.task(retries=1)
def load(ctx):
duckdb.sql(f"""
insert into fct_orders
select order_id, cast(order_ts as date) from 'data/orders.csv'
where order_ts >= '{ctx['data_interval_start']}' and order_ts < '{ctx['data_interval_end']}'
""")
if ctx['ds'] == '2025-06-03' and ctx['try_number'] == 1:
raise TimeoutError('connection dropped after the insert') # the rows are already in
for day in ['2025-06-02', '2025-06-03', '2025-06-04']:
dag.run_until(day)
duckdb.sql("select order_date, count(*) as rows_loaded from fct_orders group by 1 order by 1").show()
The run for 3 June is green, because the retry succeeded. The grid says everything is fine and the data is wrong: the failure came after the insert, so the retry inserted the same six orders a second time.
What the retry did
| Day | Orders in the source | Rows in fctorders | Run state |
|---|---|---|---|
| 1 June | 6 | 6 | success |
| 2 June | 6 | 6 | success |
| 3 June | 6 | 12 | success (on try 2) |
A failed task is not a task that did nothing. It may have done all of its work, half of it, or none, and the retry cannot tell which.
The rows went in. Only the answer was lost.
A sequence between the scheduler, a worker and the warehouse: the insert commits, the acknowledgement is lost when the connection drops, the try is marked failed, and the retry inserts the same rows again.
Try 1 does its work. The scheduler hands the load for 3 June to a worker. The worker sends the insert, and the warehouse commits it: six rows are in.
The answer never arrives. The connection resets before the warehouse can say OK. The worker sees an error and reports the try as failed. Nothing tells it that the rows are already there.
The retry. After the retry delay the scheduler sends try 2. It runs the same insert, and the warehouse commits the same six orders again.
A green run, 12 rows. Try 2 gets its answer, so the task is marked success. The grid shows what the scheduler knows. Only the table knows what was written.
Read it top to bottom: time runs downwards and each arrow is one message. From the worker's side, "the database did not answer" and "the database did the work and the answer got lost" look the same.
Make the second try harmless
You cannot stop an answer from getting lost. You can make the second try harmless.
A task you can run twice, and get the same table as running it once, is called idempotent. Then a retry, a manual rerun or a backfill can never double anything. For a load there are three common ways:
- Delete, then insert the run's interval, in one transaction.
- MERGE (upsert) on a key, so a second run updates the rows the first one added.
- Overwrite the partition for that day (Spark, Delta Lake, BigQuery).
All three make the table depend only on the interval, not on how many times the task ran.
Same failure, same retry, six rows
import duckdb
import miniflow as mf
duckdb.sql("create table fct_orders (order_id int, order_date date)")
dag = mf.DAG('daily_orders', start_date='2025-06-01', schedule='@daily', log=False)
@dag.task(retries=1)
def load(ctx):
duckdb.sql("begin transaction")
duckdb.sql(f"delete from fct_orders where order_date = '{ctx['ds']}'") # clear the interval first
duckdb.sql(f"""
insert into fct_orders
select order_id, cast(order_ts as date) from 'data/orders.csv'
where order_ts >= '{ctx['data_interval_start']}' and order_ts < '{ctx['data_interval_end']}'
""")
duckdb.sql("commit")
if ctx['ds'] == '2025-06-03' and ctx['try_number'] == 1:
raise TimeoutError('connection dropped after the insert')
for day in ['2025-06-02', '2025-06-03', '2025-06-04']:
dag.run_until(day)
print('tries on 3 June:', dag.tries('2025-06-03', 'load'))
duckdb.sql("select order_date, count(*) as rows_loaded from fct_orders group by 1 order by 1").show()
The only change is the delete before the insert, inside one transaction. The transaction matters too: if the task died between the delete and the insert, the delete would roll back and the old rows would stay.
Remember: a failed task is not a task that did nothing. Make it safe to run twice first, then give it retries.
At least once, sometimes twice at once
There is a second way to get a repeat, and it is nastier. An orchestrator promises that a task runs at least once, never exactly once.
Suppose a worker stops reporting: its pod ran out of memory, its node was drained, or the network dropped. After 300 seconds of silence ([scheduler] task_instance_heartbeat_timeout) the scheduler gives up on that task instance and fails or retries it. If it was only a network split, the first copy may still be writing when the second starts.
So a task has to survive two things: a replay (the same interval written again later) and a concurrent duplicate (two copies writing at the same moment). Delete-then-insert survives the first. Watch what it does with the second.
Two copies delete and insert at the same moment
A sequence between two copies of the load task and the orders table: copy A deletes and inserts without committing, copy B waits on the locked rows, then deletes nothing and inserts its own rows, leaving twelve.
The day already holds 6 rows. Copy A begins a transaction and deletes them. The delete is not committed yet, so the old rows are locked, not gone.
A inserts, B arrives. A inserts 6 fresh rows, still uncommitted. Copy B starts its own DELETE. It sees the 6 old rows, finds them locked by A, and waits.
A commits. B wakes up. The old rows are gone, so B has nothing left to delete. A's new rows were not committed when B's DELETE began, so that DELETE never sees them.
B inserts its own copy. B adds 6 more rows and commits. Each transaction was correct on its own. Together they left 12 rows.
Read it top to bottom. In Postgres at READ COMMITTED, each statement sees only the rows that were committed when that statement began. That is why B's DELETE misses A's new rows.
Which designs survive which repeat
| Design | A replay later | Two copies at once | Watch out for |
|---|---|---|---|
| Plain INSERT | duplicates | duplicates | every retry adds rows |
| DELETE + INSERT in one transaction | safe | duplicates under READ COMMITTED | the second DELETE cannot see the first copy's uncommitted rows: serialise with a lock or a pool of 1 slot |
| MERGE on a key with a unique constraint | safe | safe: the second copy waits, then updates or fails | needs a real business key |
| Overwrite the partition (INSERT OVERWRITE, Delta replaceWhere) | safe | one commit wins, the other fails with a conflict | the partition must match the interval exactly |
| Write to a path named by the interval, then swap it in | safe | the last writer wins | clean up half-written temporary files |
Side effects need the same care. An email, a payment or an API POST should carry an idempotency key such as dag_id/task_id/ds, which the receiver uses to drop repeats.
Tell a person once, then clear the run
Some nights the tries run out. Then a person has to know, and the run has to be put right.
Alert once, when a task has used all its tries, not on every try, or people learn to ignore the noise. Airflow calls a function you give it (on_failure_callback). Another way is a task with trigger_rule='one_failed', which runs only when something upstream failed.
Then recovery. Say the run for 2 June stopped at load: extract succeeded, load failed, report never ran. You fix the cause and clear the run. The scheduler reruns the tasks that did not succeed, and the successful ones keep their result. That is only safe because each task is idempotent.
Alert, then clear
import miniflow as mf
def page_on_call(ctx):
print(f" ALERT: {ctx['task_id']} failed for {ctx['ds']} after try {ctx['try_number']}: {ctx['exception']}")
dag = mf.DAG('daily_orders', start_date='2025-06-01', schedule='@daily', retries=2, on_failure=page_on_call)
@dag.task()
def extract(ctx):
pass
@dag.task(fail_on={'2025-06-02': 3}) # the warehouse is down all night on 2 June
def load(ctx):
pass
@dag.task()
def report(ctx):
pass
extract >> load >> report
dag.run_until('2025-06-03')
dag.grid()
dag.clear('2025-06-02') # the warehouse is back: rerun what did not succeed
dag.grid()
retries=2 on the DAG is the default for every task, like Airflow's default_args. In the first grid load is FAIL and report is up, upstream failed. In the second, ok(4) means load succeeded on its fourth try: try numbers keep counting across clears, as in Airflow. extract was not run again.
Retries multiply the damage of a task that is not idempotent. With retries=3, an append that fails after writing can load the same day four times, and every run ends green. Make the task idempotent first, then add retries. And do not retry permanent errors for hours: a renamed column will not fix itself. In Airflow, raise AirflowFailException: the task fails at once and skips its remaining retries.
A failed load on the run grid
A run grid over a week of June in which the load task can be made to fail every try on 2 June, so the tasks after it never start, and a later backfill reruns the day.
Tick Make load fail on 2 June, then press Next day twice. The load uses up its three tries and the tasks after it never start. The small number in a cell counts tries.
120 tasks retry in step
Retries have a failure of their own. At 02:00 the partner API goes down for 20 minutes, and the 120 copy tasks of swiftkart_ingest fail together. With a fixed retry_delay of 5 minutes they all come back together at 02:05, 02:10 and 02:15, onto a service that is trying to restart. With retries=3, every task has used its four tries before the API is back. That is a retry storm.
The cure has two parts. Exponential backoff waits longer after each failure: at least retry_delay x multiplier^(n-1) after try n. Jitter adds an extra wait, different for each task, of up to the same amount again. Airflow takes it from a hash of the DAG, task, logical date and try number, so tasks that failed together come back apart.
A 20-minute outage: fixed delay, then backoff
A timeline of minutes after 02:00 with the API down for 20 minutes: with a fixed delay three tasks retry together at 5, 10 and 15 minutes and all fail; with backoff and jitter their tries spread out and succeed after the API is back.
A fixed 5-minute delay. These three tasks, and the other 117, retry at minutes 5, 10 and 15, exactly together. The API is still down each time. After the fourth try they give up, five minutes before it comes back.
Backoff with jitter. Try 2 lands between minute 5 and minute 10, at a different moment for each task. Try 3 comes 10 to 20 minutes after that. For these three it lands after the API is back, and all of them succeed.
Each small bar is one try, on a clock of minutes after 02:00. The start times come from the next card: retry_delay=300, multiplier 2, and a failed try ends at once.
Airflow's backoff formula, on 120 tasks
import hashlib, math
def airflow_retry_delay(dag_id, task_id, ds, failed_try, retry_delay=300, multiplier=2.0, max_delay=None):
"""Seconds Airflow waits after try `failed_try` fails: its formula, with the same kind of jitter."""
if multiplier in (0, 1):
return retry_delay # no backoff: a fixed delay
min_backoff = max(1, math.ceil(retry_delay * multiplier ** (failed_try - 1)))
h = int(hashlib.sha1(f"{dag_id}#{task_id}#{ds}#{failed_try}".encode()).hexdigest(), 16)
delay = min_backoff + h % min_backoff # from min_backoff up to 2 x min_backoff - 1
return min(delay, max_delay) if max_delay else delay
def simulate(multiplier, tasks=120, retries=3, outage_s=20 * 60):
"""Every task's first try fails at 02:00, the API is down for 20 minutes, a failed try takes no time."""
per_minute, recovered = {}, 0
for n in range(tasks):
t = 0
for try_number in range(1, retries + 2):
per_minute[t // 60] = per_minute.get(t // 60, 0) + 1
if t >= outage_s:
recovered += 1
break
t += airflow_retry_delay('swiftkart_ingest', f'copy_t{n:03d}', '2025-06-03', try_number, multiplier=multiplier)
peak = max(v for minute, v in per_minute.items() if minute > 0)
return recovered, peak
for multiplier in (1, 2.0):
recovered, peak = simulate(multiplier)
print(f"multiplier {multiplier}: {recovered} of 120 tasks recover, busiest minute after 02:00 has {peak} tries")
print('copy_t001 waits', [airflow_retry_delay('swiftkart_ingest', 'copy_t001', '2025-06-03', k) for k in (1, 2, 3)], 'seconds')
The delay rule is Airflow's own (min_backoff + hash % min_backoff, then the max_retry_delay cap); only the text that is hashed is simplified. Backoff turns three spikes of 120 into a spread of at most 30 a minute, and every task outlives the outage. Try a 40-minute outage.
Remember: backoff makes each wait longer. Jitter makes each task's wait different. You need both.
All of it in one Airflow file
Runs in Airflow:
from datetime import datetime, timedelta
from airflow.sdk import dag, task
from airflow.sdk.exceptions import AirflowFailException
from airflow.timetables.interval import CronDataIntervalTimetable
def notify_on_call(context):
ti = context["task_instance"]
print(f"ALERT {ti.dag_id}.{ti.task_id} failed for {context['ds']}")
default_args = {
"retries": 3,
"retry_delay": timedelta(minutes=5),
"retry_exponential_backoff": 2.0, # Airflow 3.2+; True on older versions
"max_retry_delay": timedelta(minutes=30),
"execution_timeout": timedelta(minutes=45),
"on_failure_callback": notify_on_call,
}
@dag(
schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"),
start_date=datetime(2025, 6, 1),
catchup=False,
default_args=default_args,
)
def daily_orders():
@task
def load(data_interval_start=None, data_interval_end=None):
columns = ["order_id", "order_ts"] # read from the source in real code
if "order_ts" not in columns:
raise AirflowFailException("order_ts is missing: a schema change, do not retry")
...
load()
daily_orders()
After tries 1, 2 and 3 fail, this waits 5 to 10, 10 to 20, then 20 to 30 minutes (the last one capped by max_retry_delay). default_args apply to every task in the DAG; a task can override any of them. execution_timeout caps one try: when it is hit the task raises AirflowTaskTimeout, and the retry rules take over. Clearing is a button in the UI, or airflow tasks clear.
Stop the work, or tell someone?
One night the load is not failing. It is slow, and Tess opens her dashboard at 06:00. Three tools sound alike and do different things.
- A timeout stops work:
execution_timeoutkills a try,dagrun_timeoutfails the whole run. - An SLA in Airflow 2 (
sla=timedelta(hours=5)on a task) only notified:sla_miss_callbackran when the task had not finished that long after the DAG run started, manual runs were not checked, and the task kept running. Airflow 3.0 removed SLAs. - A deadline alert (Airflow 3.1, experimental) replaces them at DAG level:
deadline=DeadlineAlert(reference=..., interval=..., callback=...). Missing the deadline runs the callback, and the run keeps going.
None of them sees a green run that loaded nothing. That needs a freshness or volume check on the table (Module 7).
A deadline alert: tell someone, do not kill the run
Runs in Airflow:
from datetime import datetime, timedelta
from airflow.sdk import DAG, AsyncCallback, DeadlineAlert, DeadlineReference, task
from airflow.providers.slack.notifications.slack_webhook import SlackWebhookNotifier
from airflow.timetables.interval import CronDataIntervalTimetable
with DAG(
dag_id="daily_revenue",
schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"),
start_date=datetime(2025, 6, 1),
catchup=False,
# the finance dashboard opens at 06:00: warn at 05:00 if the run is still going
deadline=DeadlineAlert(
reference=DeadlineReference.DAGRUN_QUEUED_AT,
interval=timedelta(hours=5),
callback=AsyncCallback(
SlackWebhookNotifier,
kwargs={"text": "daily_revenue {{ dag_run.run_id }} is not done 5 hours after it was queued"},
),
),
):
@task(execution_timeout=timedelta(minutes=45))
def load():
...
load()
The timeout and the deadline do different jobs. The timeout ends a stuck try so retries can work. The deadline tells a person, early enough to act, that the data will be late.
Numbers to remember
| Name | Number or version | What it is |
|---|---|---|
| retries | 0 by default ([core] defaulttaskretries) | retries=3 allows four tries |
| retrydelay | 300 s by default ([core] defaulttaskretrydelay) | the wait before the next try |
| retryexponentialbackoff | True means a multiplier of 2, up to Airflow 3.1 | from 3.2 it takes a number, and True is read as 2.0 |
| maxretrydelay | you set it, for example 30 minutes | caps the wait, jitter included |
| executiontimeout, dagruntimeout | you set them, for example 45 minutes a try | cap one try (AirflowTaskTimeout), or the whole run |
| [scheduler] taskinstanceheartbeattimeout | 300 s | silence after which a running task is failed or retried |
| Task SLAs (sla=) | removed in Airflow 3.0 | they only notified; the task kept running |
| DeadlineAlert | Airflow 3.1, experimental | counts from when the run was queued (DAGRUNQUEUEDAT), its logical date (DAGRUNLOGICALDATE), a fixed time, or the average runtime of recent runs |
Real teams send failure alerts to Slack or Microsoft Teams, and page the on-call engineer through PagerDuty or Opsgenie only for pipelines with a deadline. Databricks Jobs, Dagster and Azure Data Factory have the same knobs under other names: retry count and interval, a timeout per activity, and alerts on failure.
What changed at SwiftKart
The load now deletes its day and inserts it again in one transaction, so a retry like the one at 03:10 leaves 3 June with six rows. You clear the load for 3 June once, and Tess's number is right again.
The copy tasks back off with jitter instead of marching together. One alert goes out when the tries run out, and a deadline alert warns at 05:00 if the revenue run is still going.
Retries deal with tonight. Lesson 9.3 deals with the past: the days a DAG missed while it was off, and the week finance wants recomputed.
In one line
A task can run more than once, so first make it safe to run twice (even two copies at once); then retry short failures with backoff and jitter, stop hung tries with a timeout, fail fast on errors no retry can fix, and alert once.
Interview corner
What does idempotent mean for a pipeline task, and how do you achieve it?
Running the task twice for the same interval leaves the target exactly as running it once. For loads: delete and reinsert the interval in one transaction, MERGE on a business key, or overwrite the partition for that date. Avoid plain appends, now(), and anything that depends on how many times the task has run.
How do you handle failures in Airflow?
Retries with a delay and exponential backoff for transient errors, an execution_timeout so hung tasks fail, and an on_failure_callback or an alert task that notifies once when retries are exhausted. Tasks are idempotent so retries are safe. To recover, fix the cause and clear the failed task instances; the scheduler reruns them and their downstream tasks.
A run failed halfway: extract succeeded, load failed. What do you do?
Read the task log to find the cause and decide whether it was transient or needs a fix. Fix it, then clear the failed task (and its downstream) for that run, leaving the successful extract alone. Because load is idempotent, it can rerun safely, and I check the row counts against the source afterwards.
At 02:00 a partner API fails and 120 tasks retry at exactly 02:05, 02:10 and 02:15, then all fail. What is happening and what do you change?
A retry storm: a fixed retry_delay keeps tasks that failed together in lockstep, so each wave hits the recovering API at once, and four tries in 15 minutes cannot outlast a 20-minute outage. I would turn on exponential backoff (multiplier 2: waits of 5 to 10, 10 to 20, then 20 to 40 minutes, with Airflow's per-task jitter), cap it with max_retry_delay, and put the tasks in a pool with a few slots so only that many calls are in flight. Permanent errors such as a 401 should raise AirflowFailException instead of retrying.