PostgreSQL RLS Can Cause 575x Query Slowdowns — Here Is How to Fix It
Row-Level Security (RLS) in PostgreSQL can silently degrade index scans to sequential scans in multi-tenant databases, causing p99 query latency to spike from milliseconds to seconds. The root cause is that PostgreSQL's current_setting() function is classified as VOLATILE, preventing the query planner from using it as a constant to drive index selection at plan time. Benchmarks on a 10-million-row table showed a roughly 575x performance regression when using a naive RLS policy compared to no RLS. The fix involves wrapping current_setting() in a STABLE function, which signals to the planner that the value is constant within a single query execution and allows index scans to resume. Pairing this with targeted partial indexes and using SET LOCAL inside explicit transactions — especially under connection poolers like PgBouncer — completes the performance-safe RLS setup.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in