r/PostgreSQL • u/compy3 • 14d ago
Projects Two tricks we used to cache tables with Row Level Security (policy inlining + pg_logical_emit_message)
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)?
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?
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_BARRIERviews where onlyLEAKPROOFfunctions and operators can be optimized across the barrier.If you treat it as just like
WHERE, you're asking for information leaks.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/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.