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.
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:
DELETE only stamps xmax on the existing tuple.UPDATE stamps xmax on the old tuple and inserts a brand-new tuple
version. Unless the new tuple fits on the same 8 KB page and modifies zero indexed columns
(allowing a HOT — Heap-Only Tuple update, aided by setting
fillfactor = 80..90), every index on the table must also insert a new index
entry pointing to the new tuple's ctid.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:
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.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.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 level | Snapshot scope | Lost update | Write skew / phantom | Engine mechanism |
|---|---|---|---|---|
READ COMMITTED (default) | New snapshot per statement | Possible unless atomic SQL or row lock | Possible | Waits on conflicting row write, then re-evaluates WHERE on the updated tuple |
REPEATABLE READ | Single snapshot at first query in tx | Blocked (aborts second writer with 40001) | Possible (disjoint writes survive) | First-updater-wins row version check; no predicate locks |
SERIALIZABLE | Single snapshot + dependency tracking | Blocked (40001) | Blocked (40001) | SSI: non-blocking SIRead predicate locks detect rw-antidependency cycles |
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
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 atREPEATABLE READorSERIALIZABLEmust be wrapped in a retry harness that replays the entire transaction decision logic (not just the failed SQL statement) onSQLSTATE 40001and40P01(deadlock).
FOR NO KEY UPDATE, SKIP LOCKED, and Advisory LocksHeavy lock contention in PostgreSQL frequently comes from acquiring stronger locks than necessary:
FOR UPDATE vs. FOR NO KEY UPDATE: a plain
SELECT ... FOR UPDATE on a parent row (for example, parts or
tenants) blocks concurrent INSERTs into child tables referencing that
parent via foreign keys (which acquire FOR KEY SHARE). Whenever your transaction
will update non-key columns — status, counters, metadata — lock with
FOR NO KEY UPDATE instead so child inserts continue unblocked.FOR UPDATE SKIP LOCKED): polling a
queue table with plain FOR UPDATE serializes every worker behind the oldest
in-flight job. Adding SKIP LOCKED lets concurrent workers bypass locked rows
immediately in sub-millisecond time while preserving exact-once lease acquisition: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.*;
pg_advisory_xact_lock(hashtext(...))):
when serializing operations on a logical resource that does not yet have a database row (for
example, per-tenant webhook ingestion or on-prem BOM revision creation), use
transaction-scoped pg_advisory_xact_lock rather than session-scoped
pg_advisory_lock. Session-scoped advisory locks leaked into a PgBouncer
transaction-pooled connection remain held forever on that backend connection.EXPLAIN (ANALYZE, BUFFERS) like an operatorNever run bare EXPLAIN ANALYZE without BUFFERS. Wall-clock
actual time fluctuates with OS page-cache warmth and noisy neighbors; buffer counts
measure physical work.
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;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.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.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.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).
In production, naive RLS policies regularly turn 1 ms lookups into multi-second sequential scans. Two rules prevent 95% of RLS regressions:
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.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).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;
Declarative partitioning is an operational lifecycle and working-set tool, not an automatic speedup:
PARTITION BY RANGE (created_at) via
pg_partman): ideal for append-heavy telemetry, audit trails, and usage
ledgers. Expiring 90-day data becomes an instant metadata operation
(DROP TABLE events_2026_07) instead of a multi-hour DELETE that
generates gigabytes of WAL and dead-tuple bloat.tenant_id: rarely worth the operational tax
until a single table's active B-tree indexes exceed RAM (shared_buffers + OS page
cache, typically 100 GB+), because PostgreSQL enforces a hard constraint: every
UNIQUE or PRIMARY KEY constraint on a partitioned table must include the
partition key, and queries missing the partition key scan every partition.| Symptom | First catalog / view to query | What you are looking for |
|---|---|---|
| Sudden p99 spike, CPU normal | pg_stat_activity + pg_locks | wait_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 weeks | pg_stat_user_tables | High n_dead_tup, stale last_autovacuum, rising Heap Fetches in EXPLAIN BUFFERS |
| Single endpoint regressed after data growth | pg_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 inserts | pg_stat_user_indexes | idx_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.