Introduction
A B2B distribution platform has a clean permission model in its application: users hold roles scoped to branches, and a central module checks every action. Then a developer adds a quick export endpoint for a customer request. It queries the orders table directly and forgets the branch filter. A branch manager downloads every branch's orders. Nothing in the code review flagged it, because the query looked like dozens of others.

Defense in depth means the database should refuse to return rows a user is not allowed to see, even when application code makes a mistake. Postgres row-level security (RLS) does exactly that, and it can follow the same branch-and-role model your application already uses.

In this article you will learn how to pass user context to Postgres, compute allowed branches efficiently, write separate read and write policies, keep queries fast, and test the whole setup. It builds on the location-scoped RBAC model described earlier in this series.

Passing User Context to the Database
RLS policies need to know who is asking. Set transaction-local settings at the start of each request, inside a transaction, so they disappear when the transaction ends and cannot leak across pooled connections.

BEGIN;
SELECT set_config('app.user_id', '42', true); -- true = local to this transaction
SELECT set_config('app.tenant_id', '7', true);
-- application queries follow
COMMIT;

Connect as an application role that is not a superuser and does not own the tables, because superusers and owners bypass RLS unless you set FORCE ROW LEVEL SECURITY.

Computing Allowed Branches Once Per Transaction
Calling a permission function for every row would be slow. Instead, compute the set of branches where the user holds a given permission once, and let policies compare against that set. A STABLE function lets Postgres evaluate it once per query rather than once per row.

CREATE FUNCTION app_branches(perm text) RETURNS bigint[]
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = app AS $$
SELECT coalesce(array_agg(DISTINCT lc.descendant_id), '{}')
FROM role_assignments ra
JOIN role_permissions rp ON rp.role_id = ra.role_id AND rp.permission = perm
JOIN location_closure lc ON lc.ancestor_id = ra.location_id
WHERE ra.user_id = current_setting('app.user_id')::bigint
$$;
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY orders_read ON orders FOR SELECT
USING (branch_id = ANY (app_branches('order.view')));
CREATE POLICY orders_write ON orders FOR UPDATE
USING (branch_id = ANY (app_branches('order.edit')))
WITH CHECK (branch_id = ANY (app_branches('order.edit')));

The function is SECURITY DEFINER so it can read the permission tables even though the application role cannot query them directly. Setting search_path on the function prevents a well-known class of privilege escalation through objects with the same name in other schemas.

Separate Policies for Reading and Writing
Users often see more than they can change. A regional manager might view all branches in her region but edit orders only in her home branch. Write separate policies per command: FOR SELECT for visibility, FOR UPDATE with both USING and WITH CHECK, FOR INSERT with WITH CHECK, and FOR DELETE if deletes are allowed at all.

WITH CHECK matters. Without it, a user who can edit an order in branch 3 could update its branch_id to 9 and move it out of reach of the people who should see it.

Keeping It Fast
Index branch_id on every branch-owned table, usually as the leading column of composite indexes that match your common queries, such as (branch_id, created_at). Check plans with EXPLAIN as the application role, not as a superuser, because RLS changes the plan.

For reporting views, use security_invoker views (available since Postgres 15) so the view applies the caller's policies rather than the view owner's. Materialized views do not apply RLS when read, so keep them out of user-facing queries or rebuild them per branch.

Practical Examples: Real-World Use Cases
The distribution platform from the introduction enabled RLS on orders, invoices, and customers. When the same export bug reappeared months later in a different endpoint, the database returned only the manager's own branches, and the issue was found in testing instead of by a customer.

A healthcare supplies company uses separate SELECT and UPDATE policies so area managers can view all depots in their area but adjust stock only in depots where they hold the stock controller role.

A franchise management SaaS combines tenant isolation and branch isolation in one policy: rows must match the current tenant and fall within the user's allowed outlets.

Common Mistakes to Avoid

  • Testing RLS as a superuser or table owner, which bypasses policies.

  • Using session-level settings with a connection pooler instead of transaction-local ones.

  • Writing a single FOR ALL policy when read and write rules differ.

  • Omitting WITH CHECK on update and insert policies.

  • Exposing materialized views or owner-privileged views that bypass RLS.

Best Practices: Actionable Tips

  • Keep the application permission module and RLS policies driven by the same tables.

  • Add an automated test that runs every API endpoint as a branch user and asserts no foreign-branch rows appear.

  • Add a CI check that lists branch-owned tables without RLS enabled.

  • Log and review queries that return zero rows unexpectedly after enabling RLS; they often reveal missing context settings.

  • Roll out RLS table by table, starting with the most sensitive data.

Conclusion
Row-level security turns your branch and role model into a rule the database enforces on every query. Pass user context with transaction-local settings, compute allowed branches once with a stable security-definer function, write separate read and write policies with WITH CHECK, index for the filter and test as the real application role. The takeaway: let application code decide what users should do, and let Postgres guarantee what they can never see.

Secure Your Multi-Branch Data With Parallaxis
Parallaxis builds ERP and operations platforms for multi-branch B2B companies, with permissions enforced in both the application and the database. If you need stronger guarantees that branches only see their own data, visit parallaxis.in to explore our ERP solutions or talk with our engineers.