Administration
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page covers the operational chores of a PostgreSQL server: who may do what, how connections are
authenticated, how configuration is changed, how dead rows are cleaned up, and how to see what the server is
doing. Every command was executed on PostgreSQL 18.6 (postgres:latest, container pg-b) with the shop schema
from Getting Started; long outputs are trimmed where stated. For the
SQL syntax of GRANT and REVOKE in general see DCL, and for how the server is built
see Architecture.
Roles and attributes
PostgreSQL has a single concept, the role. A role with LOGIN is what other systems call a user; a role without it
is a group. Roles are cluster-wide (shared by all databases) and can be members of other roles, inheriting their
privileges.
CREATE ROLE app_read NOLOGIN;
CREATE ROLE app_write NOLOGIN IN ROLE app_read;
CREATE ROLE alice LOGIN PASSWORD 'secret' IN ROLE app_write;
CREATE ROLE bob LOGIN PASSWORD 'secret' CONNECTION LIMIT 5 VALID UNTIL '2030-01-01';
SELECT rolname, rolcanlogin, rolsuper, rolcreatedb, rolconnlimit, rolvaliduntil
FROM pg_roles WHERE rolname IN ('app_read','app_write','alice','bob') ORDER BY 1;
rolname | rolcanlogin | rolsuper | rolcreatedb | rolconnlimit | rolvaliduntil -----------+-------------+----------+-------------+--------------+------------------------ alice | t | f | f | -1 | app_read | f | f | f | -1 | app_write | f | f | f | -1 | bob | t | f | f | 5 | 2030-01-01 00:00:00+00
The most important attributes are:
| Attribute | Effect |
|---|---|
|
Role may open a connection |
|
Bypasses every permission check; keep it for administrators only |
|
May create databases or manage other roles |
|
May connect as a streaming replication client (see Replication & High Availability) |
|
Ignores row-level security policies |
|
Maximum concurrent connections for this role |
|
Password expiry timestamp |
|
Whether membership grants privileges automatically |
The pattern above, group roles that own privileges and login roles that join the groups, keeps GRANT statements
short and makes offboarding a one-line DROP ROLE.
GRANT, REVOKE and default privileges
A new object is usable only by its owner (and superusers). Privileges are granted per object type:
GRANT USAGE ON SCHEMA shop TO app_read;
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO app_read;
GRANT INSERT, UPDATE ON shop.orders, shop.order_items TO app_write;
ALTER DEFAULT PRIVILEGES IN SCHEMA shop GRANT SELECT ON TABLES TO app_read;
GRANT ... ON ALL TABLES affects only tables that exist now. ALTER DEFAULT PRIVILEGES applies to tables the granting
role creates in future. Inspect the result with \dp and \ddp:
postgres=# \dp shop.orders
Schema | Name | Type | Access privileges | Column privileges | Policies
--------+--------+-------+----------------------------+-------------------+----------
shop | orders | table | postgres=arwdDxtm/postgres+| |
| | | app_read=r/postgres +| |
| | | app_write=aw/postgres | |
postgres=# \ddp
Default access privileges
Owner | Schema | Type | Access privileges
----------+--------+-------+---------------------
postgres | shop | table | app_read=r/postgres
The letters are r SELECT, a INSERT, w UPDATE, d DELETE, D TRUNCATE, x REFERENCES, t TRIGGER and m
MAINTAIN (added in PostgreSQL 17). The privilege system is layered, so a missing schema USAGE blocks table access even
when the table privilege exists:
SET ROLE bob;
SELECT count(*) FROM shop.orders;
ERROR: permission denied for schema shop
alice inherits app_read through app_write, so she can read and update, but cannot delete:
SET ROLE alice; SELECT count(*) FROM shop.orders; -- 8 UPDATE shop.orders SET status='shipped' WHERE id=1002; -- UPDATE 1 DELETE FROM shop.orders WHERE id=1002; ERROR: permission denied for table orders
After REVOKE UPDATE ON shop.orders FROM app_write, the same UPDATE fails with permission denied for table orders.
Two hardening habits are worth adopting early: revoke the default CREATE on the public schema from everyone
(REVOKE ALL ON SCHEMA public FROM PUBLIC;, which PostgreSQL 15 and later already restricts by default), and give
applications a dedicated non-owner role so a SQL-injection bug cannot run DDL.
Schemas and search_path
A schema is a namespace inside a database. Unqualified names are resolved through search_path, whose default is
"$user", public. The first existing schema in the list is also where CREATE TABLE puts new objects.
SHOW search_path;
SET search_path = audit, shop, public;
CREATE TABLE log(id int);
SELECT schemaname, tablename FROM pg_tables WHERE tablename='log';
search_path ----------------- "$user", public schemaname | tablename ------------+----------- audit | log
search_path can be set per session, per role or per database; a role-level override is stored in
pg_db_role_setting:
ALTER ROLE alice SET search_path = audit, shop;
SELECT rolname, setconfig FROM pg_db_role_setting s JOIN pg_roles r ON r.oid = s.setrole;
rolname | setconfig
---------+-----------------------------
alice | {"search_path=audit, shop"}
Never rely on an unqualified function call inside a SECURITY DEFINER function without pinning search_path
(ALTER FUNCTION ... SET search_path = pg_catalog, shop), because a caller could shadow it with an object in a schema
they control.
Row-level security
Row-level security (RLS) filters which rows a role can see or modify, enforced by the server rather than by every query. A policy is a predicate attached to a table.
CREATE ROLE shop_app LOGIN PASSWORD 'secret';
GRANT USAGE ON SCHEMA shop TO shop_app;
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO shop_app;
ALTER TABLE shop.orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY own_orders ON shop.orders FOR SELECT TO shop_app
USING (customer_id = current_setting('app.customer_id', true));
The application sets a session variable after authenticating the end user; current_setting(name, true) returns
NULL instead of raising an error when it is unset, so a forgotten setting shows no rows rather than all of them:
SELECT count(*) AS owner_sees FROM shop.orders; -- as superuser/owner: 8 (RLS is bypassed)
SET ROLE shop_app;
SELECT count(*) AS no_setting FROM shop.orders; -- 0
SET app.customer_id = 'c-1';
SELECT id, customer_id, status FROM shop.orders ORDER BY id;
SET app.customer_id = 'c-3';
SELECT id, customer_id, status FROM shop.orders ORDER BY id;
id | customer_id | status ------+-------------+--------- 1001 | c-1 | shipped 1002 | c-1 | open 1007 | c-1 | shipped (3 rows) id | customer_id | status ------+-------------+----------- 1004 | c-3 | shipped 1005 | c-3 | cancelled (2 rows)
Table owners and superusers bypass RLS unless the table is switched to FORCE ROW LEVEL SECURITY; roles with
BYPASSRLS always bypass it. pg_policy lists the defined policies:
polname | polcmd | polroles | pg_get_expr
------------+--------+------------+----------------------------------------------------------------
own_orders | r | {shop_app} | (customer_id = current_setting('app.customer_id'::text, true))
Use WITH CHECK on INSERT and UPDATE policies to restrict the rows a role may write, and remember that policies
add a predicate to every plan, so index the column they filter on.
Authentication: pg_hba.conf
pg_hba.conf (host-based authentication) decides, for each connection, which methods are accepted based on the
connection type, database, user and client address. Rules are matched top to bottom and the first match wins.
The official Docker image ships these rules; inspect them without opening the file through pg_hba_file_rules:
SELECT line_number, type, database, user_name, address, auth_method FROM pg_hba_file_rules;
line_number | type | database | user_name | address | auth_method
-------------+-------+---------------+-----------+-----------+---------------
117 | local | {all} | {all} | | trust
119 | host | {all} | {all} | 127.0.0.1 | trust
121 | host | {all} | {all} | ::1 | trust
124 | local | {replication} | {all} | | trust
125 | host | {replication} | {all} | 127.0.0.1 | trust
126 | host | {replication} | {all} | ::1 | trust
128 | host | {all} | {all} | all | scram-sha-256
Connections from the loopback interface are trusted (no password), and everything else requires scram-sha-256. The
effect is easy to see from inside the container: over loopback any password is accepted, but over the container’s
network address the wrong password is rejected.
$ docker exec -e PGPASSWORD=wrong pg-b psql -h 172.17.0.4 -U shop_app -d postgres -c 'select 1' psql: error: connection to server at "172.17.0.4", port 5432 failed: FATAL: password authentication failed for user "shop_app" $ docker exec -e PGPASSWORD=secret pg-b psql -h 172.17.0.4 -U shop_app -d postgres -Atc 'select current_user' shop_app
The method used to store passwords is the password_encryption setting, scram-sha-256 since PostgreSQL 14, and
the stored verifier in pg_authid.rolpassword starts with SCRAM-SHA-256$. A production pg_hba.conf looks like
this (shown as configuration, not executed here):
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer
hostssl shop app_rw 10.0.0.0/24 scram-sha-256
hostssl replication replicator 10.0.0.0/24 scram-sha-256
host all all 0.0.0.0/0 reject
Changes to pg_hba.conf take effect after SELECT pg_reload_conf();. Prefer hostssl for anything crossing a
network and always finish with an explicit reject. Password-less trust is acceptable only for loopback in
disposable containers. The standard authentication methods are scram-sha-256, peer/ident (operating system user),
cert, ldap, gss and, since 18, oauth; md5 is deprecated.
Configuration
Settings come from several layers; later layers override earlier ones:
-
built-in defaults,
-
postgresql.conf(and files it includes), -
postgresql.auto.conf, written byALTER SYSTEM, -
ALTER DATABASE ... SETandALTER ROLE ... SET, -
SETin the session orSET LOCALin a transaction.
SHOW name displays the effective value, and pg_settings explains where it came from and whether it needs a restart
(context is postmaster for restart-only parameters, sighup for reload, user for per-session):
SELECT name, context FROM pg_settings
WHERE name IN ('work_mem','shared_buffers','log_min_duration_statement') ORDER BY 1;
name | context ----------------------------+------------ log_min_duration_statement | superuser shared_buffers | postmaster work_mem | user
In the Docker image 18 the files live in /var/lib/postgresql/18/docker/ (SHOW config_file;, SHOW hba_file;).
ALTER SYSTEM edits postgresql.auto.conf without touching postgresql.conf, and pg_reload_conf() applies changes
that do not need a restart:
ALTER SYSTEM SET work_mem = '32MB';
ALTER SYSTEM SET max_connections = 150;
SELECT pg_reload_conf();
SELECT name, setting, pending_restart FROM pg_settings WHERE name IN ('work_mem','max_connections');
SELECT name, setting, applied, error FROM pg_file_settings WHERE sourcefile LIKE '%auto.conf';
name | setting | pending_restart
-----------------+---------+-----------------
max_connections | 100 | t
work_mem | 16384 | f
name | setting | applied | error
-----------------+---------+---------+------------------------------
work_mem | 32MB | t |
max_connections | 150 | f | setting could not be applied
max_connections is pending_restart = t until the server restarts, while work_mem was applied by the reload.
pg_file_settings is the tool for validating a configuration file before reloading, because it reports errors per line.
ALTER SYSTEM RESET ALL removes every ALTER SYSTEM override.
In that session SHOW work_mem still printed 16MB after the reload, because the example database had a
database-level override (ALTER DATABASE postgres SET work_mem = '16MB'), which outranks the configuration file; the
source column of pg_settings reads database. Use ALTER DATABASE ... RESET work_mem to remove it.
VACUUM and dead rows
Because of MVCC (see Transactions, Isolation & MVCC), UPDATE
and DELETE leave old row versions in place. VACUUM marks the space of dead versions reusable, updates the free
space and visibility maps, and freezes old transaction IDs. It does not normally return space to the operating
system, and it does not block reads or writes.
The following demo creates a 100,000-row table, deletes half of it and updates a third:
CREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE TABLE shop.events AS SELECT g AS id, md5(g::text) AS payload FROM generate_series(1,100000) g;
ALTER TABLE shop.events ADD PRIMARY KEY (id);
DELETE FROM shop.events WHERE id % 2 = 0;
UPDATE shop.events SET payload = 'x' WHERE id % 3 = 0;
SELECT n_live_tup, n_dead_tup, n_tup_upd, n_tup_hot_upd, n_tup_del FROM pg_stat_user_tables WHERE relname='events';
SELECT dead_tuple_count, dead_tuple_percent, free_percent FROM pgstattuple('shop.events');
n_live_tup | n_dead_tup | n_tup_upd | n_tup_hot_upd | n_tup_del
------------+------------+-----------+---------------+-----------
50000 | 66667 | 16667 | 16667 | 50000
dead_tuple_count | dead_tuple_percent | free_percent
------------------+--------------------+--------------
16687 | 13.87 | 35.57
All 16,667 updates were HOT (heap-only tuple) updates because payload is not indexed; n_dead_tup counts both
deleted and superseded versions. A plain VACUUM (VERBOSE) reports what it did (trimmed):
INFO: vacuuming "postgres.shop.events" INFO: table "events": truncated 896 to 834 pages INFO: finished vacuuming "postgres.shop.events": index scans: 1 pages: 62 removed, 834 remain, 896 scanned (100.00% of total), 0 eagerly scanned tuples: 16687 removed, 50000 remain, 0 are dead but not yet removable index scan needed: 834 pages from table (93.08% of total) had 50000 dead item identifiers removed WAL usage: 2785 records, 6 full page images, 466358 bytes, 0 buffers full
After it, pgstattuple shows zero dead tuples and 53.85% free space inside the pages, but the file shrank only from
7,176 kB to 6,712 kB: the free space is reusable by future inserts yet still allocated. VACUUM FULL rewrites the
table into a new file and returns the space, at the cost of an ACCESS EXCLUSIVE lock for the whole operation:
VACUUM FULL shop.events;
SELECT pg_size_pretty(pg_table_size('shop.events')) AS after_full, pg_size_pretty(pg_relation_size('shop.events_pkey')) AS idx;
after_full | idx ------------+--------- 2832 kB | 1112 kB
The index also shrank (2,208 kB to 1,112 kB). Avoid VACUUM FULL on live tables; use it in a maintenance window, or
rebuild online with the pg_repack extension.
| Command | Locks | Does |
|---|---|---|
|
|
Reclaims dead tuples for reuse, updates maps, freezes |
|
same |
Vacuum plus fresh planner statistics |
|
|
Rewrites the table and indexes, returns space to the OS |
Autovacuum
The autovacuum launcher runs workers in the background so manual vacuuming is rarely needed. It vacuums a table when
dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor * reltuples, and analyzes it by the
analogous analyze settings. The defaults on this server:
SELECT name, setting, unit FROM pg_settings WHERE name LIKE 'autovacuum%' ORDER BY name;
name | setting | unit ---------------------------------------+-----------+------ autovacuum | on | autovacuum_analyze_scale_factor | 0.1 | autovacuum_analyze_threshold | 50 | autovacuum_freeze_max_age | 200000000 | autovacuum_max_workers | 3 | autovacuum_naptime | 60 | s autovacuum_vacuum_cost_delay | 2 | ms autovacuum_vacuum_insert_scale_factor | 0.2 | autovacuum_vacuum_insert_threshold | 1000 | autovacuum_vacuum_scale_factor | 0.2 | autovacuum_vacuum_threshold | 50 | autovacuum_worker_slots | 16 | autovacuum_work_mem | -1 | kB
(rows for autovacuum_multixact_freeze_max_age, autovacuum_vacuum_cost_limit and autovacuum_vacuum_max_threshold
omitted.) The default scale factor of 0.2 means a 100-million-row table accumulates 20 million dead rows before it is
vacuumed. Large, busy tables should override it per table:
ALTER TABLE shop.events SET (autovacuum_vacuum_scale_factor = 0.02,
autovacuum_vacuum_threshold = 500,
autovacuum_analyze_scale_factor = 0.02);
SELECT relname, reloptions FROM pg_class WHERE relname='events';
relname | reloptions
---------+------------------------------------------------------------------------------------------------------------
events | {autovacuum_vacuum_scale_factor=0.02,autovacuum_vacuum_threshold=500,autovacuum_analyze_scale_factor=0.02}
ALTER TABLE ... RESET (...) removes the overrides. The tuning guidance (cost limits, workers, long transactions that
prevent cleanup) is in Performance Tuning.
Bloat
Bloat is space occupied by dead or reusable-but-unused tuples. Causes: autovacuum that cannot keep up, long-running
transactions or abandoned replication slots that hold back the cleanup horizon, and heavy update or delete churn. Detect
it with the pgstattuple extension (exact but scans the table) or pgstatindex for indexes:
SELECT version, avg_leaf_density, leaf_fragmentation FROM pgstatindex('shop.events_pkey');
version | avg_leaf_density | leaf_fragmentation
---------+------------------+--------------------
4 | 89.78 | 0
A leaf density far below the default 90% (for a B-tree) signals a bloated index. Fixes are REINDEX INDEX CONCURRENTLY
(online, builds a replacement alongside), VACUUM FULL (offline), or pg_repack.
Transaction ID wraparound
Transaction IDs are 32-bit, so after about two billion transactions old row versions would appear to be in the future
unless they are frozen. Vacuum freezes tuples older than vacuum_freeze_min_age, and an aggressive vacuum is forced
when a table’s age(relfrozenxid) passes autovacuum_freeze_max_age (200 million), even if autovacuum is disabled.
Monitor the age per database and per table:
SELECT datname, age(datfrozenxid) AS xid_age, current_setting('autovacuum_freeze_max_age') AS freeze_max_age
FROM pg_database ORDER BY 1;
SELECT name, setting FROM pg_settings WHERE name LIKE '%freeze%' OR name = 'vacuum_failsafe_age' ORDER BY 1;
datname | xid_age | freeze_max_age
-----------+---------+----------------
postgres | 163 | 200000000
template0 | 163 | 200000000
template1 | 163 | 200000000
name | setting
---------------------------+------------
autovacuum_freeze_max_age | 200000000
vacuum_failsafe_age | 1600000000
vacuum_freeze_min_age | 50000000
vacuum_freeze_table_age | 150000000
(autovacuum_multixact_freeze_max_age is also listed by that second query.) Alert when age(datfrozenxid) approaches a
few hundred million. The usual causes of trouble are a long-open transaction, a forgotten prepared transaction
(pg_prepared_xacts), or a stuck replication slot, each of which stops freezing from advancing. If the age nears
the failsafe point, vacuum switches to an emergency mode that skips index cleanup; the verbose vacuum output above also reports a count of
"eagerly scanned" pages, which is how PostgreSQL 18 spreads freezing work across normal vacuums.
Monitoring views
The statistics views are the first stop for any investigation. Replace guesswork with these:
SELECT backend_type, count(*) FROM pg_stat_activity GROUP BY 1 ORDER BY 2 DESC;
backend_type | count ------------------------------+------- io worker | 3 walwriter | 1 autovacuum launcher | 1 client backend | 1 background writer | 1 checkpointer | 1 logical replication launcher | 1
pg_stat_activity has one row per process, with state, wait_event_type, wait_event and query. The io worker
rows are the PostgreSQL 18 asynchronous I/O workers. pg_stat_database has per-database counters:
SELECT datname, numbackends, xact_commit, xact_rollback, blks_read, blks_hit, deadlocks FROM pg_stat_database WHERE datname='postgres';
SELECT round(100.0*sum(blks_hit)/nullif(sum(blks_hit+blks_read),0),2) AS cache_hit_pct FROM pg_stat_database;
datname | numbackends | xact_commit | xact_rollback | blks_read | blks_hit | deadlocks
----------+-------------+-------------+---------------+-----------+----------+-----------
postgres | 1 | 404 | 5 | 2569 | 196858 | 0
cache_hit_pct
---------------
98.84
pg_stat_user_tables shows scan counts, live and dead tuples and the last (auto)vacuum and analyze times, and
pg_stat_user_indexes.idx_scan identifies indexes that are never used:
relname | seq_scan | idx_scan | n_live_tup | n_dead_tup | vacuum_count -------------+----------+----------+------------+------------+-------------- customers | 2 | 8 | 4 | 0 | 0 events | 11 | 1 | 50000 | 0 | 1 order_items | 1 | 0 | 11 | 0 | 0 orders | 1 | 11 | 8 | 0 | 0 products | 1 | 11 | 5 | 0 | 0
(Trimmed to six of the columns the query returns.)
Locks and blocked sessions
With two sessions, the first updating a row inside an open transaction and the second updating the same row, the second
waits. pg_stat_activity plus pg_blocking_pids() finds the culprit:
SELECT pid, state, wait_event_type, wait_event, pg_blocking_pids(pid) AS blocked_by, left(query,45) AS query
FROM pg_stat_activity WHERE datname='postgres' AND pid <> pg_backend_pid() ORDER BY pid;
pid | state | wait_event_type | wait_event | blocked_by | query
-----+--------+-----------------+---------------+------------+-----------------------------------------------
307 | active | Timeout | PgSleep | {} | BEGIN; UPDATE shop.products SET stock=stock-1
314 | active | Lock | transactionid | {307} | UPDATE shop.products SET stock=stock-2 WHERE
pg_locks shows the lock itself; the waiter holds an ungranted ShareLock on a transactionid:
SELECT l.locktype, l.mode, l.granted, c.relname FROM pg_locks l
LEFT JOIN pg_class c ON c.oid = l.relation
WHERE l.locktype IN ('relation','transactionid','tuple') AND (c.relname IS NULL OR c.relname LIKE 'products%')
ORDER BY l.granted, l.locktype;
locktype | mode | granted | relname ---------------+------------------+---------+--------------- transactionid | ShareLock | f | relation | RowExclusiveLock | t | products_pkey relation | RowExclusiveLock | t | products ...
Resolve it by ending the blocker. pg_cancel_backend(pid) cancels the current statement; pg_terminate_backend(pid)
closes the connection and rolls back its transaction:
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE query LIKE 'BEGIN; UPDATE%' AND pid <> pg_backend_pid();
SELECT sku, stock FROM shop.products WHERE sku='A-1';
pg_terminate_backend ---------------------- t sku | stock -----+------- A-1 | 10
The terminated transaction was rolled back, so the waiting update (stock-2) then completed against the original 12,
leaving 10. To prevent sessions from lingering, set idle_in_transaction_session_timeout, lock_timeout and
statement_timeout per role (shown as configuration, not executed here). See
Transactions, Isolation & MVCC for the lock modes.
Routine maintenance
-
ANALYZErefreshes the statistics the planner depends on (ANALYZE VERBOSE shop.eventsreported "scanned 353 of 353 pages, containing 50000 live rows and 0 dead rows"). Run it after bulk loads, and after creating an expression index. -
REINDEXrebuilds indexes;REINDEX INDEX CONCURRENTLYavoids blocking writes and is the right choice online. -
CLUSTER shop.events USING events_pkeyrewrites a table in index order once (likeVACUUM FULL, it takes anACCESS EXCLUSIVElock, and the order is not maintained afterwards). -
pg_stat_reset()clears the counters of the current database; do this only deliberately, since it removes the evidence you may need. -
Log slow statements with
log_min_duration_statementand lock waits withlog_lock_waits, then analyze with Diagnosing Slow Queries.