Job stuck in PROCESSING? Liveness for atomic Postgres claims
Short answer: A job gets stuck in PROCESSING when the claim that moved it there has no way back out. An atomic UPDATE … WHERE status = 'PENDING' guarantees only one worker wins; it says nothing about what happens when that worker dies. The fix is to record when the claim was taken, let any worker take over a claim older than a known window, bound the number of takeovers, and make sure every path out of the work, including a throw, releases the claim.
I got each of those wrong once in KhataGO, a WhatsApp bookkeeping app I built. This is what each mistake looked like and what the code does now.
The claim that was correct
Every inbound WhatsApp message becomes a row in a Postgres table. Meta delivers at least once, so the row has waMessageId String? @unique (prisma/schema.prisma). A second delivery hits the constraint and gets acknowledged without a second row. The integration test fires eight concurrent deliveries of the same message id and asserts that one row is written and every caller gets a 202 (tests/integration/whatsapp-webhook.integration.test.ts).
Then something has to run the AI step on that row, and only one process may do it. The first version was this:
updateMany({
where: { aiStatus: "PENDING" },
data: { aiStatus: "PROCESSING" },
});
A conditional update. Two concurrent callers both match the WHERE, Postgres serialises them on the row lock, re-evaluates the predicate against the updated row, and the loser updates zero rows. The same test file races ten of these and asserts exactly one wins. It was correct.
What it could not do
There was no path from PROCESSING to anything except a finished run. The work ran inside Next's after(), which shares the webhook invocation's budget and dies with it. A five-turn tool-calling loop can outlive that budget. When it did, the row stayed PROCESSING forever, and nothing in the system could tell an abandoned claim from one still legitimately running.
A separate bug made it worse. A transient model error wrote FAILED on the first failure, so a message lost to a five-second outage was lost for good. Same shape: the state machine had an entrance and no exit.
Mutual exclusion and liveness are different properties. The test I had proved the first. Nothing proved the second, because nothing in a unit test dies halfway through an await.
Fix one: a claim that ages
Two columns on the row now (prisma/schema.prisma):
aiClaimedAt DateTime? // when the current PROCESSING claim was taken
aiAttempts Int @default(0) // incremented on every claim, including reclaims
And the rule for "may I take this row" lives in one place, lib/whatsappClaim.ts, as the Prisma where the claim and the sweeper both use:
export const AI_CLAIM_STALE_MS = 10 * 60 * 1000;
export const AI_MAX_ATTEMPTS = 3;
export function reclaimableWhere(now: Date) {
const staleBefore = new Date(now.getTime() - AI_CLAIM_STALE_MS);
return {
status: PROCESSABLE_MESSAGE_STATUS,
aiAttempts: { lt: AI_MAX_ATTEMPTS },
OR: [
{ aiStatus: "PENDING" },
{ aiStatus: "PROCESSING", aiClaimedAt: { lt: staleBefore } },
],
};
}
The claim itself (lib/whatsapp.ts) wins two ways in a single update: the row is PENDING, or it is PROCESSING and the claim is older than ten minutes.
const claim = await prisma.whatsappMessage.updateMany({
where: { id: message.id, ...reclaimableWhere(claimedAt) },
data: {
aiStatus: "PROCESSING",
aiClaimedAt: claimedAt,
aiAttempts: { increment: 1 },
},
});
if (claim.count === 0) return false;
Both predicates stay inside the mutation. A read-then-update would let two reclaimers through; one conditional UPDATE lets the row lock decide.
Ten minutes is a judgement, and the unit tests pin the reasoning rather than the number: the window must exceed a generous worst-case run, and must be at most fifteen minutes so a crash is not a lasting outage (tests/lib/whatsapp-claim.test.ts). Too short duplicates a paid model call and attempts the ledger writes again. Too long leaves a person waiting on a reply that will not come.
The attempt counter increments on claim, not on failure. A failure that never reports itself, because the process died, still spent an attempt. Below three, a failed run returns the row to PENDING and a sweeper picks it up. At three, it dead-letters as FAILED and lands on an admin page with a replay button.
Fix two: silence is not an error
The claim window closed the door for a worker that dies. It did not close the door for a dependency that goes quiet.
Every recovery path I had was entered by an error arriving: a 429 cascades to the next model, a thrown error becomes a FAILED outcome, three of those dead-letter. The SDK I used built its fetch with no AbortSignal unless you passed a timeout, and I passed none. A model that accepts the connection and never answers leaves await fetch(...) pending indefinitely. I measured that against a local server that accepts and never replies.
Follow one message through it. A worker claims it, attempts 1, calls the model, and the model goes quiet. The process gets killed before the call returns. Nothing writes a terminal state, because the code that writes one is on the other side of the await. Ten minutes later another worker takes it, attempts 2. Then 3. Now aiAttempts: { lt: 3 } excludes it from the sweeper, and aiStatus is still PROCESSING, never FAILED. The admin page lists where: { aiStatus: "FAILED" } (app/admin/page.tsx), the replay endpoint resets where: { id, aiStatus: "FAILED" } (app/api/admin/dead-letters/route.ts), and the sweeper cron reports count({ aiStatus: "FAILED" }). The row is in none of them. The dashboard says zero dead letters and the message is gone.
The counter that exists to stop a deterministic failure from burning paid calls is what turned slowness into permanence. It counts claims, and a slow dependency produces claims without outcomes.
The fix is a deadline on every wait, and the deadlines are derived from the claim window rather than chosen. lib/deadlines.ts holds a 240 s run budget and a 60 s per-call timeout. The test asserts the relationship, not the numbers (tests/lib/deadlines.test.ts):
expect(WORST_CASE_CLAIM_HOLD_MS).toBeLessThan(AI_CLAIM_STALE_MS);
expect(WORST_CASE_CLAIM_HOLD_MS).toBe(AGENT_RUN_BUDGET_MS + GEMINI_CALL_TIMEOUT_MS);
The sum, not the maximum, because the budget is checked between calls, so a call that starts one millisecond before the budget expires still gets its full per-call timeout. Change the claim window and the test fails instead of the timeouts quietly going wrong.
Fix three: the release was on the happy path
The shape of the processing function was: claim, do the work, write the terminal state. The last write is the only thing that clears aiClaimedAt. There was no try around the middle, so any throw between the two skipped the release and left the row exactly as above: PROCESSING, claim live, attempt spent.
The most likely thrower was not the model. Users can add their own Gemini key, the server uses its own only if one is configured, and the first thing the AI step does is resolve a key. With neither, it throws NoApiKeyError. So a user who had not finished setup texted the product and lost the message permanently, after three claims that could never have succeeded. The error class carries a message written for the user, telling them to add a key in Settings. It reached nobody, because the send came after the update that never ran.
Now the work runs inside a function that never throws (lib/whatsappWork.ts):
export async function runMessageWork(message, userId): Promise<MessageWork> {
try {
return { aiResult: await answerMessage(message, userId), terminal: false };
} catch (error) {
return failedWork(error, message.id);
}
}
A throw is treated as the FAILED outcome it is: retryable below the limit, dead-lettered at it, aiClaimedAt cleared either way. NoApiKeyError is marked terminal so it dead-letters on the first attempt instead of the third, and its message is delivered. Two more attempts cannot change whether a key exists.
What to do with your own stuck jobs
If you have rows wedged in a processing state, it is almost always one of these.
Find the statement that acquires and the statement that releases, and read what is between them. If the answer is "an await on anything at all" and the two are not joined by a finally or a transaction, the release is conditional on the happy path.
Record when the claim was taken. A boolean state cannot be aged. A timestamp can, and the takeover rule belongs inside the same conditional UPDATE that takes the claim, so two reclaimers serialise on the row.
Then ask which failure makes no noise. A dependency that throws is handled by whatever handles errors. One that goes silent is handled by nothing until every wait has a deadline, and the deadlines have to add up to less than the claim window or a healthy run gets taken over while it is still alive.
The bugs behind this post are §2, §11 and §18 of KhataGO's FINDINGS.md. The queue that sits on top of the claim, a polling worker with no broker, is its own post: Postgres as a job queue.