← Technical notes
Illustrative2 diagrams

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
Queue Worker DB External API 01job 02claim, conditional update 03send 04error 05clear claim if marker matches 06last error = stage + message 07return error, retry later 08retry 09claim 10send 11ok + external ref 12save ref, clear last error
  1. 01
    Queue → Workerjob
  2. 02
    Worker → DBclaim, conditional update
  3. 03
    Worker → External APIsend
  4. 04
    External API → Workererror
  5. 05
    Worker → DBclear claim if marker matches
  6. 06
    Worker → DBlast error = stage + message
  7. 07
    Worker → Queuereturn error, retry later
  8. 08
    Queue → Workerretry
  9. 09
    Worker → DBclaim
  10. 10
    Worker → External APIsend
  11. 11
    External API → Workerok + external ref
  12. 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

  1. 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.
  2. Call the external API. On failure, clear the claim (only if it is still our marker) and return an error so the queue retries.
  3. On success, store the external reference and clear the error, again only if our marker is still there.
  4. 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.
  5. 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.
  6. Recording the error is best-effort and never replaces the real failure.
All diagrams

Other views

Tap a table to see what it links to.

INVOICE_JOBstring statestring external_refstring last_errortimestamp last_error_attimestamp updated_at

← Technical notes on the home page