Skip to main content

Databases · Advanced · 32 min

Get the clinic database ready for production

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7

You will work through a production checklist on the clinic database, from memory settings and time limits to a timed restore drill, write the results into a one-page runbook and then remove everything the series created.

On this page

Seven parts built the clinic booking database: a schema, rules the database enforces, realistic volume, indexes for the real queries, versioned migrations, least-privilege roles and point-in-time recovery. This last part is the checklist you go through before real patients book real appointments. Each step changes one thing, proves it worked and writes the result down, so you finish with a one-page runbook for whoever is on call, and then clear away the demo.

The checklist covers memory, logging, time limits for the app, finding the expensive queries, autovacuum, connection limits, a restore drill and an upgrade policy. None of it is exotic. Most production incidents on small PostgreSQL servers come from one of these being left at its default: a forgotten transaction holding locks for hours, a report that runs for twenty minutes during the morning rush, or a backup nobody had ever restored.

Everything runs on PostgreSQL 18.7, the current 18.x release. PostgreSQL 19.0 came out on 19 November 2026; step 8 covers when and how to move to it. The role names are the ones part 6 used: clinic_owner runs migrations, clinic_app is the booking app and clinic_reporting is read-only. If you chose other names, change them in the commands.

Step 1 · Size the memory settings for this server

PostgreSQL's defaults are chosen so it starts on almost anything, which means they suit almost nothing in production. shared_buffers defaults to 128 MB whether the server has 1 GB of memory or 64 GB. Start by finding out what you are working with:

Bash
sudo -u postgres psql -Atc "SHOW server_version;"
grep -E '^(MemTotal|MemAvailable):' /proc/meminfo
nproc
df -h "$(sudo -u postgres psql -Atc 'SHOW data_directory;')"

Four settings matter most, and each has a starting point you can work out from the memory figure:

  • shared_buffers is PostgreSQL's own cache, shared by every connection. A quarter of the server's memory is the starting point the PostgreSQL documentation gives. Going much higher rarely helps, because the operating system caches the same files.
  • effective_cache_size allocates nothing. It tells the planner how much of the database is likely to be cached somewhere, in shared_buffers or the operating system's page cache, which makes it more willing to use indexes. Three quarters of memory suits a server that runs only PostgreSQL.
  • work_mem is the memory one sort or hash can use before it spills to disk. It is per operation, not per connection: one query can use it several times, and every connection can run such a query at once. Divide a quarter of memory by max_connections and keep at least the 4 MB default.
  • maintenance_work_mem is used by VACUUM, CREATE INDEX and restores. A sixteenth of memory, between 64 MB and 1 GB, is a sensible range.

If the booking app runs on the same machine, which is common on a single small VPS, take those fractions of the memory you can give PostgreSQL rather than the whole figure.

This script works the values out and prints them so you can read them before applying anything:

Bash
mem_mb=$(awk '/^MemTotal:/ {print int($2 / 1024)}' /proc/meminfo)
conns=$(sudo -u postgres psql -Atc "SHOW max_connections;")
shared_buffers_mb=$(( mem_mb / 4 ))
effective_cache_mb=$(( mem_mb * 3 / 4 ))
work_mem_mb=$(( mem_mb / 4 / conns ))
if [ "$work_mem_mb" -lt 4 ]; then work_mem_mb=4; fi
maintenance_mb=$(( mem_mb / 16 ))
if [ "$maintenance_mb" -lt 64 ]; then maintenance_mb=64; fi
if [ "$maintenance_mb" -gt 1024 ]; then maintenance_mb=1024; fi
echo "memory=${mem_mb}MB max_connections=${conns}"
echo "shared_buffers=${shared_buffers_mb}MB effective_cache_size=${effective_cache_mb}MB work_mem=${work_mem_mb}MB maintenance_work_mem=${maintenance_mb}MB"

On a 2 GB VPS, a common starting size for a small server, that comes to 512 MB, 1536 MB, 5 MB and 128 MB. If you plan to lower max_connections once PgBouncer is in front (step 6), you can raise work_mem to match.

Apply them with ALTER SYSTEM, which writes to postgresql.auto.conf in the data directory, so your edits to postgresql.conf and the package's defaults stay separate. Run this in the same terminal, because it uses the variables the script set:

