Skip to main content
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—
Primary DB serverOrder appINSERT an orderConnection poolReused connectionsQuery plannerPicks a planorders tableRows · indexesWALWrite-ahead logRead replicaRead-only copyReport appReads the replicaSave order
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​

SymptomLikely causeWhat to check
sorry, too many clients alreadyTotal connections from all app replicas exceed max_connectionsSELECT 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 highSeq Scan on a large table, a missing indexEXPLAIN ANALYZE <query>, pg_stat_statements for the slowest queries
Requests hang, then time outA long transaction holds a row lockpg_stat_activity where wait_event_type = 'Lock', and pg_blocking_pids(pid)
deadlock detectedTwo transactions lock the same rows in a different orderServer log for the two statements; lock rows in one order and retry in the app
Data saved but not shownReading from a lagging replicareplay_lag in pg_stat_replication; read your own writes from the primary
COMMIT is slow for every writeSlow disk flush for the WALDisk 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

  1. After HPA scales the order app from 3 to 5 replicas, new DB connections fail with "sorry, too many clients already". What is the most likely cause?
  2. A customer saves an order, but the order history page, which reads from a replica, does not show it. What is going on?
  3. Why does COMMIT return only after the WAL record is flushed to disk?

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