Making background job failures visible and safe to retry
Example domain: a worker that sends invoices to an external billing API in bulk.
Based on patterns I've built in production (details under NDA). The example domain below is illustrative.
TL;DR
Illustrative note: claim a row before calling out, record the stage and last error, and retry without sending twice.
live trace · Failed call, then retryfrom the original diagram
01
Queue → Workerjob
02
Worker → DBclaim, conditional update
03
Worker → External APIsend
04
External API → Workererror
05
Worker → DBclear claim if marker matches
06
Worker → DBlast error = stage + message
07
Worker → Queuereturn error, retry later
08
Queue → Workerretry
09
Worker → DBclaim
10
Worker → External APIsend
11
External API → Workerok + external ref
12
Worker → DBsave ref, clear last error
…
01
The problem
+
Jobs fail for many reasons (bad config, upstream error, lost race). Ops couldn't see why something was
stuck, and retries risked sending twice.
02
How it works
+
Claim before calling: a single conditional UPDATE stamps a claim
marker only if the row is still pending. Two workers race and only one wins; the loser exits quietly
without retrying.
Call the external API. On failure, clear the claim (only if it is still our marker) and return an error
so the queue retries.
On success, store the external reference and clear the error, again only if our marker is still there.
On every failure, record the stage and last error on the row
(truncated, overwritten each time). The admin screen shows why a row is stuck at a glance.
A stale claim (older than a set window) can be reclaimed; a callback that arrives with the external id
can heal a row whose reference was never saved.
Recording the error is best-effort and never replaces the real failure.