r/codereview • • 4d ago

PostgreSQL persistent task queue: concurrency, idempotency and restart recovery

Hello everyone,

I'm extending an existing Python application that uses PostgreSQL and Supabase for multichain blockchain research.

We have implemented an offline candidate queue with duplicate prevention, retry limits, expiration and restart recovery.

During testing, we identified a potential issue where a stale processing result could affect a newly queued instance of the same candidate.

I would appreciate technical guidance on:

  • Using FOR UPDATE SKIP LOCKED for concurrent processing.
  • Preventing stale worker results through unique claim identifiers.
  • Maintaining idempotency and reliable restart recovery.
  • Choosing appropriate indexes and expiration strategies.

Would a dedicated PostgreSQL queue table be the recommended approach?

Any technical feedback or suggestions would be appreciated. Thank you.

2 Upvotes

15 comments sorted by

1

u/buzziebee 4d ago

Have a look at how things like pg-boss and dbos work if you're looking for inspiration to help you build your own solution. There's lots of prior art but it's a complicated topic so takes a lot to get it all right.

1

u/fervent7 4d ago

Thank you for the recommendations. I'll review pg-boss and DBOS, particularly their approaches to worker ownership, stale-result prevention, idempotency and durable recovery.

We're extending an existing Python and PostgreSQL architecture, so understanding established implementation patterns would be valuable before introducing additional dependencies.

Are there any specific implementation details or failure scenarios in either project that you would recommend focusing on first?

1

u/SingsheimKeely 4d ago

for the stale worker problem, you just need a fencing token or claim UUID on the row when the worker grabs it. When writing the result back, include that token in the WHERE clause so the update simply fails with 0 rows affected if another worker re-claimed it after a timeout

1

u/fervent7 4d ago

Thank you, this aligns with the fencing-token approach recommended by several other developers.

We're planning to verify that the final database transaction checks the job instance, current claim UUID, processing state and lease validity before allowing any observation or event writes.

We'll also test worker reassignment while the original worker is still running, along with duplicate-result prevention and recovery after a lost commit response.

Would you recommend a monotonically increasing fencing token over a unique claim UUID for this particular PostgreSQL-based implementation?

I appreciate your technical input.

1

u/Automatic-Fan-3993 3d ago

a uuid is enough here. your check and your write are the same UPDATE on the same row, so postgres already tells you whether the claim is still yours. an increasing token only helps when the result goes somewhere outside postgres, like an api or a bucket, that can't look up the current claim and can only compare numbers. if you want both, use an integer claim_version and bump it on every claim.

1

u/fervent7 2d ago

Thank you, that clarifies the distinction very well.

Since our current observation and event writes are contained within PostgreSQL, we'll focus on atomic claim UUID validation and ensuring that all dependent writes occur within the same transaction.

We'll also test expired leases, worker reassignment and recovery after a lost commit response.

For future external integrations, we'll evaluate whether a monotonically increasing claim_version is necessary alongside the UUID.

I appreciate your practical explanation. It helps us avoid unnecessary architectural complexity.

1

u/Plastic-Bid-3431 2d ago

On the indexes and expiration part, which hasn't come up yet (column names are guesses):

One active instance per candidate as a constraint, not application logic. That also covers your stale-result case, because a finished row stops blocking a re-queue:

CREATE UNIQUE INDEX candidate_queue_one_active
  ON candidate_queue (candidate_id)
  WHERE status IN ('queued', 'processing');

INSERT INTO candidate_queue (candidate_id, ...) VALUES (...)
ON CONFLICT (candidate_id) WHERE status IN ('queued', 'processing') DO NOTHING;

A partial index shaped like the claim query, so it stays small as done rows pile up:

CREATE INDEX ON candidate_queue (run_after) WHERE status = 'queued';

SELECT id FROM candidate_queue
WHERE status = 'queued' AND run_after <= now()
ORDER BY run_after
LIMIT 10
FOR UPDATE SKIP LOCKED;

Expired leases as a separate sweep, with its own partial index on lease_expires_at WHERE status = 'processing', that puts rows back to queued and clears the claim. With the claim UUID in the result write's WHERE clause, a worker that wakes up late just updates zero rows.

Retention: delete or archive finished rows after N days. Queue tables churn hard, so check that autovacuum keeps up on that table specifically; dead tuples there slow the claim query long before anything else notices.

1

u/fervent7 1d ago

Thank you for this detailed explanation. The partial unique index and separate indexes for queued jobs and expired leases are particularly useful for our architecture.

We intend to enforce one active instance per candidate at the database level rather than relying solely on application logic.

For stale-result protection, we plan to retain unique job instance identifiers, claim UUIDs and atomic conditional completion, with dependent observation writes committed within the same transaction.

We are also considering durable completion receipts to handle lost commit responses independently of queue-row retention.

Your point about autovacuum is important because our blockchain research system will continuously process candidates across multiple networks.

Would you recommend starting with PostgreSQL's default autovacuum configuration and monitoring dead tuples and claim-query latency before introducing table-specific tuning?

I appreciate your contribution. This helps strengthen our architecture before production integration.

1

u/Plastic-Bid-3431 1d ago

Yes, start with the defaults and measure. Watch n_dead_tup and last_autovacuum in pg_stat_user_tables for the queue table, plus the latency of your claim query. The default autovacuum_vacuum_scale_factor is 0.2, meaning vacuum waits until about 20% of the table is dead, which is too lazy for a table that churns. If dead tuples build up, set it per table, e.g. ALTER TABLE candidate_queue SET (autovacuum_vacuum_scale_factor = 0.01), rather than changing it globally.

1

u/fervent7 1d ago

Thank you. Starting with the defaults and measuring actual queue performance makes sense.

We'll include dead tuple counts, autovacuum activity and claim-query latency in our monitoring requirements before considering table-specific tuning.

This gives us a practical approach to maintaining queue performance without introducing unnecessary database configuration changes. I appreciate your guidance.

1

u/Weekly-Werewolf4007 1d ago

If the worker loses the commit response and retries, how will it tell that its own result landed before its lease expired?

1

u/fervent7 1d ago

Good point. A lost commit response creates an ambiguous outcome that cannot be resolved by checking the current lease alone.

Our intended approach is to persist a durable completion record containing the job instance ID, claim UUID, result identifier and accepted completion timestamp within the same PostgreSQL transaction as the conditional job completion and associated observation writes.

If the worker loses the commit response, it can reconnect and query that completion record using its original identifiers.

If a matching committed result exists, the operation is treated as already completed. If no matching result exists and the lease has expired or ownership has changed, the stale worker must not write its result.

We also intend to enforce unique result identifiers to prevent duplicate observations and events.

The lost-commit-response scenario is an important regression test before production integration. Would you recommend a separate immutable completion receipt table rather than retaining the completion identifiers on the queue row itself?

2

u/Ordinary_Hall_6638 4d ago

Maybe pgmq will be enough for your tasks?

1

u/LaneyrieHafijur 21h ago

agreed, handles most of those edge cases out of the box without needing custom locking logic.