Duplicate database rows after Airflow task retry in PythonOperator
0 reputation · 28 Jan 2020, 03:49 UTC
0 reputation · 28 Jan 2020, 03:49 UTC
Run an Airflow PythonOperator task that inserts records into an external PostgreSQL table and ensure that automatic retries do not create duplicate rows when a transient failure occurs after the insert succeeds but before the task reports success.
Airflow re-executes the same callable on each retry. The retries setting controls attempt count but does not track side effects or deduplicate writes. on_retry_callback can run cleanup logic before a retry, but it is not a built-in idempotency guard and may not exist in older Airflow versions. Application-level idempotency keys are available, but the team wants to know whether Airflow retry semantics alone can prevent the duplication.
36775 reputation · 28 Jan 2020, 06:09 UTC
No. Airflow does not provide a built-in mechanism to skip task re-execution because an earlier attempt already committed an external write. The retries setting only controls how many times the callable is re-run; it does not track side effects outside Airflow's metadata database. Both PythonOperator and the TaskFlow API decorator use the same underlying retry semantics, so neither prevents duplicate PostgreSQL rows by itself.
| Item | Behavior |
|---|---|
| Retry re-executes the callable from the start | Well-established |
| A committed PostgreSQL insert survives task failure | Well-established |
on_retry_callback cannot see external committed writes | Well-established |
| PythonOperator and TaskFlow share retry semantics | Well-established |
Exact on_retry_callback version support | Version-dependent; check installed Airflow release |
The likely failure window is: attempt one inserts a row and commits, then fails before Airflow marks the task instance successful. On retry, Airflow runs the same callable again and issues a second insert for the same logical record.
try_number alone, because it changes on retry.INSERT ... ON CONFLICT (idempotency_key) DO NOTHING or DO UPDATE SET ... so a repeated attempt does not create a second row.on_retry_callback as the primary guard. It runs in the same task-instance context and cannot reliably detect whether the previous attempt committed the external write.PythonOperator and TaskFlow API retries behave the same way because both resolve to the same task-instance retry logic. on_retry_callback may not exist or may behave differently in older Airflow releases. Run python -c 'import airflow; print(airflow.__version__)' and inspect BaseOperator in your installed version before depending on it.
Can you add a unique constraint or idempotency-key column to the target PostgreSQL table? If schema changes are not possible, the recommendation shifts to a separate durable deduplication table or an external lock.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.