r/Supabase • • 3d ago

database PostgreSQL persistent task queue: concurrency, idempotency and restart recovery

/r/codereview/comments/1y6b5t7/postgresql_persistent_task_queue_concurrency/

For those using Supabase, would you recommend Supabase Queues (pgmq) or a dedicated PostgreSQL queue table for this use case? I'm particularly interested in concurrency, stale worker protection and reliable restart recovery.

1 Upvotes

11 comments sorted by

View all comments

1

u/CaressingCash21 2d ago

Since you're keeping the existing Postgres queue, I'd make completion ONE database function/transaction. First do a conditional UPDATE matching the job instance, current claim ID, processing state and an unexpired lease, then use RETURNING to gate the observation/event inserts. Zero rows means stale: no result writes. That keeps the ownership check and all completion effects together, instead of checking a claim and writing results in separate requests. Add a unique key per logical result/event as well, so retries after a lost response can't duplicate them. If you later use pgmq for delivery, put its acknowledgment in that transaction too. I'd test reassignment while the old worker is paused, and a crash after commit but before it gets the response!!! PostgreSQL explains the concurrent UPDATE/WHERE recheck here: https://www.postgresql.org/docs/current/transaction-iso.html

1

u/fervent7 2d ago

Thank you for this detailed and practical recommendation.

Keeping the conditional completion, ownership validation and observation/event inserts within one atomic PostgreSQL transaction makes sense for our existing architecture.

The two failure scenarios you highlighted are particularly important: reassignment while the original worker is paused, and a crash after commit but before acknowledgement.

We'll include both in our regression verification, alongside unique logical result identifiers and restart recovery.

Would you recommend implementing the completion operation as a dedicated PostgreSQL function with restricted execution privileges, or handling it through an application-managed transaction using a least-privilege database role?

I appreciate the PostgreSQL documentation reference and your technical guidance.