Skip to main content

Postgres as a job queue: claim, timeout and DLQ, no Redis

8 min read
PostgreSQL
Job Queue
Distributed Systems
Reliability
Node.js
Backend
SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus

You can run a job queue on one Postgres table with no Redis and no broker. The claim is a single conditional UPDATE whose WHERE accepts a row that is PENDING, or PROCESSING with a claim timestamp older than a window; that window is your visibility timeout, an attempts column incremented on every claim is your retry policy, and attempts >= N is your dead-letter queue. What you pay for this is polling, and you bound that with exponential backoff and jitter.

The rest is how I got there in KhataGO and what I got wrong on the way.

There is one; it speaks SQL

KhataGO takes WhatsApp messages from small business owners and turns them into ledger entries. Meta delivers webhooks at least once and redelivers on slow responses, so the webhook does the minimum: verify the signature and insert the row, then answer 202 (app/api/whatsapp/route.ts). The row has a unique waMessageId, so a duplicate delivery hits the constraint and never becomes a second job. I wrote about that choice in Why we didn't use Redis for webhook deduplication.

Once dedup lives in the table, the table is already most of a queue. The mapping, straight from docs/WORKER.md:

Queue concept KhataGO equivalent
enqueue webhook inserts the row, acks 202
visibility timeout aiClaimedAt + AI_CLAIM_STALE_MS (10 min)
receive / claim conditional updateMany; the loser updates 0 rows
retry policy aiAttempts incremented on claim, not on failure
dead-letter queue aiAttempts >= AI_MAX_ATTEMPTS (3) and aiStatus = FAILED
replay admin resets attempts and status, audited

Adding Redis or SQS here would copy this state into a second system that can disagree with the first. When someone asks "why not a real queue?", the honest answer is that there is one and it speaks SQL.

Why after() on serverless is not durability

The first version ran the model call inside Next's after(), right after the 202. The ack shape is right, but after() shares the invocation's budget and dies with it, and a five-turn tool-calling loop can outlive a serverless function. When it did, the row stayed PROCESSING and nothing could tell an abandoned claim from a running one (FINDINGS.md §2).

Recovery was a daily cron plus a small sweep on the next webhook: it healed when traffic arrived. The fix was a separate process, worker/, polling the same table. It adds capacity through the same claim rather than replacing the after() path, so either alone is enough and both together can't duplicate work.

The claim

Two ways to win, both inside one mutation (lib/whatsapp.ts):

const claim = await prisma.whatsappMessage.updateMany({
  where: { id: message.id, ...reclaimableWhere(claimedAt) },
  data: {
    aiStatus: AiProcessingStatus.PROCESSING,
    aiClaimedAt: claimedAt,
    aiAttempts: { increment: 1 },
  },
});
if (claim.count === 0) return false;

reclaimableWhere is the rule, and it lives in its own file so the sweeper and the claim can't drift apart (lib/whatsappClaim.ts):

return {
  status: PROCESSABLE_MESSAGE_STATUS,
  aiAttempts: { lt: AI_MAX_ATTEMPTS },
  OR: [
    { aiStatus: "PENDING" },
    { aiStatus: "PROCESSING", aiClaimedAt: { lt: staleBefore } },
  ],
};

Note what is not here: SELECT ... FOR UPDATE SKIP LOCKED. Two concurrent claimants both match the WHERE, Postgres serialises them on the row lock and re-evaluates the predicate against the updated row, so the loser sees a fresh aiClaimedAt and updates zero rows. A read-then-update would let both through. Two integration tests run this against a real Postgres in CI (tests/integration/whatsapp-webhook.integration.test.ts). One fires 10 concurrent conditional updateMany calls at one PENDING row and asserts exactly one returns count: 1. It uses the plain PENDING claim, not the stale-takeover branch, so it shows the row lock picking one winner; it does not race two reclaimers. The other fires 8 concurrent deliveries of the same waMessageId at the webhook and asserts one row is written and all eight get a 202.

Stale takeover is conservative: a PROCESSING row with a null aiClaimedAt is not reclaimable, because duplicating a live run costs a paid model call. tests/lib/whatsapp-claim.test.ts pins the edges, including that a fresh PROCESSING row is left alone and that exhausted attempts stop a claim whatever the state.

Why attempts count on claim, not on failure

