A lease, not a heartbeat
How to make duplicate delivery and crashed workers boring, with one SQL statement.
A queue with at-least-once delivery will hand you the same job twice, and a worker will sometimes die halfway through one. The usual answer is a supervisor process that watches heartbeats and requeues silent jobs. That is another moving part that can itself fail.
Put the ownership on the row instead. Claiming a job is one conditional update that stamps an owner token and an expiry:
UPDATE jobs
SET status = 'processing',
worker_token = $2,
lease_expires_at = $3,
attempt_count = attempt_count + 1
WHERE id = $1
AND (status = 'queued'
OR (status = 'processing' AND lease_expires_at < now()))
RETURNING *;If no row comes back, someone else holds a live lease or the job is finished: delete the message and move on. That single statement makes duplicates a non-event, and the expired-lease branch makes a crashed worker's job recoverable without anything having to notice the crash.
Every later write matches on the owner token and checks whether it hit a row. A worker that stalled past its lease updates nothing, and, importantly, doesn't delete its queue message on the strength of a write that never landed. Extending the queue's visibility timeout while you work is the liveness signal, so there is no heartbeat table at all.