Prepare Managed PostgreSQL for High Load
Go through this checklist before a traffic peak, such as a launch, a migration cutover or a seasonal spike, so that the service absorbs it.
Know Your Connection Limit
Each PostgreSQL connection is a server process with its own memory. max_connections comes with
the plan and is not a service setting, so the first question is how many connections your
application really opens.
Read the limit:
exo api get-dbaas-service-pg SERVICE_NAME -z ZONE -q '"max-connections"'Parameters:
SERVICE_NAME: name of the Managed PostgreSQL service, for examplemy-postgresql.ZONE: zone the service runs in, for examplech-gva-2.
Or from the database:
SHOW max_connections;
SHOW superuser_reserved_connections;superuser_reserved_connections is 3, and those slots are not available to avnadmin, which is
not a superuser. On a startup-4 service, for example, max_connections is 100, so 97
connections are usable. Past that limit, new connections fail with
FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute.
Count what is in use:
SELECT count(*) AS total,
count(*) FILTER (WHERE state = 'active') AS active,
count(*) FILTER (WHERE state = 'idle') AS idle,
count(*) FILTER (WHERE state = 'idle in transaction') AS idle_in_transaction
FROM pg_stat_activity
WHERE backend_type = 'client backend';Sessions idle in transaction hold locks and keep VACUUM from cleaning up. The service closes
them after idle_in_transaction_session_timeout, 24 hours on a new service: lower it before the
peak, as described in
Manage long-running queries.
Route the Application Through a Connection Pool
Every service runs PgBouncer on its own port. A pool in transaction mode lets many client
connections share a few server connections: a client connection only holds a server connection
for the duration of a transaction. Pools are created through the API. See
Manage connection pools
for creation, pool modes and the connection URI.
Size the pool on what the database can run in parallel, not on the number of clients: a pool larger
than that only moves the queue from PgBouncer into PostgreSQL. A pool can also queue clients for
too long: they fail with FATAL: query_wait_timeout.
PgBouncer parameters are set with --pg-bouncer-settings:
exo dbaas update SERVICE_NAME -z ZONE -f \
--pg-bouncer-settings '{"server_idle_timeout":300,"min_pool_size":5,"max_prepared_statements":200}'Parameters:
server_idle_timeout: seconds after which an unused server connection is closed.min_pool_size: server connections PgBouncer keeps open even when idle, so that the first requests of a burst do not wait for new connections.max_prepared_statements: protocol-level prepared statements PgBouncer tracks per connection,0to3000. A non-zero value lets drivers that prepare statements work intransactionmode.
List the available keys with exo dbaas type show pg --settings pgbouncer.
Size work_mem
work_mem is the memory one sort or hash operation may use before spilling to temporary files.
One query can use several multiples of it, in each parallel worker, in every concurrent session.
Raise it for the role or session that needs it rather than for the whole service:
ALTER ROLE reporting SET work_mem = '256MB';The service-wide default is --pg-work-mem, in MB, from 1 to 1024:
exo dbaas update SERVICE_NAME -z ZONE -f --pg-work-mem 16Before changing it, confirm that statements actually spill, with the temporary-file ranking of Identify slow queries and the plans in Optimize slow queries.
Review shared_buffers
shared_buffers is set as a percentage of the service RAM, from 20 to 60, with
--pg-shared-buffers-percentage. The default is 20%. Changing it restarts the service, so do it
well before the peak. How to judge whether it is large enough, and why a large value can hurt, is
explained in
Shared buffers and memory.
Tune Autovacuum for the Peak
Under heavy writes, autovacuum can fall behind: dead rows pile up, tables and indexes grow, and
plans degrade. The service parameters are nested in the autovacuum object of --pg-settings:
| Parameter | Default | Range | Restart |
|---|---|---|---|
autovacuum_vacuum_threshold | 50 | 0 to 2147483647 | No |
autovacuum_vacuum_scale_factor | 0.2 | 0 to 1 | No |
autovacuum_analyze_threshold | 50 | 0 to 2147483647 | No |
autovacuum_analyze_scale_factor | 0.1 | 0 to 1 | No |
autovacuum_naptime | 60 (seconds) | 1 to 86400 | No |
autovacuum_vacuum_cost_delay | 2 (ms) | -1 to 100 | No |
autovacuum_vacuum_cost_limit | -1 | -1 to 10000 | No |
autovacuum_max_workers | 3 | 1 to 20 | Yes |
log_autovacuum_min_duration | 1000 (ms) | -1 to 2147483647 | No |
With a scale factor of 0.2, a table of 500 million rows is only vacuumed after about 100 million
rows have changed. Make autovacuum start earlier and do more per round:
exo dbaas update SERVICE_NAME -z ZONE -f \
--pg-settings '{"autovacuum":{"autovacuum_vacuum_scale_factor":0.05,"autovacuum_vacuum_cost_limit":2000,"autovacuum_naptime":30}}'A parameter sent outside the autovacuum object is rejected with
Additional property autovacuum_vacuum_scale_factor is not allowed.
Or override only the busiest tables, which applies immediately:
ALTER TABLE public.orders SET (
autovacuum_vacuum_scale_factor = 0.01,
autovacuum_vacuum_threshold = 1000,
autovacuum_analyze_scale_factor = 0.02
);Check that autovacuum keeps up:
SELECT relid::regclass AS table_name,
n_live_tup,
n_dead_tup,
round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
last_autovacuum,
autovacuum_count
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;And watch the vacuums in progress during the peak:
SELECT p.pid, p.relid::regclass AS table_name, p.phase,
pg_size_pretty(p.heap_blks_total * 8192) AS total,
pg_size_pretty(p.heap_blks_scanned * 8192) AS scanned
FROM pg_stat_progress_vacuum p;Review Your Indexes
Find the statements that dominate total time with pg_stat_statements, as described in
Identify slow queries,
and the tables read sequentially at scale:
SELECT relid::regclass AS table_name,
seq_scan,
seq_tup_read,
idx_scan,
n_live_tup
FROM pg_stat_user_tables
WHERE seq_scan > 0
ORDER BY seq_tup_read DESC
LIMIT 20;Every index adds work to every write. Drop the ones nobody uses, with the query in Optimize slow queries, and build the missing ones before the peak, without blocking writes:
CREATE INDEX CONCURRENTLY orders_created_at_idx ON public.orders (created_at);
ANALYZE public.orders;Run ANALYZE on tables you have just loaded or reindexed, so that the planner does not work from
stale statistics when the traffic arrives.
Load Test a Fork
Run the load test against a fork of the service, a separate service created from its backups, so that production is not affected. See Fork a service and recover to a point in time. Create the fork on the plan you will run in production.
pgbench is part of the PostgreSQL client tools. Create its test tables in the fork, then run a
timed test:
pgbench -i -s 100 "FORK_URI"
pgbench -c 50 -j 4 -T 600 -P 30 --protocol=prepared "FORK_URI"Parameters:
FORK_URI: the connection URI of the fork, fromexo dbaas show FORK_NAME -z ZONE --uri.-i -s 100: create thepgbenchtables, with 100000 rows per unit of scale inpgbench_accounts.-c 50: concurrent client connections. Keep it below the usable connections of the plan when you connect directly.-j 4: client threads, at most the number of cores of the machine that runspgbench.-T 600: duration in seconds. Long enough for checkpoints and autovacuum to happen.-P 30: report throughput and latency every 30 seconds.--protocol=prepared: use prepared statements, as most drivers do.
Replace the built-in transactions with your own SQL as soon as the setup works:
pgbench ... -f my-workload.sql "FORK_URI". To measure what pooling brings, run the same test
against a pool URI of the fork and compare. With more pgbench clients than server connections in
the pool, some runs stall and end with query_wait_timeout; keep -c within the pool size for a
clean comparison.
Delete the fork when you are done.
Move Backups and Maintenance Away from the Peak
The daily backup starts at a time you choose:
exo dbaas update SERVICE_NAME -z ZONE -f --pg-backup-schedule 03:30Parameters:
--pg-backup-schedule: start time of the daily backup,HH:MM, in UTC.
Set the maintenance window outside the peak as well, see Maintenance windows.
Scale Before, Not During
If the expected load does not fit even after pooling, tuning and index work, move to a larger plan ahead of time: a plan change ends with a switchover that drops open connections. See Change the service plan.