Bash
sudo -u postgres psql -v ON_ERROR_STOP=1 <<SQL
ALTER SYSTEM SET shared_buffers = '${shared_buffers_mb}MB';
ALTER SYSTEM SET effective_cache_size = '${effective_cache_mb}MB';
ALTER SYSTEM SET work_mem = '${work_mem_mb}MB';
ALTER SYSTEM SET maintenance_work_mem = '${maintenance_mb}MB';
SELECT pg_reload_conf();
SQL
echo "$shared_buffers_mb" > ~/clinic-db/shared_buffers_mb.txt

A reload applies settings that can change while the server runs. shared_buffers needs a restart, which step 2 does once for everything. Ask PostgreSQL what is waiting:

Bash
sudo -u postgres psql -c "SELECT name, setting, unit, pending_restart FROM pg_settings WHERE name IN ('shared_buffers', 'effective_cache_size', 'work_mem', 'maintenance_work_mem');"

Check it worked

The last query lists the four settings. effective_cache_size, work_mem and maintenance_work_mem already show the new values and pending_restart is f. shared_buffers still shows the old value (as a number of 8 kB pages) with pending_restart set to t.

Step 2 · Log slow statements and load pg_stat_statements

When a receptionist says the diary was slow at ten past nine, you need the server log to say which statement was slow, for whom and for how long. Four logging settings cover most of what you need:

  • log_min_duration_statement = 250ms logs every statement that takes longer, with its text and duration. Start at 250 ms for a booking app, where a screen should load in well under a second, and lower it once the log is quiet.
  • log_line_prefix adds the user and database to each line. The default, '%m [%p] ', gives only the time and process ID.
  • log_lock_waits = on logs any session that waits longer than deadlock_timeout (1 second by default) for a lock. It is off by default.
  • log_temp_files = 10MB logs any query that spills more than 10 MB to disk, the sign that work_mem is too small for it.

pg_stat_statements, which step 4 uses, has to be loaded when the server starts, through shared_preload_libraries. Setting that replaces its current value, so first check what is in it. This keeps anything already listed and adds pg_stat_statements only if it is missing:

Bash
current=$(sudo -u postgres psql -Atc "SHOW shared_preload_libraries;" | tr -d ' ')
case ",$current," in
  *,pg_stat_statements,*) libs="$current" ;;
  ,,) libs="pg_stat_statements" ;;
  *) libs="$current,pg_stat_statements" ;;
esac
echo "shared_preload_libraries will be: $libs"

Then apply all five settings:

Bash
sudo -u postgres psql -v ON_ERROR_STOP=1 <<SQL
ALTER SYSTEM SET log_min_duration_statement = '250ms';
ALTER SYSTEM SET log_line_prefix = '%m [%p] %q%u@%d ';
ALTER SYSTEM SET log_lock_waits = on;
ALTER SYSTEM SET log_temp_files = '10MB';
ALTER SYSTEM SET shared_preload_libraries = '${libs}';
SQL

Restart PostgreSQL so the memory settings from step 1 and the new library take effect. A restart drops every connection, so on a live clinic pick a quiet moment, such as before opening:

Bash
sudo systemctl restart postgresql

Confirm the new values, then run a statement that is slower than the threshold:

Bash
sudo -u postgres psql -c "SELECT name, current_setting(name) FROM pg_settings WHERE name IN ('shared_buffers', 'shared_preload_libraries', 'log_min_duration_statement');"
sudo -u postgres psql -d clinic -c "SELECT pg_sleep(0.5);"

Read the end of the server log:

Bash
sudo tail -n 5 /var/log/postgresql/postgresql-18-main.log

Check it worked

shared_buffers shows the value the script printed in step 1, shared_preload_libraries includes pg_stat_statements and log_min_duration_statement is 250ms. The log ends with a line something like 2026-11-18 08:02:11.482 UTC [4120] postgres@clinic LOG: duration: 500.912 ms statement: SELECT pg_sleep(0.5);, with the user and database after the process ID.

Step 3 · Put time limits on the app role

