Postgres.fm· Nikolay Samokhvalov and Michael Christofides·· 20d ago
Postgres.fm Breaks Down the Hidden Costs of CREATE TEMP TABLE
The hidden costs of CREATE TEMP TABLE
Key Takeaway
Postgres. fm episode 193 examines the hidden costs of CREATE TEMP TABLE: dead tuples, catalog bloat, and the shared invalidation queue every session must read.
Why It Matters
When temporary tables are repeatedly created and dropped in the request path, distinguish baseline catalog churn from shared invalidation lock contention amplified by many idle sessions.
Technical Breakdown · Distilled from the original source
Private table data, visible catalog metadata
- Other sessions cannot see a temporary table’s data, but they can see its definition and statistics. Creating one adds at least 13 catalog rows, or about 31 if it has a
textcolumn; an index adds more. The episode’s correction estimates that creating and dropping two temporary tables and an index per query at 10 million queries a day produces at least 600 million catalog row changes, not 60 million.
Shared invalidation and lock contention
- Shared invalidation applies to catalog and relation caches. The circular queue holds 4,096 messages. At 2,048, the session furthest behind receives a catch-up signal and passes it along one session at a time. If the queue fills, sessions that have not read the messages are reset and must rebuild their caches; writers do not wait for them to catch up.
LWLock:SInvalWritemeasures contention for a cluster-wide lock, not time spent waiting for readers. Writers flag every session and queue cleanup scans every session, both while holding the lock, so idle sessions can amplify contention.
Commit behavior and fast-path limits
ON COMMIT DELETE ROWStruncates the table and its indexes at commit without producing dead tuples. With no idle sessions,ON COMMIT DROPcosts come mainly from catalog changes and file creation and removal; shared invalidation accounts for less than 1%.- PostgreSQL 18 raises the default number of fast-path lock slots per session from 16 to 64 and scales it with
max_locks_per_transaction. Temporary-table DDL takesAccessExclusiveLock, which never uses the fast path, so raising the setting does not eliminate thisLWLock:LockManagerwait.
Source: Postgres.fm· share.transistor.fm
PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.