PostgreSQL 19 — what to actually use in production, from REPACK to pg_plan_advice
PostgreSQL 19 shipped on 2026-11-19. REPACK merges VACUUM FULL and CLUSTER, and REPACK (CONCURRENTLY) cleans up a table without blocking reads or writes. pg_plan_advice and pg_stash_advice stabilise plans without a hint extension. EXPLAIN (ANALYZE, IO) exposes async I/O, WAIT FOR LSN gives standbys read-your-writes, and INSERT ... ON CONFLICT DO SELECT finishes get-or-create in one round trip. Here is what to use, with the upgrade traps: io_workers removed, JIT off by default, max_locks_per_transaction doubled.
- Released
- 2026.11.19
- Online cleanup
- REPACK CONCURRENTLY
- Plan control
- pg_plan_advice
- Upgrade traps
- 3 big ones
Where to look in this release
PostgreSQL 19 was released on 19 November 2026. You do not need to read the release notes end to end. Six things actually change decisions on a running service.
| What changed | What it means | Section |
|---|---|---|
REPACK · REPACK (CONCURRENTLY) |
Merges VACUUM FULL and CLUSTER. The latter cleans up without blocking reads or writes |
1 |
pg_plan_advice · pg_stash_advice |
Constrains the planner’s choices instead of forcing a plan | 2 |
EXPLAIN (ANALYZE, IO) |
Shows async I/O queueing and request sizes | 3 |
WAIT FOR LSN |
Read-your-writes on a standby | 4 |
INSERT ... ON CONFLICT DO SELECT |
Get-or-create in one round trip | 5 |
| Planner and executor work | NOT IN → anti join, pre-join aggregation, ~2x faster FK checks |
6 |
flowchart LR
A["Move to 19"] --> B{"What hurts today"}
B -->|"Tables are bloated"| C["REPACK<br/>(CONCURRENTLY)"]
B -->|"Plans flip on you"| D["pg_plan_advice<br/>pg_stash_advice"]
B -->|"Suspect I/O waits"| E["EXPLAIN<br/>(ANALYZE, IO)"]
B -->|"Read after write on a replica"| F["WAIT<br/>FOR LSN"]
B -->|"Nothing"| G["Just the upgrade<br/>(section 7)"]
1. REPACK — cleaning up a table without downtime
Until now, reclaiming dead tuples and returning disk to the OS meant VACUUM FULL; rewriting rows in index order meant CLUSTER. The names were confusing, and both hold an ACCESS EXCLUSIVE lock for the whole operation. On a 100GB table, every query touching it queues behind it.
19 merges the two into REPACK. The old commands remain for compatibility.
-- Clean up a bloated table
REPACK orders;
-- Reorder rows by an index (the old CLUSTER)
REPACK orders USING INDEX orders_created_at_idx;
-- Refresh statistics afterwards, report progress
REPACK (ANALYZE, VERBOSE) orders (created_at);
-- Online: no blocking of reads or writes
REPACK (CONCURRENTLY) orders USING INDEX;
REPACK (CONCURRENTLY) is the interesting one. Most of the work runs under a SHARE UPDATE EXCLUSIVE lock, and ACCESS EXCLUSIVE is taken only for the final file swap.
sequenceDiagram
participant S as REPACK (CONCURRENTLY)
participant T as target table
participant O as other sessions
S->>T: SHARE UPDATE EXCLUSIVE<br/>copy into new files
O->>T: INSERT · UPDATE · DELETE keep working
S->>S: capture changes via logical decoding
S->>S: apply captured changes to the new file
S->>T: ACCESS EXCLUSIVE (briefly)
Note over S,T: swap files, release lock
O->>T: read and write as usual
How does it stay consistent without a lock? Changes that arrive during the operation are captured with logical decoding, applied to the new file, and only then does it ask for ACCESS EXCLUSIVE. Once granted, it makes a final pass over any remaining changes and swaps the files. So the lock time is proportional to how many changes piled up while waiting for the lock, which is usually short.
What to use, when
| Command | What it does | Lock | Disk |
|---|---|---|---|
VACUUM |
Marks dead tuple space reusable | SHARE UPDATE EXCLUSIVE |
File size unchanged |
VACUUM FULL |
Rewrites into a new file | ACCESS EXCLUSIVE (whole run) |
Table + indexes of free space |
CLUSTER |
Rewrites in index order | ACCESS EXCLUSIVE (whole run) |
Same |
REPACK |
Both of the above | ACCESS EXCLUSIVE (whole run) |
Same |
REPACK (CONCURRENTLY) |
Mostly SHARE UPDATE EXCLUSIVE, swap only |
Rarely blocks | Same + changes + sort file |
Finding tables worth repacking
n_dead_tup is an estimate as of the last VACUUM or ANALYZE, so use it for ranking, not as an absolute number.
SELECT relname,
n_live_tup,
n_dead_tup,
pg_size_pretty(pg_total_relation_size(relid)) AS total,
pg_size_pretty(pg_indexes_size(relid)) AS indexes,
round(100.0 * n_dead_tup / greatest(n_live_tup + n_dead_tup, 1), 1) AS dead_pct
FROM pg_stat_user_tables
WHERE n_dead_tup > 10000
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 10;
Big tables with a high dead_pct are the candidates. But heavily updated tables accumulate dead tuples even when healthy, especially with a lowered fillfactor. This is not something you schedule daily; check once or twice whether the win holds, then decide.
Conditions and traps of CONCURRENTLY
This is where it actually bites in production.
| Condition | Detail |
|---|---|
| Must be a table | No materialized views, partitioned tables, UNLOGGED tables, system catalogs or TOAST tables |
| Needs a primary key and index-based replica identity | Required for capturing changes via logical decoding |
| Not inside a transaction block | Fails under BEGIN |
| Needs replication slots | Uses up to max_repack_replication_slots (default 5); server-start only |
| Refuses invalid indexes | Clean up leftovers from a failed CREATE INDEX CONCURRENTLY first |
| Bound on concurrent changes | Fails if other sessions update or delete more than about 104 million rows during the run |
| Races with DDL | DDL on the table from another transaction can make it fail |
| Disk headroom | Table + indexes. If USING INDEX turns into a sort, a temp file the size of the table as well |
And there is the line the docs warn about:
REPACKwith theCONCURRENTLYoption is not MVCC-safe. After the repacking transaction commits, the table will appear empty to concurrent transactions, if they are using a snapshot taken before repacking started.
A transaction that took its snapshot before the repack started will see the table as empty afterwards. Run this while a two-hour batch or reporting transaction is open, and that transaction quietly returns nothing. The lock that used to protect you is gone, and so is the accident it prevented. So check pg_stat_activity first.
SELECT pid, state, now() - xact_start AS xact_age, left(query, 60) AS query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
AND now() - xact_start > interval '10 minutes'
ORDER BY xact_start;
Progress shows up in pg_stat_progress_repack.
SELECT pid, phase, heap_blks_total, heap_blks_scanned,
round(100.0 * heap_blks_scanned / nullif(heap_blks_total, 0), 1) AS pct
FROM pg_stat_progress_repack;
A runbook
-- 1) Check free space and invalid indexes
SELECT pg_size_pretty(pg_total_relation_size('orders')) AS needs_at_least;
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid AND indrelid = 'orders'::regclass;
-- 2) In a window without long-lived transactions
SET maintenance_work_mem = '1GB';
REPACK (CONCURRENTLY, VERBOSE) orders USING INDEX;
-- 3) Refresh statistics (REPACK (ANALYZE) works only on a single non-partitioned table)
ANALYZE orders;
REPACK also advances relfrozenxid, but it is not a way to prevent transaction ID wraparound. It rewrites everything, takes far longer than VACUUM, and on a busy table a CONCURRENTLY run can fail after most of the work is done. Wraparound protection is still VACUUM.
2. pg_plan_advice — stabilise plans without a hint extension
Plans change when data distribution changes, and sometimes they get much worse. Your options used to be the pg_hint_plan extension, or pinning enable_seqscan = off-style GUCs on a session. The first is operationally heavy; the second breaks ten queries while fixing one.
19 offers a third path with pg_plan_advice. It does not command a plan; it constrains the choices.
LOAD 'pg_plan_advice'; -- or shared_preload_libraries / session_preload_libraries
EXPLAIN (COSTS OFF, PLAN_ADVICE)
SELECT o.id, o.total, c.name
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= now() - interval '1 day';
The chosen plan comes with a sentence at the end.
Generated Plan Advice:
JOIN_ORDER(o c)
HASH_JOIN(c)
SEQ_SCAN(o)
INDEX_SCAN(c customers_pkey)
NO_GATHER(o c)
Keep only the parts you care about and put them in pg_plan_advice.advice.
SET pg_plan_advice.advice = 'JOIN_ORDER(o c)';
EXPLAIN (COSTS OFF) SELECT ...;
The output then shows Supplied Plan Advice: JOIN_ORDER(o c) /* matched */. Every piece of supplied advice reports whether it was fully applied, partly applied (/* partially matched */) or not — so you do not burn an afternoon on “I added a hint and nothing changed”.
| Tag | What it controls |
|---|---|
JOIN_ORDER(a b c) |
Join order |
HASH_JOIN · MERGE_JOIN · NESTED_LOOP |
Join method |
SEQ_SCAN · INDEX_SCAN(t idx) · INDEX_ONLY_SCAN(t idx) · BITMAP_HEAP_SCAN |
Scan method |
NO_GATHER (and the parallel tags) |
Parallelism |
DO_NOT_SCAN |
Keep a target out of the final plan |
It constrains, it does not force
Internally pg_plan_advice works by telling the core planner what not to do. So however you write the advice, you only ever get a plan the core planner would have considered.
- Plan advice never makes planning fail.
- Advice that asks for something impossible can produce nodes flagged
Disabled: true, and a plan worse than with no advice at all. - For example, you cannot force an index on
SELECT * FROM some_table. The planner rules out an index before any costing.
So the order is: measure why it is slow first, apply advice only to queries where the risk is high, and keep the tags minimal.
pg_stash_advice — apply by query ID
pg_plan_advice.advice is per session. To cover the whole application, use pg_stash_advice, which keeps a query ID → advice string map in shared memory and applies it whenever that query is planned.
-- 1) Server settings (restart required)
-- shared_preload_libraries = 'pg_stash_advice'
-- pg_stash_advice.stash_name = 'prod'
CREATE EXTENSION pg_stash_advice;
-- 2) Find the query ID: EXPLAIN VERBOSE prints Query Identifier
EXPLAIN (VERBOSE, COSTS OFF) SELECT ...;
-- 3) Stash the advice
SELECT pg_create_advice_stash('prod');
SELECT pg_set_stashed_advice('prod', 1234567890123456789, 'JOIN_ORDER(o c)');
-- 4) Point sessions at the stash (global, per database, or per role)
ALTER DATABASE shop SET pg_stash_advice.stash_name = 'prod';
| Worth knowing | Detail |
|---|---|
| Applied when | Only at planning time. Already cached plans are unaffected |
| Persistence | On by default (pg_stash_advice.persist) to pg_stash_advice.tsv in the data directory |
| Query ID | Needs compute_query_id; auto enables it when the module loads |
| Security | Only superusers (or delegated roles) change a stash, but any user can set stash_name and read its contents — put nothing sensitive in advice strings |
| Cost | Applying advice has a planning cost even when the plan does not change; use it sparingly |
3. EXPLAIN (ANALYZE, IO) — see whether async I/O is actually working
The async I/O subsystem arrived in 18 and got more automatic in 19. EXPLAIN now has an option to show whether it is doing anything.
EXPLAIN (ANALYZE, BUFFERS, IO)
SELECT id, status FROM orders WHERE created_at >= now() - interval '1 day';
For each scan node, IO reports the prefetch queue (average and maximum distance, queue capacity) and the I/O requests it issued (total count, average request size, number of waits, average concurrency). It only works together with ANALYZE, and in text format only non-zero values are printed.
-- auto_explain: attach it to slow queries automatically
-- auto_explain.log_min_duration = '500ms'
-- auto_explain.log_analyze = on
-- auto_explain.log_io = on
The server settings changed too.
| Setting | 18 | 19 |
|---|---|---|
io_method |
worker / io_uring / sync |
Same (worker default) |
| I/O workers | io_workers |
io_min_workers (2) to io_max_workers (8), adjusted automatically |
| Worker retirement | — | io_worker_idle_timeout (1 min), io_worker_launch_interval (100ms) |
| Combined I/O size | io_combine_limit |
Same (128kB default, capped by io_max_combine_limit) |
io_workers is gone. If you tuned it in 18 and left it in postgresql.conf, 19 will fail to start on an unrecognised parameter. Remove it and move to io_min_workers / io_max_workers.
4. WAIT FOR LSN — read-your-writes on a standby
Write to the primary, read from a replica — and every so often the row you just wrote is not there. Until now you polled pg_current_wal_lsn() against pg_last_wal_replay_lsn() from the application.
19 moves the wait into the server.
-- Remember the LSN right after the write on the primary,
-- then wait for it in the replica session
WAIT FOR LSN '0/3A2B1C8'
WITH (MODE 'standby_replay', TIMEOUT '2s', NO_THROW);
-- success | timeout | not in recovery
| Option | Meaning |
|---|---|
MODE 'standby_replay' (default) |
Wait until replayed; afterwards pg_last_wal_replay_lsn() is at or past the target |
MODE 'standby_flush' |
Flushed to disk, not necessarily applied |
MODE 'standby_write' |
Written to OS buffers (weaker durability) |
MODE 'primary_flush' |
Flushed on the primary |
TIMEOUT '2s' |
Milliseconds or a string with a unit; 0 waits forever |
NO_THROW |
Report timeout or promotion as a status string instead of an error |
NO_THROW matters in production. Without it a timeout is an error and you must roll back the transaction. With it, you must check the return value: not in recovery means you ran it on a primary, or the standby was promoted while waiting (the timeline changed, so re-evaluate whether the target LSN still means anything).
A few constraints are worth memorising.
- It must be a top-level command. Not callable from a function, procedure or
DOblock. - Not after a snapshot is taken. In
REPEATABLE READorSERIALIZABLEit works only before the first snapshot-taking statement. - Rejected while the session holds a lock (standby modes), because that lock can block replay and the cycle is invisible to deadlock detection.
- The LSN is a string literal. If you build it in the application, validate the format (
^[0-9A-F]+/[0-9A-F]+$).
The pattern:
-- primary
INSERT INTO orders (...) VALUES (...) RETURNING id, pg_current_wal_lsn() AS lsn;
-- replica (outside a transaction, before other queries)
WAIT FOR LSN '0/3A2B1C8' WITH (MODE 'standby_replay', TIMEOUT '1s');
SELECT * FROM orders WHERE id = 42;
5. INSERT … ON CONFLICT DO SELECT — get-or-create in one round trip
ON CONFLICT DO NOTHING RETURNING does not return the conflicting row, so get-or-create always took two round trips.
INSERT INTO users (email, name) VALUES ('a@example.com', 'A')
ON CONFLICT (email) DO NOTHING
RETURNING id; -- zero rows on conflict
SELECT id FROM users WHERE email = 'a@example.com'; -- second round trip
And if another session deletes that row in between, the second query finds nothing again. 19 returns the existing row right there.
INSERT INTO users (email, name) VALUES ('a@example.com', 'A')
ON CONFLICT (email) DO SELECT
RETURNING id, email, name;
RETURNING is optional; use it to get specific columns. You can lock the row as well.
-- Lock and read if it exists, insert if not
INSERT INTO counters (name, value) VALUES ('visits', 1)
ON CONFLICT (name) DO SELECT FOR UPDATE
RETURNING value;
flowchart LR
A["get-or-create"] --> B{"18 or older"}
A --> C{"19"}
B --> B1["INSERT ... DO NOTHING<br/>RETURNING"]
B1 --> B2["zero rows,<br/>SELECT again"]
B2 --> B3["2 round trips<br/>delete in between breaks it"]
C --> C1["INSERT ... DO SELECT<br/>RETURNING"]
C1 --> C2["1 round trip<br/>can lock the row"]
One privilege is new: DO SELECT needs SELECT on the table, and FOR UPDATE / FOR SHARE also needs UPDATE on at least one column. A service that only ever used DO NOTHING can hit a permission error on deploy — check before you ship.
6. Quiet wins
These get faster without touching application code.
| What | In 19 |
|---|---|
NOT IN |
Converted to an ANTI JOIN when no NULLs are present |
LEFT JOIN |
More cases become ANTI JOIN, with Memoize on unique inner sides |
| Aggregation | Aggregates computed before joins where possible (eager aggregation) |
| Foreign key checks | Improved; bulk inserts nearly 2x faster in testing |
COPY FROM |
SIMD for text and CSV input |
COPY TO |
JSON output (FORCE_ARRAY for a single array), direct output of partitioned tables |
NOTIFY |
Wakes only backends listening to the notification (it used to wake most) |
| TOAST compression | Default pglz → lz4 (wal_compression = on picks the best method too) |
| Table scans | Mark pages all-visible as they read, so later VACUUM has less to do |
EXPLAIN |
Memoize cache estimates, WAL full-page bytes in ANALYZE |
Developer conveniences too: IGNORE NULLS on lead(), lag(), first_value(), last_value(), nth_value(); random() for dates and timestamps; the unsigned 64-bit oid8; jsonpath string methods (lower(), replace(), split_part(), …); bytea ↔ uuid casts.
7. Before you upgrade
If you are moving with pg_upgrade, start here. The nastiest items break config files and monitoring queries silently.
| Item | In 19 | What to do |
|---|---|---|
io_workers |
Removed | Replace with io_min_workers / io_max_workers; a leftover entry blocks startup |
| JIT | Off by default | Set jit = on only where you run many large analytical queries |
md5 auth |
Warns even on success | Migrate to SCRAM |
| RADIUS | Removed | Use another auth method |
standard_conforming_strings |
Always on |
Old dumps with backslash escapes must be taken with the 19 pg_dump |
max_locks_per_transaction |
64 → 128 | Lock slot allocation changed, so double your old value for the same capacity |
btree_gist inet/cidr indexes |
Default opclass changed | pg_upgrade refuses clusters with them — clean up first |
| CR/LF in names | Disallowed | Fix database, role and tablespace names (upgrade is refused) |
sync_error_count |
Renamed sync_table_error_count |
Update monitoring queries |
Wait events BUFFERPIN / BufferPin |
Renamed BUFFER / BufferCleanup |
Update dashboards and alert rules |
log_lock_waits |
On by default | Expect more log volume; tune with deadlock_timeout if needed |
| TOAST compression | lz4 for new columns |
Existing columns keep their method (changing it rewrites the table) |
MULE_INTERNAL encoding |
Removed | Dump and restore in another encoding |
Full text search · pg_trgm |
Locale handling changed | After pg_upgrade, REINDEX those indexes and recompute stored tsvector values |
As a checklist:
- Delete removed parameters (
io_workers) frompostgresql.conf. - Diff
SHOW ALLbetween 18 and 19 — changed defaults (JIT,log_lock_waits,max_locks_per_transaction, TOAST compression) show up here. - Run
pg_upgrade --checkfirst to catch refusal conditions (CR/LF names,btree_gistinet/cidr). - Fix dashboards and alerts that use the renamed wait events and view columns.
- After the upgrade,
ANALYZE, then compareEXPLAIN (ANALYZE, BUFFERS)for your ten most important queries, before and after.
Wrapping up
flowchart LR
A["Move to 19"] --> B["Fix config and<br/>monitoring (io_workers, events)"]
B --> C["REPACK (CONCURRENTLY)<br/>on bloated tables"]
C --> D["pg_stash_advice only<br/>for unstable plans"]
D --> E["EXPLAIN (ANALYZE, IO)<br/>to see the I/O"]
E --> F["WAIT FOR LSN<br/>for replica reads"]
REPACK (CONCURRENTLY)cleans up without locking the table. But with a long-open transaction around, that transaction sees the table as empty — checkpg_stat_activityfirst.pg_plan_advice/pg_stash_advicenarrow the planner’s choices rather than forcing a plan. Plans the core planner never considered stay unavailable, and impossible advice can make things worse.WAIT FOR LSNsolves standby read-your-writes inside the server. Run it as the transaction’s first statement, and check the return value when you passNO_THROW.INSERT ... ON CONFLICT DO SELECTturns get-or-create into one round trip. It needsSELECTprivilege.- What breaks silently in an upgrade is usually configuration and monitoring. Check
io_workers, the JIT default, the doubledmax_locks_per_transaction, and the renamed wait events before anything else.
Comments