Idempotent Job with Advisory Lock

12880
0

I reached for idempotency the moment retries started duplicating side effects. In Advisory lock helper, I generate a deterministic lock ID and use pg_try_advisory_lock to ensure only one worker owns the critical section; the ensure block always calls pg_advisory_unlock so I don’t leak locks. Then, in Idempotent job, I build an execution key like payment:capture:<id> and wrap the entire capture flow in AdvisoryLock.with_lock. Inside payment.with_lock, I do a second layer of safety by checking captured_at? before calling the gateway, then I persist captured_at as the one true “done” marker. The result is “exactly-once-ish” behavior without pretending the world is perfect.