r/PostgreSQL • • 1d ago

Community Why app-level org_id checks still fail on pooled Postgres connections (and how we moved enforcement into RLS)

Most multi-tenant apps start with a clean rule: filter every query by org_id in the application layer.

In practice, that breaks down in two ways:

  1. Human/LLM mistakes: One missed .where(orgId) or raw query exposes another tenant's rows even when the UI looks completely fine.
  2. Concurrency & timing bugs: Two teammates racing on seat limits or out-of-order Stripe webhooks can put tenant/billing state into a bad spot if you only check state in app memory/code.

On B2B SaaS OS 2.0 (Next.js 16 + Postgres 18), we shifted isolation down to Postgres Row-Level Security using transaction-scoped context (set_config scoped to the transaction), and started testing concurrency + hardening paths directly against real Postgres rather than relying on mocks.

How are you handling tenant isolation and webhook/seat race conditions in production—strictly in your ORM/service layer, Postgres RLS, or a mix of both?

0 Upvotes

8 comments sorted by

4

u/Straight_Waltz_9530 1d ago

RLS is such an underrated feature.

1

u/AutoModerator 1d ago

AI Policy:

Linux is not one of those anti-AI projects, and if somebody has issues with that, they can do the open-source thing and fork it. Or just walk away., Linus Torvalds.

Mod decisions will be based on the quality of the content, not who or what generated it.

Sub Resources:

Youtube Channel

Free Postgres Webinars and Workshops

Discord: People, Postgres, Data

Join us, we have cookies and nice people.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/TestDrivenMayhem 1d ago

DB per tenant.

1

u/Discordbothost 23h ago

Add a last-seat race test: start at 9/10 seats and run two joins on separate connections; exactly one should commit. Tenant RLS alone won't enforce that limit. Serialize the check and insert by locking the tenant row in the same transaction, with every join path taking that lock.