A crash never reports a failure. If the counter moved only when a handler said "I failed", a message that crashed its worker every time would be retried forever. Counting on claim means the crash still spends an attempt. The cost of that choice is in §18 below.

The window has to be derived, not picked

Ten minutes is the visibility timeout. Everything that runs under a claim has to finish inside it, including the slow case where a model accepts the connection and goes quiet (§11). So the budgets in lib/deadlines.ts are outputs of the window, and the test asserts the inequality rather than the numbers:

AGENT_RUN_BUDGET_MS + GEMINI_CALL_TIMEOUT_MS < AI_CLAIM_STALE_MS
              240 s +                  60 s < 600 s

The sum, not the max, because a call that starts one millisecond before the run budget expires still gets its own full timeout. Change the window and tests/lib/deadlines.test.ts fails.

Dead letters and audited replay

At three attempts the row is written aiStatus: FAILED and shows up in the admin list. Replay is one endpoint, and the reset is conditional on the row still being dead (app/api/admin/dead-letters/route.ts):

const result = await tx.whatsappMessage.updateMany({
  where: { id, aiStatus: "FAILED" },
  data: { aiStatus: "PENDING", aiAttempts: 0, aiClaimedAt: null, aiError: null },
});
if (result.count === 0) throw new NothingToReplay();

Same discipline as the claim: the check is inside the mutation, so replaying twice is a no-op and a message that completed meanwhile can't be yanked back to rerun its side effects. The reset and its audit row commit in one transaction; the throw rolls both back, so the log never records a replay that didn't happen (tests/lib/deadLetterReplay.test.ts asserts the 409 and the missing audit row).

Polling, honestly

The worker loop (worker/loop.ts) sleeps 250 ms after a sweep that found work, doubles while idle up to 30 s, and jitters ±20%. The jitter is not decoration: two replicas started together and backing off deterministically poll in lockstep forever. The loop survives a sweep that throws, since a brief DB blip is operational rather than a bug. It also wakes from a long sleep on SIGTERM, because the container was once killed with exit 137 after logging "shutdown requested" and napping through Docker's ten-second grace. All of it is unit-tested with an injected sleep, random source and sweep (worker/loop.test.ts).

The trade-off is real: an idle worker still queries every 30 s and a busy one every 250 ms. At KhataGO's scale that's nothing. With hundreds of consumers, or a need for sub-100 ms pickup, the polling itself becomes the load.

What I got wrong

The longer version of these three mistakes is in the post on liveness for atomic claims. Short version:

The original claim was updateMany({ where: { aiStatus: "PENDING" }, data: { aiStatus: "PROCESSING" } }). Correct mutual exclusion, no way back out. A lock without an expiry is a deadlock waiting for a crash (§2).

Later, the sweeper's "what do I hand out" and the processor's "what will I act on" disagreed. A message from an unregistered number was refused in the processor's opening lines, before the claim that would have spent an attempt, so the sweeper selected it again every sweep. Three such rows filled the webhook sweep permanently, and because the processor returned void, every refusal counted as progress. The backoff never engaged and the worker sat at 250 ms logging processed: 5 (§17). The fix: message status joined reclaimableWhere, the refusal writes a terminal SKIPPED, and the processor returns a boolean the sweep counts.

Then §18: the claim was taken by the first statement and released by the last, with no try between them. Any throw skipped the release, the attempt stayed spent, and three throws made the row unreclaimable while still PROCESSING: invisible to the dead-letter list, refused by replay. The most common thrower wasn't the model; it was a user who hadn't added their API key yet. Now the work runs inside a catch, a throw becomes a FAILED outcome with aiClaimedAt cleared either way, and a missing key dead-letters on the first attempt with the message the user was owed (tests/lib/whatsapp-async.test.ts).

When I'd switch to a broker

When several services need the same events, or one message must fan out to independent consumers. When throughput makes polling the dominant load on the database. Neither applies to a table one product reads to answer one person's message.

What to do

Put the claim predicate in one function and use it for both the candidate query and the claim itself. Keep every condition inside the UPDATE, never in a read before it. Store the claim time and count; derive every timeout from the claim window with a test that asserts the inequality. Wrap the work between claim and release in a catch so the release runs on every path. Make the processor return whether it did anything, and have the backoff read that. Make replay conditional on the row still being dead, and write its audit row in the same transaction. Then write the test that fires N concurrent claims at one row and asserts one winner. If that passes against your real database, you have a queue.

SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus