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.…