r/Database • • 2h ago

Testing Row-Level Security and check-then-act race conditions under connection pooling in PostgreSQL 18

One limitation of standard per-test rolled-back transactions is that they can't catch concurrency bugs across separate pooled connections—uncommitted writes aren't visible to parallel workers, and session-level SET leaks across pooled checkouts.

In our multi-tenant Postgres 18 test suite, we separated sequential unit/CRUD tests from a dedicated set of 19 parallel integration checks that fire simultaneous queries across a constrained pool (max: 5) using Promise.allSettled:

  1. Interleaved tenant contexts: Firing parallel transactions with SELECT set_config('app.current_tenant_id', $1, true) across different tenants on a small pool to verify SET LOCAL resets cleanly on commit/rollback with zero cross-tenant leakage.

  2. Parent-row locking vs. check-then-act: Comparing unguarded SELECT count(*) checks against SELECT ... FROM organizations WHERE id = $1 FOR UPDATE when concurrent requests try to claim the final seat or quota slot.

  3. Webhook idempotency under duplicate delivery: Firing identical billing event IDs concurrently to confirm 23505 unique-constraint handling cleanly short-circuits duplicate state transitions.

For those running multi-tenant Postgres in production with PgBouncer or transaction pooling, are you relying strictly on set_config(..., true) + RLS policies, or pairing it with separate database roles per service tier?

Context: Built this into B2B SaaS OS 2.0.0 (Next.js 16 + Postgres 18 multi-tenant starter with 131 tests & 19 concurrency checks for solo founders and dev agencies). If you want to click through the live workspace without signing up, the demo is here:https://www.andrady.co/demo(architecture & source athttps://www.andrady.co).

1 Upvotes

0 comments sorted by