r/PostgreSQL • • 14d ago

Projects Two tricks we used to cache tables with Row Level Security (policy inlining + pg_logical_emit_message)

Post image

My co-founder James just shipped the first of two big swings at Row Level Security in PgCache, our caching proxy for Postgres. In case it's not obvious, I'm one of the founders, but the two tricks he used are pretty neat on their own, so I wanted to share them here.

The problem with caching RLS tables is pretty simple: If your cache keys on the SQL text, you give tenant 7's orders to tenant 8, so until now we told anyone using RLS to leave those tables out of PgCache.

1- The policy is just part of the WHERE clause

Back in August, James told me "RLS itself is just an extension to the WHERE clause," and that's basically how it works now. PgCache asks Postgres which policies apply to the session's role, fills in the session's own values, and folds them into the query:

CREATE POLICY tenant_policy ON orders
  USING (tenant_id = current_setting('app.tenant_id')::int);

-- after SET app.tenant_id = '7', this query
SELECT * FROM orders WHERE status = 'open';
-- gets cached as
SELECT * FROM orders WHERE status = 'open' AND tenant_id = 7;

So every tenant gets its own cache entry (and two sessions for the same tenant share one).

The obvious alternative was a cache entry per role, but then PgCache couldn't check new rows from the replication stream against the policy, so every insert into an RLS table would mean throwing cached results away.

Once the policy is a plain filter, the replication stream keeps each tenant's results fresh in place, like any other query. The tradeoff is that the role PgCache connects with needs to see every row for when it fills the cache (but if you're using PgCache you're already using a role that has access to logical replication anyway).

2- Getting DDL into the replication stream

The big challenge is that there's not enough in the logical replication stream to actually support Row Level Security. Logical replication is all about rows, so it never tells you when someone runs CREATE POLICY or REVOKE.

Our fix is a pair of event triggers on your database that turn each DDL command into a logical message:

PERFORM pg_logical_emit_message(true, 'pgcache', <the objects that changed>);

That true makes it transactional, so the message lands in the stream (and in the right order) inside the same transaction. And there's no extension to install.

Roles were the one gap, since event triggers don't fire for ALTER ROLE or GRANT role TO role. James really didn't want to poll anything, but PgCache now reads pg_roles and pg_auth_members every 5 seconds, which turned out to be way cheaper than the alternatives.

The second of our 2 big swings will be policies built on JWT claims (Supabase's auth.uid()), which still pass through to Postgres for now. Plan is to add other rare policy shapes on an as-needed basis, but Supabase feels like tablestakes for saying "our proxy is feature complete" in 2026.

James wrote up all the details in the repo: ADR-062 for the policy inlining, ADR-058 for the event triggers and ADR-061 for privileges and the role poll. The compatibility docs list what's cached and what passes through.

Curious to know how you guys are actually passing the tenant through to Postgres in production (custom setting, SET ROLE per tenant, JWT claims)?

12 Upvotes

10 comments sorted by

3

u/DickBrainTime 14d ago

For an app using transaction pooling, I'd pass the tenant as a transaction-local setting, e.g. `BEGIN; SELECT set_config('app.tenant_id', $1, true); ...; COMMIT`. The `true` makes it local to that transaction (similar to `SET LOCAL`), so the next request reusing the connection doesn't inherit it. The parameterized `set_config` call also works cleanly with prepared queries.

The separate trust boundary is *who sets that value*: `app.tenant_id` by itself isn't authenticated identity. If an untrusted client can issue arbitrary SQL as the app role, it can choose its own setting, so an RLS policy comparing `tenant_id` to `current_setting(...)` isn't sufficient against that client. This pattern needs a trusted API to authenticate the tenant and assign the setting; direct/untrusted SQL access needs a different boundary.

I saw ADR-062 already models `SET LOCAL`, `RESET` and role context. I'd specifically regression-test one pooled connection alternating tenant 7/8, including rollback/savepoint and cache-hit/coalesced requests, rather than assume those are missing. Is the intended PgCache usage mainly trusted application connections or also direct client SQL?

1

u/compy3 13d ago

Thanks for this!

PgCache tracks SET, SET LOCAL and set_config per connection, so the transaction-local pattern you describe is supported.

On trust: mostly application connections today. PgCache doesn't authenticate the tenant, it just uses whatever value the session set, so like you said, a trusted layer has to be the one setting it.

Great test list - passing it on.

1

u/Basic-Set-3758 14d ago

yeah parameterized set_config with the local flag is way nicer with prepared statements than string-interpolating SET LOCAL

2

u/iiiinthecomputer 14d ago

Row security policy is not "just an extension of the WHERE clause".

You have to be very conscious of information leaks via function side effects and even timing. It's much closer to SECURITY_BARRIER views where only LEAKPROOF functions and operators can be optimized across the barrier.

If you treat it as just like WHERE, you're asking for information leaks.

1

u/compy3 13d ago edited 13d ago

This is a good flag. We're less familiar with SECURITY_BARRIER so something to look into more.

I would say that we’re generally not expecting pgcache to be used in situations that allow users to run arbitrary sql against it (*our focus is not to take on responsibility for authenticating the tenant, that’s on the application).

In any case, worth taking a pass to see what ways security can be tightened in our RLS handling. Thanks for this.

*edit: clarified the focus parenthesis above

2

u/Significant_Tune9219 14d ago

Folding the policy into the query text is neat, but it only stays correct if the cache knows every input the policy depends on. A policy that calls current_user, a role membership check, or a STABLE function reading another table can change its result without the query text changing, so it's worth thinking about how those get keyed or invalidated. Does it fall back to bypassing the cache when a policy references something it can't inline?

1

u/compy3 13d ago

Yes, that’s the approach we’ve taken - current_user and any custom settings the policy reads (e.g. app.tenant_id, JWT claims) become part of the cache key, so two sessions only share an entry if those values match. A STABLE SQL function gets its body inlined, so a table it reads becomes part of the cached query and is kept current by CDC like any other join. Policy changes evict the affected queries, and role membership changes are picked up by polling the role catalogs (5s by default, since Postgres doesn’t emit events for those). Anything we can’t inline or track (plpgsql functions, built-in GUCs, etc.) makes the query forward to origin.

1

u/Significant_Tune9219 13d ago

Polling the role catalogs every 5s leaves a short window where a revoked role could still be served a cached entry. Once the poll notices a change, is eviction immediate, and is there a way to tighten the interval for sensitive policies?

1

u/compy3 13d ago edited 11d ago

Sounds like you have a specific use case in mind - at present we’re solving generally, and I’d have to check with my cofounder who’s building, but I think it’s theoretically possible to tighten the interval. I’ll check eviction time but should be immediate, yes.

Edit:
1- checked with my founder, yes the cache is invalidated as soon as the poll notices any changes.
2- currently there is one setting that configures the general poll interval, so that can be shortened. However the setting controls all polling.

Always happy to jump on a call if you have specific requirements

1

u/AutoModerator 14d 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.