← All writing

PostgreSQL internals for multi-tenant backends: MVCC, serialization anomalies, locking, EXPLAIN BUFFERS, and RLS pitfalls

Yunseop Im · Software Engineer, Backend & AI Systems · M.S. CS, Georgia Tech

Most backend outages blamed on "database scale" happen well under a few thousand writes per second. They are almost never caused by PostgreSQL hitting hardware limits; they are caused by application engineers treating Postgres as an abstract relational store instead of an 8 KB page-oriented MVCC storage engine with specific planner, lock, and visibility rules.

This field guide covers the five PostgreSQL mechanics that repeatedly decide whether a multi-tenant SaaS or enterprise data platform stays fast and correct under load: storage and Visibility Map degradation, concurrency anomalies and Serializable Snapshot Isolation (SSI), row-lock granularity and queue contention, reading EXPLAIN (ANALYZE, BUFFERS), and Row-Level Security (RLS) performance traps.

1. Storage engine & MVCC: why "Index Only Scan" silently degrades

A PostgreSQL table is an unordered heap of 8 KB pages. Every row version (tuple) carries transaction-visibility metadata in its 23-byte header — primarily xmin (the transaction ID that inserted this tuple version) and xmax (the transaction ID that updated or deleted it, or 0 if still live). Oversized attributes such as wide JSONB blobs or document text are compressed and sliced out-of-line via TOAST so sequential scans that omit those columns never pay their I/O cost.

Because Postgres implements Multi-Version Concurrency Control (MVCC) by appending new tuple versions rather than overwriting in place:

The Visibility Map trap

B-tree index entries in PostgreSQL do not store xmin/xmax visibility metadata. When the planner chooses an Index Only Scan on a covering index, Postgres consults a compact bitmap called the Visibility Map (VM) — two bits per 8 KB heap page indicating whether all tuples on that page are visible to all current transactions.

-- Healthy table after VACUUM: VM bits are set, zero heap I/O
Index Only Scan using orders_tenant_created_cov_idx on orders
  (cost=0.42..8.84 rows=25 width=20) (actual time=0.028..0.041 rows=25 loops=1)
  Index Cond: (tenant_id = '42'::uuid)
  Heap Fetches: 0
  Buffers: shared hit=4

-- Same query on a write-heavy table while autovacuum lags:
Index Only Scan using orders_tenant_created_cov_idx on orders
  (cost=0.42..8.84 rows=25 width=20) (actual time=0.061..4.890 rows=25 loops=1)
  Index Cond: (tenant_id = '42'::uuid)
  Heap Fetches: 980
  Buffers: shared hit=612 read=184

Why did latency jump 100× with the exact same query plan? Default autovacuum_vacuum_scale_factor = 0.2 waits until 20% of the table has changed before vacuuming. On a 50M-row events table, that means 10 million dead/updated tuples accumulate — clearing VM bits across thousands of pages — before autovacuum even starts. Every dirty VM bit forces Index Only Scan to drop down to the heap (Heap Fetches) to check tuple visibility.

Production rules:

  1. Tune hot append/update tables per-table: lower autovacuum_vacuum_scale_factor = 0.01 (or switch to a fixed autovacuum_vacuum_threshold = 50000) and raise autovacuum_vacuum_cost_limit so vacuum keeps the Visibility Map warm.
  2. Enforce idle_in_transaction_session_timeout (for example, 15s–30s). Never hold a database transaction open across an external LLM or webhook HTTP call: a single stalled snapshot pins OldestXmin cluster-wide, preventing VACUUM from reclaiming dead tuples on any table in that database.

2. Transaction isolation anomalies & Serializable Snapshot Isolation (SSI)

PostgreSQL implements three distinct isolation levels (READ UNCOMMITTED behaves identically to READ COMMITTED). Choosing between them requires knowing the exact concurrency anomalies each permits:

Isolation levelSnapshot scopeLost updateWrite skew / phantomEngine mechanism
READ COMMITTED (default)New snapshot per statementPossible unless atomic SQL or row lockPossibleWaits on conflicting row write, then re-evaluates WHERE on the updated tuple
REPEATABLE READSingle snapshot at first query in txBlocked (aborts second writer with 40001)Possible (disjoint writes survive)First-updater-wins row version check; no predicate locks
SERIALIZABLESingle snapshot + dependency trackingBlocked (40001)Blocked (40001)SSI: non-blocking SIRead predicate locks detect rw-antidependency cycles

