PostgreSQL Partitioning Meets Row-Level Security: Sharding Multi-Tenant SaaS Data Without Sacrificing Policy Enforcement
--- title: "PostgreSQL Partitioning Meets Row-Level Security: Sharding Multi-Tenant SaaS Data Without Sacrificing Policy Enforcement" published: true description: "Learn how PostgreSQL RLS policies interact with declarat
---
title: "PostgreSQL Partitioning Meets Row-Level Security: Sharding Multi-Tenant SaaS Data Without Sacrificing Policy Enforcement"
published: true
description: "Learn how PostgreSQL RLS policies interact with declarative partitioning, avoid silent data leaks on new partitions, and optimize tenant isolation with partition pruning."
tags: postgresql, architecture, security, performance
canonical_url: https://mvpfactory.co/blog/postgresql-rls-partitioning-multi-tenant
---
## What We Are Building
By the end of this walkthrough you will understand exactly how PostgreSQL's declarative partitioning and Row-Level Security interact โ and more importantly, where they silently diverge. We will set up tenant-isolated partitioned tables, apply the correct RLS pattern per partition, and wire up a verification query you can run as a deploy gate. This is the pattern I use in every production multi-tenant system.
## Prerequisites
- PostgreSQL 13+ with declarative partitioning support
- A working understanding of RLS (`CREATE POLICY`, `ENABLE ROW LEVEL SECURITY`)
- Familiarity with range or list partitioning on a high-volume table
---
## Step 1 โ Understand the Inheritance Gap
Here is the gotcha that will save you hours.
When you enable RLS on a parent table and define a policy on it, child partitions inherit the RLS *enabled* flag โ but **not the policy itself**. Queries routed through the parent are covered. Direct child-table access is not.
sql
ALTER TABLE events ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON events
USING (tenant_id = current_setting('app.current_tenant')::uuid);
The planner can prune to `events_2024_q4` and execute directly against it. When it does, PostgreSQL re-checks RLS on that child. No policy on the child means your `FORCE ROW LEVEL SECURITY` setting and the connecting role's privileges determine whether data leaks. A misconfigured connection pool role or a `BYPASSRLS` superuser gets through unimpeded.
---
## Step 2 โ Verify With pg_policies, Not Assumptions
The docs do not make this obvious, but `pg_policies` returns zero rows for a child partition that is relying solely on parent-level policy definitions. Run this after attaching any new partition:
sql
SELECT tablename, policyname, cmd, qual
FROM pg_policies
WHERE tablename = 'events_2024_q4';
Zero rows. The partition looks unprotected โ because for direct access, it effectively is. Any automated security audit querying `pg_policy` per-table will produce a false negative and your compliance check passes when it should fail.
---
## Step 3 โ Apply Policy Per Partition at Attach Time
Here is the minimal setup to get this working correctly. Treat each partition as a first-class security boundary:
sql
-- Run immediately after attaching a new partition
ALTER TABLE events_2024_q4 ENABLE ROW LEVEL SECURITY;
ALTER TABLE events_2024_q4 FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON events_2024_q4
USING (tenant_id = current_setting('app.current_tenant')::uuid);
Automate this. Make it a required migration step, not a manual checklist item.
---
## Step 4 โ Keep Your USING Clause Pruning-Friendly
The entire reason you partitioned was partition pruning. On a 500M-row `events` table, pruning on `tenant_id` can drop query cost from a full sequential scan to a single child-table scan โ often 20โ40x in wall clock time. Your RLS predicate must cooperate with the planner for this to work:
| Predicate Form | Partition Pruning | Notes |
|---|---|---|
| `tenant_id = current_setting(...)::uuid` | Yes (planning time) | Preferred |
| `tenant_id = get_tenant_id()` (stable fn) | Yes (execution time) | Works, slightly later |
| `tenant_id = ANY(get_tenant_ids())` | Partial | Only if list is static |
| Complex subquery join | No | Planner cannot prune |
A cast mismatch between `uuid` and `text` silently kills pruning and you get sequential scans at scale with no warning.
---
## Step 5 โ Wire Up a Deploy-Gate Audit Query
Let me show you a pattern I use in every project. Run this as a CI check or nightly job:
sql
SELECT
c.relname AS partition,
rls.rowsecurity,
COUNT(p.policyname) AS policy_count
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
JOIN pg_class r ON r.oid = i.inhparent AND r.relname = 'events'
JOIN pg_tables rls ON rls.tablename = c.relname
LEFT JOIN pg_policies p ON p.tablename = c.relname
GROUP BY c.relname, rls.rowsecurity
HAVING COUNT(p.policyname) = 0 OR rls.rowsecurity = false;
If this returns any rows in production, you have an unprotected partition. Treat it as a P0 incident.
---
## Gotchas
**Parent-only policies are not enough.** The inherited `rowsecurity = true` flag is not the same as having an enforced policy on every child. Never assume coverage flows down automatically.
**`pg_policies` lies by omission.** It will not show parent policies as applying to children. Your audit tooling must query per child table explicitly.
**Type mismatches are silent performance killers.** A `uuid` column compared against a `text` setting in your USING clause compiles without error and fails pruning without explanation. Keep types consistent from schema design forward.
---
## Conclusion
Combining declarative partitioning with RLS is a sound architecture for multi-tenant SaaS at scale โ horizontal performance via pruning, policy-enforced isolation without application-layer gymnastics. The contract only holds if you treat partition attachment as a security event, not just a schema event. Apply policies explicitly per child, verify with `pg_policies`, and automate the audit. The 20โ40x query performance gain is worth protecting carefully.
**Further reading:** [PostgreSQL RLS documentation](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) ยท [Declarative Partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html)
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.