A web request that takes 30 seconds has already failed: the patient has closed the page. The query behind it is still running, though, holding a connection and perhaps locks. A transaction someone opened and forgot (a crashed worker, a developer's terminal left at BEGIN) is worse: it holds locks until the connection closes and stops autovacuum cleaning up rows it might still see.

Set limits on the roles, so they apply to every connection those roles make, whatever the app code does. IN DATABASE clinic keeps them to this database:

Bash
sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL'
ALTER ROLE clinic_app IN DATABASE clinic SET statement_timeout = '5s';
ALTER ROLE clinic_app IN DATABASE clinic SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE clinic_app IN DATABASE clinic SET lock_timeout = '3s';
ALTER ROLE clinic_reporting IN DATABASE clinic SET statement_timeout = '2min';
ALTER ROLE clinic_reporting IN DATABASE clinic SET idle_in_transaction_session_timeout = '5min';
SQL
sudo -u postgres psql -c '\drds clinic_*'

What each one does:

  • statement_timeout cancels any statement that runs longer. Five seconds is generous for the booking screens; the reporting role gets two minutes, because a month-end report legitimately takes longer.
  • idle_in_transaction_session_timeout closes a connection that has sat inside an open transaction, doing nothing, for longer than the limit.
  • lock_timeout makes a statement give up if it waits more than 3 seconds for a lock, instead of queueing behind a migration.

PostgreSQL 17 added transaction_timeout, which limits a whole transaction, however busy. Leave it off for now; it is easy to set too low for a legitimate batch job.

Settings like these are read when a connection starts. Connections that are already open keep the old values, so restart the app or its connection pool after a change. SET ROLE clinic_app from a superuser session does not apply them either, so test by logging in as the role. Enter the clinic_app password from part 6 when asked:

Bash
psql -h localhost -U clinic_app -d clinic <<'SQL'
SHOW statement_timeout;
SELECT pg_sleep(10);
SQL

To see the idle limit act without waiting 30 seconds, lower it for one session, open a transaction and let psql pause for two seconds with \! sleep 2:

Bash
psql -h localhost -U clinic_app -d clinic <<'SQL'
SET idle_in_transaction_session_timeout = '1s';
BEGIN;
SELECT 1;
\! sleep 2
SELECT 2;
SQL

Check it worked

\drds lists five settings across the two roles, each against the clinic database. The first session prints 5s, then about five seconds later ERROR: canceling statement due to statement timeout, not after ten. The second ends with FATAL: terminating connection due to idle-in-transaction timeout and a message that the connection to the server was lost: the server closed the forgotten transaction and released everything it held.

Step 4 · Find the most expensive queries with pg_stat_statements

The slow-query log shows single slow statements. It does not show the 8 ms query that runs 200,000 times a day and costs more in total than any report. pg_stat_statements does: it groups statements by shape, with literal values replaced by $1, $2 and so on, and adds up their calls and time. Create it in the clinic database:

Bash
sudo -u postgres psql -d clinic -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;"

On a live server you would wait a day of normal traffic. To see it work now, replay a short burst of the booking app's two busiest reads with pgbench, which ships with PostgreSQL. The \set lines pick a random clinic and patient for each run:

Bash
cat > /tmp/clinic-workload.sql <<'SQL'
\set clinic random(1, 20)
\set patient random(1, 200000)
SELECT a.starts_at, a.status FROM appointments a WHERE a.clinic_id = :clinic AND a.starts_at >= current_date AND a.starts_at < current_date + 1 ORDER BY a.starts_at;
SELECT a.starts_at, a.status, a.fee FROM appointments a WHERE a.patient_id = :patient ORDER BY a.starts_at DESC LIMIT 20;
SQL
sudo -u postgres psql -d clinic -c "SELECT pg_stat_statements_reset();"
sudo -u postgres pgbench -n -c 4 -t 250 -f /tmp/clinic-workload.sql clinic
rm /tmp/clinic-workload.sql

-c 4 -t 250 runs four clients, 250 transactions each; -n skips the vacuum pgbench otherwise runs on its own test tables, which do not exist here. Now list the top statements by total time:

Bash
sudo -u postgres psql -d clinic -c "SELECT calls, round(total_exec_time::numeric, 1) AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms, rows, left(regexp_replace(query, '\s+', ' ', 'g'), 70) AS query FROM pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = 'clinic') ORDER BY total_exec_time DESC LIMIT 5;"

Read the columns in this order. total_ms is what the query costs the server overall, so it decides what to work on first. mean_ms tells you whether a single call is slow, which matters for a screen a person is waiting on. calls divided by the period tells you how often it runs. Take the top statement, run it with real values under EXPLAIN (ANALYZE, BUFFERS) as in part 4, and fix the plan, not the symptoms.

Check it worked

The diary and patient history queries are at or near the top, each with calls of 1000 and $1 where the clinic or patient ID was. Their mean_ms is a few milliseconds at most, because part 4's indexes serve both.

Step 5 · Check that autovacuum is keeping up

Every update and delete leaves a dead row version behind. Autovacuum removes them, but by default it waits until a fifth of a table has changed (autovacuum_vacuum_scale_factor = 0.2). On 3 million appointments that is 600,000 dead rows before the first clean-up. PostgreSQL 18 caps the trigger with autovacuum_vacuum_max_threshold, but that defaults to 100 million rows, far above this table. The vacuum tutorial (/tutorials/keep-postgresql-healthy-with-vacuum-and-autovacuum) covers how it works; here you check it and tune the one table that matters.

Look at dead rows and when each table was last cleaned:

Bash
sudo -u postgres psql -d clinic -c "SELECT relname, n_live_tup, n_dead_tup, round(100.0 * n_dead_tup / greatest(n_live_tup, 1), 1) AS dead_pct, greatest(last_vacuum, last_autovacuum) AS last_vacuumed, greatest(last_analyze, last_autoanalyze) AS last_analyzed FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 5;"

Then check two things that stop autovacuum doing its job. A long-open transaction stops it removing any row that transaction might still see, and transaction ID age shows how close each database is to a forced anti-wraparound vacuum (at autovacuum_freeze_max_age, 200 million by default):

Bash
sudo -u postgres psql -c "SELECT pid, usename, state, now() - xact_start AS open_for FROM pg_stat_activity WHERE xact_start IS NOT NULL AND backend_type = 'client backend' ORDER BY xact_start LIMIT 5;"
sudo -u postgres psql -c "SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY 2 DESC;"

Appointments change all day (booked, then completed, cancelled or missed), so have autovacuum visit that table after 2 per cent of its rows change, and refresh its statistics after 1 per cent:

Bash
sudo -u postgres psql -d clinic -c "ALTER TABLE appointments SET (autovacuum_vacuum_scale_factor = 0.02, autovacuum_analyze_scale_factor = 0.01);"
sudo -u postgres psql -d clinic -c "SELECT relname, reloptions FROM pg_class WHERE relname = 'appointments';"

Autovacuum runs that take longer than 10 minutes are already logged, because log_autovacuum_min_duration defaults to 10min. If the log shows them on this table, look again at maintenance_work_mem.

Check it worked

No table has a dead_pct above about 20. appointments and patients are the tables to watch, and they show a vacuum and analyze time once autovacuum has visited them; small, rarely changed tables such as clinics and services may show no times at all, because they never cross autovacuum's thresholds. The open-transaction list shows nothing older than a few seconds; thanks to the previous step, the app role cannot leave one open for more than 30 seconds. Every xid_age is far below 200 million. The last query shows reloptions as {autovacuum_vacuum_scale_factor=0.02,autovacuum_analyze_scale_factor=0.01}.

Step 6 · Set connection limits and decide where PgBouncer fits

Every connection is a separate server process with its own memory, and each one can use work_mem several times over. If the booking app opens connections freely, a busy morning can exhaust max_connections, and then nobody can connect, including you. See where the server stands:

Bash
sudo -u postgres psql -c "SELECT name, setting FROM pg_settings WHERE name IN ('max_connections', 'superuser_reserved_connections', 'reserved_connections');"
sudo -u postgres psql -c "SELECT usename, state, count(*) FROM pg_stat_activity WHERE backend_type = 'client backend' GROUP BY usename, state ORDER BY count(*) DESC;"

superuser_reserved_connections (3 by default) keeps slots for superusers, so sudo -u postgres psql still works when the app has used up the rest. reserved_connections does the same for roles you grant pg_use_reserved_connections, such as a monitoring role.

Give each role a ceiling, so one misbehaving part of the system cannot crowd out the others. The reporting role gets few connections because each of its queries is heavy:

Bash
sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL'
ALTER ROLE clinic_app CONNECTION LIMIT 40;
ALTER ROLE clinic_reporting CONNECTION LIMIT 5;
ALTER ROLE clinic_owner CONNECTION LIMIT 3;
SQL
sudo -u postgres psql -c "SELECT current_setting('max_connections')::int AS max_connections, current_setting('superuser_reserved_connections')::int + current_setting('reserved_connections')::int AS reserved, sum(rolconnlimit) FILTER (WHERE rolconnlimit > 0) AS role_limits FROM pg_roles;"

The role limits plus the reserved slots should come to less than max_connections, so the limits are reached before the server's hard ceiling.

Where PgBouncer fits: once the app runs more than one server, or a framework opens a pool of connections per worker, the number of client connections grows faster than PostgreSQL wants to handle. PgBouncer sits between them. In transaction mode, hundreds of app connections share a small pool of PostgreSQL server connections, often 10 to 20 for a server like this, and a server connection goes back to the pool as soon as a transaction ends. The role settings from step 3 still apply, because PgBouncer logs in to PostgreSQL as the role. What breaks is per-session state set by the app: a plain SET lasts only until the server connection is handed to someone else, so use SET LOCAL inside a transaction instead. /tutorials/pool-postgresql-connections-with-pgbouncer sets it up.

Check it worked

The last query shows max_connections of 100 (unless you changed it), reserved of 3, and role_limits of 48, which leaves room. Logging in as clinic_reporting from six terminals at once makes the sixth fail with too many connections for role "clinic_reporting".

Step 7 · Run a timed restore drill

Part 7 set up point-in-time recovery, which is what you use after a disaster. The drill here answers two quieter questions you need answers to before a disaster: does a logical backup restore cleanly into an empty database, and how long does it take? That time is your recovery time for this method, and it belongs in the runbook.

Dump the clinic database in custom format into a drill folder, restore it into a new database and time the whole run:

Bash
mkdir -p ~/clinic-db/drill
start=$SECONDS
sudo -u postgres pg_dump -Fc -d clinic > ~/clinic-db/drill/clinic.dump
sudo -u postgres createdb clinic_drill
sudo -u postgres pg_restore --exit-on-error -d clinic_drill < ~/clinic-db/drill/clinic.dump
elapsed=$(( SECONDS - start ))
echo "Restore drill $(date -u +%Y-%m-%d): dump and restore took ${elapsed}s, dump size $(du -h ~/clinic-db/drill/clinic.dump | cut -f1)" | tee ~/clinic-db/drill/result.txt

The dump is written by your own shell, into your home folder, and read back the same way, so the postgres user never needs access to that folder. Now compare the two databases:

Bash
for db in clinic clinic_drill; do
  sudo -u postgres psql -d "$db" -Atc "SELECT '$db', (SELECT count(*) FROM appointments), (SELECT count(*) FROM patients), (SELECT max(id) FROM appointments), (SELECT count(*) FROM pg_indexes WHERE tablename = 'appointments');"
done

A drill that is not compared is not a drill. Checking that the counts, the newest ID and the number of indexes match catches a dump that stopped early or a restore that skipped objects. When you are satisfied, drop the copy:

Bash
sudo -u postgres dropdb clinic_drill
rm ~/clinic-db/drill/clinic.dump

Repeat the drill every month, and restore part 7's base backup with WAL replay at least once a quarter, on a separate machine if you can. A restore that only ever ran on the server it backs up does not prove you can recover from losing that server.

Check it worked

result.txt holds one line with today's date, the time in seconds and the dump size. The two rows of the comparison are identical apart from the database name. sudo -u postgres psql -c '\l clinic*' lists only clinic.

Step 8 · Set the upgrade policy and write the runbook

PostgreSQL ships a minor release (18.6, 18.7, and so on) for every supported version at least once a quarter. Minor releases contain only fixes, often security fixes, never format changes: install them promptly, restart, and you are done. See what you are running and what is available:

Bash
sudo -u postgres psql -Atc "SHOW server_version;"
apt-cache policy postgresql-18

To apply a minor release:

Bash
sudo apt update
sudo apt install --only-upgrade postgresql-18
sudo systemctl restart postgresql

Read the release notes for each one first: some ask you to rebuild a kind of index or run a check after upgrading.

A major release (18 to 19) changes the on-disk format and needs planning. Each major version gets five years of fixes; 18 is supported until 14 November 2030, so there is no rush to move to 19.0, released on 19 November 2026. A sensible policy is to move once the new major has had two or three minor releases. The tool is pg_upgrade (Ubuntu's pg_upgradecluster -m upgrade runs it for you; without -m it dumps and restores instead): run it with --check first, then for real on a copy of production, then in a planned window. --link or the new --swap mode avoid copying every data file, so the window is minutes rather than hours. PostgreSQL 18's pg_upgrade also carries the planner statistics across, so queries do not run on guesses until the first ANALYZE. Test the app against the new version before the window, not during it.

Now write everything this part found into one page. The script fills in the live values from the server; the rest is the procedure to follow. It writes to ~/clinic-runbook.md, outside the folder the next step removes:

Bash
pgq() { sudo -u postgres psql -d clinic -Atc "$1"; }
{
  echo "# Clinic database runbook"
  echo
  echo "Generated $(date -u +%Y-%m-%d). Server $(uname -n): $(nproc) CPUs, $(awk '/^MemTotal:/ {print int($2 / 1024)}' /proc/meminfo) MB memory."
  echo "PostgreSQL $(pgq 'SHOW server_version'), data directory $(pgq 'SHOW data_directory')."
  echo
  echo "## Settings"
  pgq "SELECT '- ' || name || ' = ' || current_setting(name) FROM pg_settings WHERE name IN ('shared_buffers', 'effective_cache_size', 'work_mem', 'maintenance_work_mem', 'max_connections', 'log_min_duration_statement', 'shared_preload_libraries') ORDER BY name"
  echo
  echo "## Roles"
  pgq "SELECT '- ' || r.rolname || ' (connection limit ' || r.rolconnlimit || '): ' || coalesce(array_to_string(s.setconfig, ', '), 'no settings') FROM pg_roles r LEFT JOIN pg_db_role_setting s ON s.setrole = r.oid WHERE r.rolname LIKE 'clinic\_%' ORDER BY r.rolname"
  echo
  echo "## Backups"
  echo "- Last restore drill: $(cat ~/clinic-db/drill/result.txt)"
  echo "- Point-in-time recovery: base backup plus WAL archive, as set up in part 7. Restore it on another machine every quarter."
  cat <<'EOF'

## Daily and weekly checks
- Top queries: SELECT calls, total_exec_time, mean_exec_time, query FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;
- Slow statements: grep 'duration:' /var/log/postgresql/postgresql-18-main.log
- Dead rows and last vacuum: pg_stat_user_tables (n_dead_tup, last_autovacuum)
- Old open transactions: pg_stat_activity where xact_start is more than a minute ago
- Connections per role and state: pg_stat_activity grouped by usename, state
- Disk space on the data directory and the WAL archive: df -h

## When the app reports errors
1. Check the server is up: pg_isready, then sudo systemctl status postgresql.
2. Look for too many connections, statement timeouts or lock waits in the server log.
3. Find blocked sessions: SELECT pid, pg_blocking_pids(pid), state, query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;
4. Cancel a runaway query with SELECT pg_cancel_backend(<pid>); terminate only if cancel fails.

## Upgrades
- Minor releases: install within two weeks of release, after reading the notes.
- Major releases: move after the new version's second or third minor release, with pg_upgrade --check, a rehearsal on a copy, then a planned window.
EOF
} > ~/clinic-runbook.md
cat ~/clinic-runbook.md

Add the people to call, where the backups are copied off the server, and anything specific to your setup. Keep the file with the app's code or your team's documentation, and update it whenever you change one of these settings.

Check it worked

apt-cache policy shows the installed postgresql-18 version and the candidate; if the candidate is newer, schedule the minor upgrade. The runbook prints with real values: your shared_buffers, the three roles with their limits and timeouts, and the drill line from the previous step.

Step 9 · Clean up the series

This is the last part, so it removes what the series created: the clinic database, its three roles, part 7's archiving settings and archive folder, the ~/clinic-demo folder from parts 1 to 5, the dbmate binary part 5 installed, the three clinic_* lines part 6 added to ~/.pgpass, and this part's ~/clinic-db working folder. Your runbook in ~/clinic-runbook.md stays.

First list what exists, so you know what the commands below will remove:

Bash
sudo -u postgres psql -c '\l clinic*'
sudo -u postgres psql -c '\du clinic*'
sudo -u postgres psql -c "SELECT name, setting FROM pg_settings WHERE name IN ('archive_mode', 'archive_command');"

If the list shows a database you restored in part 7 under another name, add a DROP DATABASE line for it below.

The next command deletes the clinic database and every row in it, and closes any open connections to it. Run it only on the server you used for this series, never where a real clinic's data lives:

Bash
sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL'
DROP DATABASE IF EXISTS clinic_drill;
DROP DATABASE IF EXISTS clinic WITH (FORCE);
DROP ROLE IF EXISTS clinic_app, clinic_reporting, clinic_owner;
SQL

If DROP ROLE fails with role "..." cannot be dropped because some objects depend on it, the error names the database where the role still owns something or holds a privilege. Connect to that database, run DROP OWNED BY <role name>; (replace the placeholder with the role from the error), and run the DROP ROLE again.

Turn off WAL archiving before deleting its folder. If you delete the folder first, every attempt to archive fails, and PostgreSQL keeps the WAL it could not archive in pg_wal until the disk fills:

Bash
sudo -u postgres psql -v ON_ERROR_STOP=1 <<'SQL'
ALTER SYSTEM RESET archive_command;
ALTER SYSTEM RESET archive_mode;
ALTER SYSTEM RESET archive_timeout;
ALTER SYSTEM RESET restore_command;
ALTER SYSTEM RESET recovery_target_time;
SQL

The first three undo the ALTER SYSTEM SET lines from part 7. Part 7 put restore_command and recovery_target_time in conf.d/pitr.conf and deleted that file, so the last two are only a safety net in case you also set them with ALTER SYSTEM; resetting a setting that was never set does nothing.

archive_mode needs a restart:

Bash
sudo systemctl restart postgresql

Now delete the files. rm -rf removes a folder and everything in it without asking and cannot be undone, so read each path before you press Enter. The first command deletes part 7's WAL archive and base backups in /var/lib/postgresql/pitr; if you chose another folder in part 7, use that path instead. The second deletes ~/clinic-demo, including the .env file that holds clinic_owner's password, and this part's ~/clinic-db:

Bash
sudo rm -rf /var/lib/postgresql/pitr
rm -rf ~/clinic-demo ~/clinic-db

Remove the dbmate binary part 5 installed. Skip this if you use dbmate for other projects:

Bash
sudo rm /usr/local/bin/dbmate

Finally, take the clinic_app, clinic_owner and clinic_reporting lines out of ~/.pgpass, so the passwords do not outlive the roles. This deletes only lines for the clinic database and those three roles, then removes the file if nothing else is left in it, which is the case if part 6 created it:

Bash
if [ -f ~/.pgpass ]; then
  sed -i '/^localhost:5432:clinic:clinic_\(app\|owner\|reporting\):/d' ~/.pgpass
  [ -s ~/.pgpass ] || rm ~/.pgpass
fi

If you wrote those lines with a different host or port, open ~/.pgpass in your editor and delete them by hand.

The memory, logging and pg_stat_statements settings stay, because they suit this server whatever runs on it next. If the server is going back to its original state, ALTER SYSTEM RESET ALL; followed by a restart removes every setting made with ALTER SYSTEM, including any from other projects.

Check it worked

\l clinic* and \du clinic* list nothing and archive_mode shows off. ls ~/clinic-demo ~/clinic-db /var/lib/postgresql/pitr reports that none of them exists, command -v dbmate prints nothing, grep clinic_ ~/.pgpass finds no lines (or reports that the file is gone), and ~/clinic-runbook.md is still there.

Next steps

  • Put PgBouncer in front of the app before you add a second app server: /tutorials/pool-postgresql-connections-with-pgbouncer.
  • Go deeper on the dead rows and freeze ages you checked in step 5: /tutorials/keep-postgresql-healthy-with-vacuum-and-autovacuum.
  • Turn the top statements from pg_stat_statements into better plans: /tutorials/speed-up-slow-postgres-queries-with-explain.
  • Rehearse the full point-in-time recovery from part 7 on a fresh machine: /tutorials/recover-the-clinic-database-to-a-point-in-time.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.