Pattern A: Lost update in Read Committed (credit ledgers & quotas)

Under default READ COMMITTED, reading a tenant's credit balance in application code (SELECT balance FROM wallet WHERE id = $1 → check balance >= 80 → UPDATE wallet SET balance = balance - 80) suffers a classic read-then-write race: two concurrent requests both read 100, both pass the application check, and the second UPDATE waits for the first commit before applying - 80 to the newly committed row — leaving the balance at -60.

You do not need SERIALIZABLE for single-row invariants. Push the invariant into a single atomic predicate update so PostgreSQL re-evaluates the WHERE clause after acquiring the row lock:

UPDATE wallet
   SET balance_micro = balance_micro - $2,
       updated_at    = now()
 WHERE user_id = $1
   AND balance_micro >= $2
RETURNING balance_micro;
-- 0 rows returned == insufficient funds; zero race window, zero explicit SELECT FOR UPDATE

Pattern B: Write skew in Repeatable Read (multi-row invariants)

Suppose a manufacturing approval rule requires at least one lead engineer to remain active on an on-call rotation (count(*) WHERE active = true >= 1), or a booking table forbids overlapping time windows when `EXCLUDE USING gist` cannot express a cross-table rule. Two concurrent transactions running at REPEATABLE READ both observe two active engineers (Alice and Bob); Transaction 1 sets active = false on Alice's row while Transaction 2 sets active = false on Bob's row. Because they touch different rows, REPEATABLE READ commits both — violating the invariant with zero active engineers.

Under SERIALIZABLE, PostgreSQL's Serializable Snapshot Isolation (SSI) places lightweight, non-blocking SIRead predicate locks in shared memory (promoted from tuple to page or relation granularity when max_pred_locks_per_transaction fills). When SSI detects a dangerous structure of two adjacent rw-antidependency edges, the first committer wins and the second receives SQLSTATE 40001 (serialization_failure).

Rule from PostgreSQL §13.5: Any transaction running at REPEATABLE READ or SERIALIZABLE must be wrapped in a retry harness that replays the entire transaction decision logic (not just the failed SQL statement) on SQLSTATE 40001 and 40P01 (deadlock).

3. Locking granularity: FOR NO KEY UPDATE, SKIP LOCKED, and Advisory Locks

Heavy lock contention in PostgreSQL frequently comes from acquiring stronger locks than necessary:

WITH claimed AS (
  SELECT id
    FROM outbox_jobs
   WHERE status = 'pending'
     AND run_after <= now()
   ORDER BY priority DESC, id ASC
   LIMIT 10
     FOR UPDATE SKIP LOCKED
)
UPDATE outbox_jobs j
   SET status     = 'processing',
       locked_at  = now(),
       attempt    = j.attempt + 1
  FROM claimed
 WHERE j.id = claimed.id
RETURNING j.*;

4. Reading EXPLAIN (ANALYZE, BUFFERS) like an operator

Never run bare EXPLAIN ANALYZE without BUFFERS. Wall-clock actual time fluctuates with OS page-cache warmth and noisy neighbors; buffer counts measure physical work.

  1. Estimated vs. actual row divergence (rows=12 vs. actual rows=48,000): when the planner underestimates cardinality by 100×, it picks a Nested Loop (quadratic random index lookups) where it needed a Hash Join. Common culprit in multi-tenant schemas: correlated columns such as (tenant_id, project_code) where Postgres multiplies independent column selectivities. Fix with multivariate statistics: CREATE STATISTICS st_tenant_proj (dependencies, ndistinct) ON tenant_id, project_code FROM documents; ANALYZE documents;
  2. Buffers: shared hit vs. read vs. temp written: each unit is an 8 KB page. temp read/written means a Sort or HashAggregate spilled to disk because work_mem (allocated per plan node per connection) was too small. Instead of raising global work_mem (which risks OOM under connection spikes), apply SET LOCAL work_mem = '64MB' inside known analytical transactions.
  3. Composite index column order: place equality predicates first (tenant_id, status), then the sort or range column (created_at DESC), and attach display-only payload columns via INCLUDE (amount_micro, actor_id) so they never bloat non-leaf B-tree pages.
  4. Specialized access methods: use GIN for array/ACL containment (WHERE acl_groups && $1::text[]) and JSONB containment (jsonb_path_ops is ~2–3× smaller and faster than default jsonb_ops when you only need @>); use GiST / pg_trgm for substring part-number searches (ILIKE '%6010%'); use BRIN on append-only timestamped audit logs where a 100 KB summary index replaces a 10 GB B-tree.

