Architecture and setup
Ten minutes to a running database, then the mental model that makes every later chapter make sense: how a query becomes a plan, and why the WAL is written before the data.
Getting it running
docker run --name pg16 \ -e POSTGRES_PASSWORD=devpassword \ -e POSTGRES_USER=oms \ -e POSTGRES_DB=oms \ -p 5432:5432 \ -v pgdata:/var/lib/postgresql/data \ -d postgres:16-alpine docker exec -it pg16 psql -U oms -d oms
A named volume survives docker compose down — but not
down -v, not a pruned volume, and not a laptop failure. Production data
belongs on a managed service with point-in-time recovery
(deployment course).
psql, the parts you need
\l list databases \dt list tables \c dbname connect \d+ orders describe a table fully \di list indexes \df list functions \dn list schemas \du list roles \x expanded output \timing show query duration \e edit in $EDITOR \i file.sql run a file \copy (SELECT …) TO 'out.csv' CSV HEADER client-side export \watch 2 re-run the last query every 2 seconds \? help on meta-commands \h SELECT help on SQL syntax
\set QUIET 1 \timing on \x auto \set COMP_KEYWORD_CASE upper \set HISTSIZE 5000 \set PROMPT1 '%[%033[1;32m%]%n@%/%[%033[0m%]%R%# ' \unset QUIET
How a query is executed
- A backend process is forkedPostgreSQL uses one OS process per connection — which is why connection pooling is not optional.
- ParseSQL text becomes a parse tree; syntax errors surface here.
- RewriteViews are expanded and row-level security policies are injected.
- PlanThe optimiser estimates the cost of thousands of candidate plans using table statistics and picks the cheapest. This is where chapter 5 lives.
- ExecuteScans, joins and aggregates run, reading 8 KB pages from
shared_buffersor from disk. - Write-ahead logAny change is written and fsynced to the WAL before the data pages, which is what makes crash recovery and replication possible.
Each backend is a process using roughly 5–10 MB. Five hundred idle connections is several gigabytes doing nothing. Bound them with HikariCP in the application, and add PgBouncer once you genuinely need more than a few hundred.
Configuration that actually matters
| Setting | Default | Sensible value | Why |
|---|---|---|---|
shared_buffers | 128 MB | 25% of RAM | PostgreSQL's own page cache |
effective_cache_size | 4 GB | 50–75% of RAM | A hint to the planner, not an allocation |
work_mem | 4 MB | 16–64 MB | Per sort/hash per operation — multiply by concurrency |
maintenance_work_mem | 64 MB | 512 MB–2 GB | Speeds up index builds and vacuum |
random_page_cost | 4.0 | 1.1 on SSD | The default assumes spinning disks and discourages index scans |
max_connections | 100 | 100–200 + a pooler | Higher is usually worse |
wal_compression | off | on | Smaller WAL, cheaper replication |
On SSDs the default of 4.0 makes the planner believe random reads are four times more
expensive than sequential ones. It therefore prefers sequential scans and ignores perfectly
good indexes. Setting it to 1.1 fixes a surprising number of "why is it not
using my index?" reports.
Extensions to enable on day one
CREATE EXTENSION IF NOT EXISTS pg_stat_statements; CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE EXTENSION IF NOT EXISTS citext; CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- pg_stat_statements needs a restart and this line in postgresql.conf: -- shared_preload_libraries = 'pg_stat_statements'
SELECT substr(query, 1, 80) AS query,
calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
Sort by total time, not mean. A 5 ms query called 400,000 times an hour costs far more than a 3-second report run twice a day.
Roles and least privilege
-- owns the schema; used only by migrations CREATE ROLE oms_owner LOGIN PASSWORD 'change-me'; -- used by the application at runtime — no DDL CREATE ROLE oms_app LOGIN PASSWORD 'change-me'; GRANT CONNECT ON DATABASE oms TO oms_app; GRANT USAGE ON SCHEMA public TO oms_app; GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO oms_app; GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO oms_app; -- applies to tables created later by the owner ALTER DEFAULT PRIVILEGES FOR ROLE oms_owner IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO oms_app; -- read-only role for analysts and BI tools CREATE ROLE oms_readonly LOGIN PASSWORD 'change-me'; GRANT CONNECT ON DATABASE oms TO oms_readonly; GRANT USAGE ON SCHEMA public TO oms_readonly; GRANT SELECT ON ALL TABLES IN SCHEMA public TO oms_readonly;
Your query has a perfectly good index but PostgreSQL uses a sequential scan. Which single setting is most often responsible?
The default cost model assumes random I/O is four times more expensive than sequential — true for spinning disks, wrong for SSDs. Lowering it to about 1.1 makes index scans look as cheap as they really are. (Stale statistics is the other common cause; see chapter 5.)