Chapter 01

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.

⏱ 14 min readLevel: beginnerHands-on

Getting it running

terminal
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
Containers are for development

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

meta-commands
\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
~/.psqlrc — worth having
\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

Connection, query pipeline of parser, rewriter, planner and executor, shared memory, background processes and disk
Five layers. Chapters 4–6 each zoom into one of them.
  1. A backend process is forkedPostgreSQL uses one OS process per connection — which is why connection pooling is not optional.
  2. ParseSQL text becomes a parse tree; syntax errors surface here.
  3. RewriteViews are expanded and row-level security policies are injected.
  4. PlanThe optimiser estimates the cost of thousands of candidate plans using table statistics and picks the cheapest. This is where chapter 5 lives.
  5. ExecuteScans, joins and aggregates run, reading 8 KB pages from shared_buffers or from disk.
  6. Write-ahead logAny change is written and fsynced to the WAL before the data pages, which is what makes crash recovery and replication possible.
Why connections are expensive

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

SettingDefaultSensible valueWhy
shared_buffers128 MB25% of RAMPostgreSQL's own page cache
effective_cache_size4 GB50–75% of RAMA hint to the planner, not an allocation
work_mem4 MB16–64 MBPer sort/hash per operation — multiply by concurrency
maintenance_work_mem64 MB512 MB–2 GBSpeeds up index builds and vacuum
random_page_cost4.01.1 on SSDThe default assumes spinning disks and discourages index scans
max_connections100100–200 + a poolerHigher is usually worse
wal_compressionoffonSmaller WAL, cheaper replication
random_page_cost is the most impactful one-line change

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

psql
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'
the query that starts every performance investigation
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

the application should not own the schema
-- 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.)