5. Multi-tenant isolation at scale: RLS planner traps & partitioning

Relying solely on developers remembering WHERE tenant_id = $1 on every SQL query is a cross-tenant data breach waiting to happen. PostgreSQL Row-Level Security (RLS) moves that boundary into the storage engine (always pair ENABLE ROW LEVEL SECURITY with FORCE ROW LEVEL SECURITY and ensure the application connects as a non-BYPASSRLS, non-table-owner role).

The two RLS performance cliffs

In production, naive RLS policies regularly turn 1 ms lookups into multi-second sequential scans. Two rules prevent 95% of RLS regressions:

  1. Every composite index on an RLS-protected table must lead with the policy column (tenant_id). RLS rewrites every query against the table to inject the policy predicate. An existing index on (created_at DESC) forces Postgres to scan recent rows across all tenants and discard 99.9% via Filter: ... Rows Removed by Filter: 1999000. Leading with (tenant_id, created_at DESC) turns the policy into an Index Cond touching single-digit buffers.
  2. Force InitPlan caching for non-trivial session/JWT helpers. If a policy calls a custom SQL/PLpgSQL helper or parses JSON claims per row (USING (tenant_id = current_tenant_id())), Postgres may evaluate that function once per candidate row during a filter scan. Wrapping the right-hand side in an uncorrelated scalar subquery — USING (tenant_id = (SELECT current_tenant_id())) — forces the planner to hoist it into an InitPlan evaluated once per query ($0) instead of millions of times. Note: for a direct current_setting('app.tenant_id')::uuid against a leading (tenant_id, ...) B-tree index, direct comparison already binds cleanly into Index Cond; test both with EXPLAIN (ANALYZE, BUFFERS) on real tenant distributions (whale vs. small tenants).

PgBouncer transaction pooling + RLS

PostgreSQL forks one OS process per client connection (~5–10 MB RSS each plus snapshot scanning overhead), so production services sit behind PgBouncer in transaction pool mode. Never set tenant context with session-level SET app.tenant_id = '...' on a transaction-pooled connection — the next request borrowing that backend connection inherits the previous tenant's GUC! Always scope context strictly to the current transaction with SET LOCAL:

BEGIN;
SELECT set_config('app.tenant_id', $1, true); -- third arg true == SET LOCAL (tx-scoped)
-- All queries in this transaction execute under RLS for $1;
-- COMMIT automatically resets app.tenant_id before PgBouncer reuses the socket.
COMMIT;

When to partition (and when not to)

Declarative partitioning is an operational lifecycle and working-set tool, not an automatic speedup:

Production diagnostic checklist

SymptomFirst catalog / view to queryWhat you are looking for
Sudden p99 spike, CPU normalpg_stat_activity + pg_lockswait_event_type = 'Lock'; blocking PID sitting idle in transaction or DDL waiting behind a long reader (blocking all subsequent queries in the lock queue!)
Gradual latency creep over weekspg_stat_user_tablesHigh n_dead_tup, stale last_autovacuum, rising Heap Fetches in EXPLAIN BUFFERS
Single endpoint regressed after data growthpg_stat_statements (sort by total_exec_time & shared_blks_read)Plan flip from Index Scan to Seq Scan or Nested Loop due to stale stats or skewed tenant ("whale tenant" problem)
Write amplification / slow insertspg_stat_user_indexesidx_scan = 0 unused indexes paying write + WAL + vacuum tax on every UPDATE; drop with DROP INDEX CONCURRENTLY

Bonus DDL rule that saves outages: never run bare ALTER TABLE ... ADD CONSTRAINT or CREATE INDEX on a live table in production. Even a 200 ms ACCESS EXCLUSIVE lock queues behind an active 10-second analytics query — and while it waits in the lock queue, every new SELECT and INSERT on that table queues behind the waiting DDL. Always set a defensive SET lock_timeout = '2s' on migrations, use CREATE INDEX CONCURRENTLY, and add foreign keys / check constraints as NOT VALID first followed by VALIDATE CONSTRAINT.

Related: Per-tenant RAG isolation · Multimodal agent SaaS architecture & ledgers · FreightScaler architecture & SQL tuning · Resume