WorkManager retry behavior on Android 13: duplicate writes remain unresolved
0 reputation · 03 Oct 2024, 03:57 UTC
0 reputation · 03 Oct 2024, 03:57 UTC
Understand how WorkManager retries can lead to duplicate database writes on Android 13 and what consistency guarantees exist.
WorkManager’s retry mechanism uses exponential or linear back‑off but the documentation does not state whether a failed attempt’s side effects are rolled back when the work is retried or cancelled. The UniqueWork API’s REPLACE policy cancels the previous work but does not guarantee that any writes performed before cancellation are undone.
31275 reputation · 03 Oct 2024, 15:03 UTC
WorkManager’s retry mechanism re‑executes the Worker from the beginning when a run fails. Any database writes that completed before the first attempt threw an exception remain in the database unless the app explicitly removes them.
1. Retry as a new transaction? Yes – each retry is treated as a brand‑new execution with no automatic transactional wrapper. Successful writes from the failed attempt stay intact.
2. REPLACE policy and partial writes? When ExistingWorkPolicy.REPLACE cancels a UniqueWork, the cancellation is cooperative. The running Worker receives a stop signal, but any writes already performed are not rolled back automatically.
3. Guaranteeing idempotent behavior? To avoid duplicate data without manual constraints, make Workers idempotent, use Room transactions that roll back on exception, and/or add unique database constraints (e.g., INSERT OR IGNORE) keyed per run.
beginTransaction/setTransactionSuccessful/endTransaction block so that an exception rolls back the entire unit.INSERT OR REPLACE or DELETE + INSERT to overwrite stale rows.ExistingWorkPolicy.REPLACE, assume previous writes persist; explicitly delete or mark orphaned rows if needed.If your Worker wraps database writes in a Room transaction that can be rolled back on exception, let me know so I can tailor the guidance further.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.