What Is the MultiXact Subsystem?
Before diving into the wait events, it helps to understand what PostgreSQL is protecting. When a single transaction modifies a row, PostgreSQL stores that transaction's ID (XID) directly in the row header's xmax field. Simple and fast. But what happens when two or more transactions need to hold locks on the same row simultaneously? For example:
- Two sessions run SELECT ... FOR KEY SHARE on the same row, OR
- A SELECT ... FOR UPDATE session encounters a row already locked by a foreign key check (FOR KEY SHARE), OR
- Multiple sub-transactions created by SAVEPOINT all reference the same row
In these cases, PostgreSQL cannot store two XIDs in a single xmax field. Instead, it creates a MultiXact ID (MXID) — a composite identifier that points to a list of all involved transaction IDs. These mappings are stored in two on-disk structures:
- pg_multixact/offsets/ — maps each MXID to its position in the member's file
- pg_multixact/members/ — stores the actual list of member XIDs
To avoid reading these files from disk on every row visibility check, PostgreSQL caches them in memory using a SLRU (Simple Least Recently Used) cache — a small, fixed-size ring buffer with just 8 buffer slots by default (64 KB) for offsets and 16 slots (128 KB) for members.
Each of those buffer slots is protected by an LWLock (Lightweight Lock). And that LWLock is exactly where the bottleneck hides.
The Core Insight:
Cache Hits and Lock Contention are not mutually exclusive
This is the most important concept in this entire post:
pg_stat_slru measures I/O misses. pg_stat_activity wait events measure lock contention.
Here is what actually happens at the microsecond level:
Session A: Needs MXID 5,000,023 → Page is in SLRU cache (blks_hit++) → LWLock is needed on buffer slot 3 → Session B already holds that LWLock → Session A WAITS → wait_event = 'MultiXactOffsetSLRU' recorded
The cache is warm, the page is in memory, but what happens when 50 concurrent sessions suddenly all need that same buffer slot's LWLock? Only one request can hold the LWLock at a time. Every session that queues behind the lock holder generates a wait event record, all while no disk I/O is occurring.
What Triggers MultiXact SLRU Wait Events?
Below are the scenario's which could trigger MultiXact SLRU Wait Events.
Thundering Herd — Mass Concurrent Row Locking
When dozens or hundreds of sessions simultaneously attempt to lock the same small set of rows, PostgreSQL must create and resolve MXIDs at high frequency. Each resolution requires an SLRU lookup. When all lookups target the same few SLRU pages, the buffer lock becomes a serialization point. A classic reconnect avalanche triggered when the connection pool detected server slowness and all clients retried simultaneously.
Foreign Key FOR KEY SHARE vs. FOR UPDATE Conflicts
This is one of the most common hidden triggers. Every time a child row is inserted or updated, PostgreSQL implicitly acquires FOR KEY SHARE on the referenced parent row to prevent the parent from being deleted. If another session simultaneously holds FOR UPDATE on that same parent row, PostgreSQL must combine both lock modes into a new MXID:
-- Session A (updater):
SELECT * FROM orders WHERE id = 1 FOR UPDATE;
-- Session B (child inserter — FK check):
INSERT INTO order_items (order_id, amount) VALUES (1, 99.00);
-- Implicitly:
SELECT * FROM orders WHERE id = 1 FOR KEY SHARE;
-- PostgreSQL creates MXID combining both transactions → SLRU write
SAVEPOINT and Sub-transaction Churn
Every SAVEPOINT creates a sub-transaction XID. ORM frameworks and JDBC drivers with autosave=always silently wrap every statement in a SAVEPOINT, generating sub-XIDs that accumulate rapidly. When these sub-XIDs reference the same rows across concurrent sessions, MXID creation accelerates. Each exception handler internally creates a SAVEPOINT, even when no explicit savepoint is declared.
Idle Sessions Holding MXID References Open
Long-running idle-in-transaction sessions hold their MXID references open, preventing PostgreSQL's autovacuum from cleaning up old multixact entries. As the MXID space grows without cleanup, the SLRU cache (fixed at 8 pages) cannot hold all active pages simultaneously. New MXID lookups begin evicting cached pages, and under concurrency the eviction/reload cycle itself creates LWLock contention.
VACUUM FREEZE During High Concurrency
When autovacuum runs VACUUM FREEZE to prevent MXID wraparound, it reads and resolves every MXID on every row in the table. During this process it holds SLRU buffer locks for each lookup. Concurrent application sessions needing the same SLRU pages must wait; generating MultiXactOffsetSLRU wait events even when the underlying cause is a routine maintenance operation.
How to Diagnose This in Real Time
Step 1: Confirm Active Wait Events
Start by querying pg_stat_activity to confirm which sessions are actively waiting on MultiXact SLRU events. Use \watch 1 to refresh every second since SLRU LWLocks are held for microseconds and brief spikes can be missed. Pay close attention to the wait_event column, MultiXactOffsetSLRU and MultiXactMemberSLRU indicate pure lock contention on cached pages, while MultiXactOffsetBuffer indicates the page was evicted from cache and is being reloaded from disk.
SELECT pid, wait_event_type, wait_event, state
, now() - query_start AS duration, left(query, 100) AS query
FROM pg_stat_activity
WHERE wait_event IN ( 'MultiXactOffsetSLRU', 'MultiXactMemberSLRU', 'MultiXactOffsetBuffer' )
ORDER BY duration DESC;
Step 2: Distinguish Lock Contention From Disk I/O
Once wait events are confirmed, determine whether the root cause is cache under sizing (disk I/O problem) or LWLock queue depth (lock contention problem). These look identical in pg_stat_activity but require completely different fixes. Query pg_stat_slru and focus on the blks_read and blks_zeroed columns. A blks_read = 0 alongside active wait events is the definitive signature of pure lock contention: the cache is warm but the LWLock protecting each buffer slot is the bottleneck.
SELECT name, blks_hit, blks_read, blks_zeroed, flushes
, ROUND(100.0 * blks_hit / NULLIF(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_slru
WHERE name LIKE 'MultiXact%';
|
Interpretation |
Meaning |
|
blks_read = 0 AND wait events are present |
Pure lock contention — the cache is warm, the lock is the bottleneck |
|
blks_read > 0 AND wait events are present |
Cache miss + lock contention — the SLRU cache is undersized |
|
blks_zeroed are increasing rapidly |
High MXID creation rate — inspect application pattern issues |
|
flushes are high (2,000+) |
Frequent checkpoint SLRU flushes holding an exclusive lock |
Step 3: Check MXID Age and Identify Hot Tables
A high MXID age means autovacuum is not keeping pace with MXID creation. This causes the MXID space to span far more SLRU pages than the 8-slot cache can hold, directly worsening lock contention. Check MXID age at both the database and table level. Any database approaching 1.5 billion should be treated as a critical incident. At the table level, focus on tables with the highest mxid_age combined with high row counts and stale last_autovacuum timestamps — these are your primary VACUUM FREEZE targets.
-- Database-level MXID age (watch for values > 1 billion)
SELECT datname, mxid_age(datminmxid) AS mxid_age
FROM pg_database
ORDER BY mxid_age DESC;
-- Table-level — find the worst offenders
SELECT relname, mxid_age(relminmxid) AS mxid_age
, pg_size_pretty(pg_total_relation_size(oid)) AS table_size, n_live_tup
FROM pg_stat_user_tables t
JOIN pg_class c USING (relname)
WHERE c.relkind = 'r'
ORDER BY mxid_age DESC
LIMIT 10;
Step 4: Find Queries Driving MXID Creation
Once the hot tables are identified, use pg_stat_statements to pinpoint the specific queries generating MXIDs at a high rate. Focus on queries using FOR UPDATE, FOR KEY SHARE, or FOR SHARE, as these are the direct triggers for concurrent row locking. Also watch for INSERT-heavy workloads on child tables with FK references, as these implicitly acquire FOR KEY SHARE on parent rows and are a common hidden driver of MXID creation.
SELECT left(query, 200) AS query, calls, mean_exec_time::numeric(10,2) AS avg_ms
FROM pg_stat_statements
WHERE query ILIKE '%for update%'
OR query ILIKE '%for key share%'
OR query ILIKE '%for share%'
ORDER BY calls DESC
LIMIT 10;
Step 5: Catch Long-Running Idle Transactions
Idle-in-transaction sessions are one of the most damaging contributors to SLRU contention. They hold row-level locks while doing nothing, preventing autovacuum from cleaning up MXIDs and forcing other sessions to queue on the same SLRU pages indefinitely. Query pg_stat_activity filtered to idle-in-transaction states and focus on sessions idle for more than 2 minutes; these are almost always stuck client tool connections (DBeaver, pgAdmin) or misbehaving application threads that opened a transaction and never committed.
SELECT pid, usename, application_name, state, now() - xact_start AS txn_age
, now() - state_change AS idle_duration, left(query, 100) AS last_query
FROM pg_stat_activity
WHERE state IN ('idle in transaction', 'idle in transaction (aborted)')
AND now() - state_change > interval '2 minutes'
ORDER BY idle_duration DESC;
Fixes and Mitigation Strategies
- Terminate long-running idle-in-transaction sessions
The fastest way to break the contention cycle during an active incident is to terminate sessions holding locks while idle. This immediately releases row-level locks, unblocks autovacuum, and allows MXID cleanup to resume. Always preview before terminating to avoid disrupting legitimate long-running batch jobs.
-- Preview candidates first
SELECT pid, usename, application_name, now() - state_change AS idle_duration
FROM pg_stat_activity
WHERE state = 'idle in transaction'
AND now() - state_change > interval '5 minutes'
ORDER BY idle_duration DESC;
--then run the terminate
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction'
AND now() - state_change > interval '5 minutes';
- Set timeouts to prevent recurrence
After immediate relief, set timeouts to automatically kill idle-in-transaction sessions before they accumulate again. Both parameters take effect immediately via pg_reload_conf() with no server restart required. Choose values appropriate to your workload, use more aggressive for high-concurrency OLTP, more lenient for batch or reporting workloads.
ALTER SYSTEM SET idle_in_transaction_session_timeout = 'XXmin';
ALTER SYSTEM SET statement_timeout = 'XXmin';
SELECT pg_reload_conf();
- VACUUM FREEZE the most affected table
Running VACUUM FREEZE on the tables identified in Step 3 immediately clears old MXIDs from row headers, replacing them with frozen values that never require SLRU lookups. This directly reduces SLRU page access and LWLock contention. For very large tables, use INDEX_CLEANUP FALSE on the first pass for speed, then run a full vacuum during off-peak hours.
VACUUM FREEZE VERBOSE your_hot_table;
- Connection pooling
Connection pooling is the most impactful long-term fix for preventing thundering herd connection storms. PgBouncer in transaction mode absorbs connection spikes at the pooler layer, ensuring PostgreSQL never sees more simultaneous sessions than the pool size, and directly reducing the number of concurrent MXID lookups and SLRU LWLock contention. On Azure PostgreSQL Flexible Server, PgBouncer is available as a built-in feature. Simply enable it via Server Parameters (pgbouncer.enabled = ON) and connect on port 6432. No separate installation is required.
# Key PgBouncer settings for OLTP workloads
-
pool_mode = transaction # Release connection after each transaction
-
default_pool_size = 100 # Real PG connections per database/user pair
-
max_client_conn = 5000 # Total clients PgBouncer will accept
Conclusion
MultiXact SLRU wait events are deceptive. A server can show 100% cache hit ratio, nominal disk I/O, and moderate CPU, all while simultaneously stalling hundreds of sessions on a lock held for microseconds. The cache appears healthy, and the problem is invisible... until sessions start piling up.
The single most important diagnostic insight is this:
pg_stat_slru measures I/O efficiency.
pg_stat_activity measures lock contention.
A 100% hit ratio does not mean there are no problems, it means the bottleneck is the lock protecting the cached page, not the cache itself.
Once you know this, the path forward is clear. Use pg_stat_slru and pg_stat_activity together, never in isolation. Track mxid_age proactively, and do not wait for autovacuum to raise the alarm. Eliminate idle-in-transaction sessions before they become lock holders. Use the weakest lock mode that satisfies your application's consistency requirements. Use FOR NO KEY UPDATE instead of FOR UPDATE wherever possible. And deploy PgBouncer (available as a built-in feature on Azure Database for PostgreSQL Flexible Server) to absorb connection storms before they reach the SLRU layer.
MultiXact contention is not inevitable. It is the compounded result of concurrent locking patterns, under-tuned autovacuum, and unbounded connection growth, all of which are fully controllable. The earlier you instrument for it, the less likely it becomes an incident.