WorkManager retries re-run doWork(): who owns deduplication for write jobs?
0 reputation · 20 May 2024, 22:49 UTC
0 reputation · 20 May 2024, 22:49 UTC
WorkManager's documented retry path re-invokes a Worker's doWork() on every attempt, with exponential backoff between runs. Unique work names and ExistingWorkPolicy stop a duplicate work item from being enqueued, but as of the 2.8.x line (worth re-checking against the current release) nothing in the documented API collapses the effects of a retried execution that already performed a write.
That leaves a gap for jobs that mutate persistent state. A Room @Transaction makes a single execution atomic, yet a retry after process death or a network flap can apply the same write twice. The usual mitigation — a persistent flag or idempotency key checked before writing — is entirely developer-supplied, and its behavior across process death and device restarts is not spelled out in the WorkManager documentation.
The unresolved decision is whether deduplication of retried writes should be a framework concern or an application concern:
32275 reputation · 21 May 2024, 00:17 UTC
When WorkManager retries a Worker, it simply re‑invokes doWork() on each attempt. The framework does not collapse the side‑effects of a previous successful run, nor does it automatically deduplicate writes performed by the worker. Deduplication of write operations is an application‑level responsibility.
doWork() on every retry, with exponential back‑off.WorkRequest under a unique work name (via ExistingWorkPolicy).@Transaction guarantees atomicity of a single execution but does not prevent the same transaction from running twice after a retry.@Entity
data class User(
@PrimaryKey val userId: String,
val name: String
)
val idempotencyKey = "op-${UUID.randomUUID()}"
if (!dao.exists(key = idempotencyKey)) {
dao.insertData(...)
dao.markAsDone(key = idempotencyKey)
}
ExistingWorkPolicy, remember it only blocks duplicate enqueuing, not duplicate execution on retry.
Do you have a unique constraint or idempotency key in place for the writes performed by this worker? Knowing that will determine whether the recommendation above needs to be adjusted.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.