Stopping duplicate GPU jobs and runaway retries with Postgres leases and transactional outboxes
Four practical PostgreSQL and Redis patterns for idempotent job claims, transactional outboxes, SKIP LOCKED leases, and DB-enforced approval gates.
Most background job bugs do not show up when a queue is empty or every third-party API answers in 100ms. They show up when an HTTP call times out after the remote worker already accepted the request, when a webhook fires after a process crash, or when two browser tabs submit the same approval simultaneously.
In systems that launch paid GPU containers, deliver customer webhooks, or execute broker orders, "at-least-once" without idempotency turns a routine network blip into duplicate bills or corrupted state. Here are four PostgreSQL and Redis patterns that stop duplicate work and stale-state races without adding heavy distributed-systems infrastructure.
Pattern 1: Claim-before-dispatch with timed leases
Suppose a user finishes uploading a large video and your API calls a GPU worker on Modal to start transcoding. If the API call times out after 30 seconds, did Modal receive the request or drop it? Retrying blindly starts a second paid GPU container for the same video.
Instead of firing the worker and updating the database afterward, claim the job atomically in PostgreSQL first:
UPDATE videos
SET
status = 'processing',
transcode_attempt_id = $2,
lease_expires_at = NOW() + INTERVAL '20 minutes'
WHERE id = $1
AND status = 'uploading'
RETURNING id, transcode_attempt_id;
Only if that update returns a row does the caller invoke the GPU worker, passing transcode_attempt_id as an idempotency token. Here is what happens on every outcome:
- The worker returns
4xx: The failure is definitive. Transition the row tofailedwith the error reason. - The worker times out or returns
5xx: Do not retry immediately and do not roll backstatustouploading. Leave the claim intact and return an uncertain state. - The job stalls: Once
lease_expires_atpasses without completion, a periodic sweeper re-claims the row and dispatches the exact sametranscode_attempt_id, which the worker deduplicates if it already started.
This pattern from ClipMux uses one table and a sweeper instead of a separate distributed lock service, and it eliminates accidental double-billing on slow GPU cold starts.
Pattern 2: Transactional outbox for critical state changes and webhooks
Writing to PostgreSQL and then calling QStash, Redis, or a webhook endpoint directly creates a classic dual-write gap. If the process crashes between the database commit and the network call, the database says a job is ready while downstream consumers wait forever.
Writing the event into an outbox table inside the exact same transaction guarantees the state change and the notification commit together:
BEGIN;
UPDATE videos
SET status = 'ready', lease_expires_at = NULL
WHERE id = $1 AND transcode_attempt_id = $2;
INSERT INTO outbox_events (id, event_type, payload, idempotency_key)
VALUES ($3, 'video.ready', $4, $3);
COMMIT;
A lightweight relay (or QStash with dead-letter retries) reads pending outbox rows and attaches Idempotency-Key to outbound HTTP requests. Notice the tradeoff: delivery is at-least-once rather than exactly-once, so downstream webhook receivers still need to deduplicate on Idempotency-Key, and you should apply the outbox consistently to critical events rather than leaving secondary events on best-effort fire-and-forget.
Pattern 3: FOR UPDATE SKIP LOCKED and revision-bound approvals
When human reviewers or background workers pull from a shared queue, simple SELECT ... WHERE status = 'pending' LIMIT 1 queries cause two workers to grab the same item under load. And if a reviewer leaves a browser tab open overnight while another teammate edits or reclassifies the item, clicking Approve on stale data overwrites newer work.
PostgreSQL gives you both safe queue claiming and optimistic concurrency out of the box:
WITH next_task AS (
SELECT id
FROM review_tasks
WHERE status = 'pending'
AND (lease_expires_at IS NULL OR lease_expires_at < NOW())
ORDER BY created_at ASC
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE review_tasks
SET
claimed_by = $1,
claim_token = $2,
lease_expires_at = NOW() + INTERVAL '10 minutes'
FROM next_task
WHERE review_tasks.id = next_task.id
RETURNING review_tasks.*;
In AI Triage, an active tab renews that 10-minute lease every minute while visible. If the user closes their laptop, the lease simply ages out without needing a separate cleanup daemon, because every query treats an expired lease as unclaimed.
When the reviewer clicks Approve, the update checks the claim token, live lease, and the exact extraction_revision_id currently displayed on screen. Any mismatch returns 409 Conflict and writes nothing.
Pattern 4: Enforce automation boundaries in the database, not UI flags
In systems that combine automated analysis with real-world side effects (financial orders, refunds, customer emails), relying on an application-layer if (isApproved) check is brittle. One new worker script or manual retry path can bypass the check.
In SwingTraderVCP, an event-driven trading workstation built over Python, FastAPI, PostgreSQL, and Redis Streams, the unattended screening pipeline cannot create a live broker order intent on its own. Creating an order intent requires an INNER JOIN against the decisions table (status = 'approved'), verifies a SHA-256 hash of the plan fields, and triggers a database lock freezing approved payloads.
For tick-by-tick position monitoring during market hours, a standalone worker takes a Redis singleton lease rather than living inside the web server:
After-hours Worker ──▶ Postgres (proposals + SHA-256 hash) ──▶ Human Approval Row
│
Live Session Monitor (Redis singleton lease) ◀── INNER JOIN ───────────┘
└── Enforces stops, targets & kill switch without any open browser tab
If the monitor loses its Redis lease, it shuts down immediately instead of risking split-brain order management across two processes.
Start with the invariants before adding new brokers
You rarely need Kafka or complex consensus tooling to fix unreliable background work in a small or mid-sized product. Most production reliability issues disappear once you put state claims, outbox events, and approval invariants inside PostgreSQL transactions and reserve Redis Streams or QStash for transport and coordination.
If your team is dealing with duplicate jobs, flaky third-party webhooks, or ambiguous backend requirements that need clean concurrency boundaries, read the SwingTraderVCP case study or learn more about my backend and distributed systems consulting.
Frequently asked questions
When should I use PostgreSQL queues like pg-boss instead of Redis Streams or QStash?
Use Postgres-backed queues when job creation must commit atomically with business data in the same transaction or when ops teams want zero extra infrastructure to manage. Add Redis Streams or QStash when you need high-throughput fan-out, real-time tick streaming, or managed HTTP webhook retries with dead-letter queues.
How does a transactional outbox avoid dual-write bugs?
By writing the outbound event row into the same PostgreSQL BEGIN ... COMMIT transaction as your state change. Either both commit or neither does, eliminating silent missing notifications if the worker crashes after updating state.
What happens if a worker holding a Postgres lease crashes permanently?
Because every claim stores a lease_expires_at timestamp, a crashed worker never locks a task forever. Once the lease expires, the next FOR UPDATE SKIP LOCKED query or sweeper automatically picks up the task.
Can you retrofit idempotency and outbox tables onto an existing production database?
Yes. We typically add an outbox_events table and idempotency_key / lease_expires_at columns incrementally behind feature flags without rewriting existing API routes.