r/Database • • 3d 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).

0 Upvotes

5 comments sorted by

1

u/Hongstar1982 2d ago

We run the same shape behind PgBouncer in transaction mode, and the thing that helped most was making the set_config unavoidable, one transaction wrapper that every request goes through so no query path can start without the tenant GUC. The policy then compares tenant_id to current_setting('app.current_tenant_id')::uuid, which errors on a placeholder that was never set, so a missed call fails loudly instead of quietly matching rows. The case that actually scares me is the stale value rather than the missing one, a session that once had SET app.current_tenant_id keeps answering for the old tenant if the pooler doesn't reset it, so we also add a BYPASSRLS role only for migrations and analytics and let app and worker traffic both go through RLS.

1

u/Pale_Ferret_8241 2d ago

Spot on across all three points—especially failing loudly with current_setting('app.current_tenant_id')::uuid (without the missing_ok flag) so an unwrapped query throws immediately instead of quietly returning an empty result set and masking a missing tenant context.

That stale-GUC fear is also why we specifically wrote a pooled-contention test firing interleaved tenant transactions through a tiny connection pool (max: 5)—confirming that transaction-local set_config(..., true) clears cleanly on commit/rollback even if a raw SET was ever attempted earlier on the socket, and pairing it with FORCE ROW LEVEL SECURITY so table owners don't accidentally bypass policies in app code while keeping BYPASSRLS strictly isolated to the migration role.

Curious—for background workers that fan out across multiple tenants (like scheduled billing or webhook retries), do you open a fresh withTenant transaction per tenant item in the batch, or handle them through a dedicated worker role?

1

u/Hongstar1982 1d ago

Per item, but through the same app role. A dedicated worker role still has to prove which tenant it's acting for, so you end up writing the same checks twice and the two copies drift. Our queue hands out one tenant per job and the job opens its own short transaction with the GUC set at the top, which keeps a bad tenant to its own rollback instead of poisoning the batch. The part that bit us was billing runs overlapping when a retry comes in late, so the claim on the job row happens inside that same transaction, that's what stops two workers from charging the same tenant twice.

1

u/nian2326076 1d ago

You're dealing with important concurrency and row-level security challenges in PostgreSQL. Ensuring that context settings are isolated for each transaction is key to preventing cross-tenant leaks. You might also want to explore using dedicated worker roles to manage tenant contexts more effectively, but be aware this can lead to needing additional checks.

For interview practice related to database handling, you can use PracHub to simulate scenarios that reinforce your understanding before implementing changes.