App basics: HTTP, auth, dataLesson 6 of 11
What Happens When an App Saves to a Database
An order app saves one order to a relational database. PostgreSQL is the example here, but MySQL and other relational databases work in a similar way. Follow the order from the app's connection pool to the query planner, through a transaction and the write-ahead log (WAL), and out to a read replica.
Connections—
Plan—
Transaction—
Replica lag—
RequestResponse / reportAppears in a later step
What you will learn
- Why apps use a connection pool and what happens when connections run out
- How the planner picks an index scan or a full table scan
- Transactions, COMMIT and the four ACID properties
- Why the WAL is written before COMMIT returns
- Replication to a read replica and stale reads from replication lag
Common database problems
| Symptom | Likely cause | What to check |
|---|---|---|
sorry, too many clients already | Total connections from all app replicas exceed max_connections | SELECT count(*) FROM pg_stat_activity;, pool size × replica count, or put a pooler such as PgBouncer in front |
| One screen is slow, DB CPU is high | Seq Scan on a large table, a missing index | EXPLAIN ANALYZE <query>, pg_stat_statements for the slowest queries |
| Requests hang, then time out | A long transaction holds a row lock | pg_stat_activity where wait_event_type = 'Lock', and pg_blocking_pids(pid) |
deadlock detected | Two transactions lock the same rows in a different order | Server log for the two statements; lock rows in one order and retry in the app |
| Data saved but not shown | Reading from a lagging replica | replay_lag in pg_stat_replication; read your own writes from the primary |
| COMMIT is slow for every write | Slow disk flush for the WAL | Disk latency on the WAL volume, WAL write and fsync time in pg_stat_io (PostgreSQL 18+) or pg_stat_wal (17 and older) |
Try it yourself
docker run -d --name pg -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:17 # a local PostgreSQL
docker exec -it pg psql -U postgres # open psql
CREATE TABLE orders (id bigserial PRIMARY KEY, customer_id int, status text, created_at timestamptz DEFAULT now());
INSERT INTO orders (customer_id, status)
SELECT (random()*10000)::int, 'paid' FROM generate_series(1, 1000000);
ANALYZE orders;
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42; -- Seq Scan
CREATE INDEX ON orders (customer_id);
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42; -- Index or Bitmap scan, much faster
SHOW max_connections;
SELECT pid, state, wait_event_type, query FROM pg_stat_activity; -- who is connected, who waits
SELECT client_addr, state, replay_lag FROM pg_stat_replication; -- on a primary with replicas
Check yourself
Further reading: PostgreSQL: Using EXPLAIN · Indexes · Transactions · Write-Ahead Logging · Explicit locking and deadlocks · Streaming replication · When One Availability Zone Goes Down · StatefulSets and databases