Day 7: The Database as Bottleneck
Goal: Watch a new feature with a query lacking an index bring the system to its knees, add the index without a write lock, let PostgreSQL run out of connections and pool them with PgBouncer · Duration: approx. 90 min · Prerequisite: Day 6
Briefing
- So far the database was harmless: 100,000 links, every query via the
primary key. Today the table grows to 2.2 million rows, and
kurzgets a feature that searches for something other than the code. - Two bottlenecks that show up in almost every system:
| Bottleneck | Symptom | Tool |
|---|---|---|
| missing index | a query reads the whole table | EXPLAIN ANALYZE,
CREATE INDEX CONCURRENTLY |
| too many connections | remaining connection slots are reserved |
pg_stat_activity, PgBouncer |
Drill 1: More Data
# on s1
mkdir -p ~/sd/tag07 && cd ~/sd/tag07
export PGPASSWORD=lab-kurz-123
time psql -h s3 -U kurz -d kurz -c "INSERT INTO links (code, url)
SELECT substr(md5('a' || i), 1, 7), 'https://example.org/artikel/' || i
FROM generate_series(1, 2000000) i ON CONFLICT DO NOTHING"
psql -h s3 -U kurz -d kurz -c "select count(*), pg_size_pretty(pg_total_relation_size('links')) from links"
psql -h s3 -U kurz -d kurz -c "analyze links"Expected:
INSERT 0 1991787
real 0m47.879s
count | pg_size_pretty
---------+----------------
2203541 | 240 MB
(1 row)
ANALYZE
8213 of the two million MD5 prefixes were already taken. Remember that number for Day 9.
Save your progress? Sign up for free
Drill 2: The New Feature
Users often submit the same long URL several times. Instead of
creating a new code each time, kurz should return the
existing one, with status 200 instead of 201:
# on s1
cd ~/kurz && cp main.go /tmp/main.go.alt
perl -0pi -e 's/\tfor versuch := 0; versuch < 3; versuch\+\+ \{\n/\t\/\/ Gibt es die Adresse schon, liefert kurz den vorhandenen Code statt eines neuen\n\tvar vorhanden string\n\terr = db.QueryRow(r.Context(),\n\t\t"SELECT code FROM links WHERE url = \$1 LIMIT 1", in.URL).Scan(&vorhanden)\n\tif err == nil {\n\t\tw.Header().Set("Content-Type", "application\/json")\n\t\tjson.NewEncoder(w).Encode(map[string]string{"code": vorhanden, "url": in.URL})\n\t\treturn\n\t}\n\tfor versuch := 0; versuch < 3; versuch++ {\n/' main.go
diff /tmp/main.go.alt main.go
go vet . && go build -o kurz .Expected:
56a57,65
> // Gibt es die Adresse schon, liefert kurz den vorhandenen Code statt eines neuen
> var vorhanden string
> err = db.QueryRow(r.Context(),
> "SELECT code FROM links WHERE url = $1 LIMIT 1", in.URL).Scan(&vorhanden)
> if err == nil {
> w.Header().Set("Content-Type", "application/json")
> json.NewEncoder(w).Encode(map[string]string{"code": vorhanden, "url": in.URL})
> return
> }
Roll out with the loop from Day 4, then try it:
# on s1
curl -s -i -X POST http://localhost/api/links -d '{"url":"https://example.org/artikel/42"}' \
| grep -E '^HTTP|code'
curl -s -X POST http://localhost/api/links -d '{"url":"https://example.org/ganz-neu-1"}' \
-w ' %{http_code}\n'Expected:
HTTP/1.1 200 OK
{"code":"cceb376","url":"https://example.org/artikel/42"}
{"code":"LZ5pZ8N","url":"https://example.org/ganz-neu-1"}
201
Works. But fast enough?
Save your progress? Sign up for free
Drill 3: Under Load
A separate script just for creating links, half existing, half new URLs:
# on s1
cd ~/sd/tag07
cat > anlegen.js <<'EOF'
import http from "k6/http";
import { check } from "k6";
const ZIEL = __ENV.ZIEL || "http://localhost";
export const options = {
scenarios: { anlegen: { executor: "constant-arrival-rate", rate: Number(__ENV.RATE || 20), timeUnit: "1s",
duration: __ENV.DAUER || "30s", preAllocatedVUs: 20, maxVUs: 300 } },
};
export default function () {
const url = Math.random() < 0.5
? `https://example.org/artikel/${1 + Math.floor(Math.random() * 2000000)}`
: `https://example.org/neu/${__VU}-${__ITER}-${Date.now()}`;
const r = http.post(`${ZIEL}/api/links`, JSON.stringify({ url }), { headers: { "Content-Type": "application/json" } });
check(r, { "200/201": (x) => x.status === 200 || x.status === 201 });
}
EOF
for r in 10 30; do
echo "== ohne Index $r/s"
RATE=$r DAUER=30s k6 run --quiet anlegen.js \
| grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/ */ /g'
doneExpected:
== ohne Index 10/s
http_req_duration..............: avg=14.9s min=728.02ms med=14.71s max=30s p(90)=26.22s p(95)=27.63s
http_req_failed................: 0.47% 1 out of 212
http_reqs......................: 212 4.402865/s
== ohne Index 30/s
http_req_duration..............: avg=26.38s min=1.19s med=30s max=30s p(90)=30s p(95)=30s
http_req_failed................: 70.54% 261 out of 370
http_reqs......................: 370 6.683818/s
Ten create operations per second, and the system manages four. At 30 per second, 70% run into HAProxy’s 30-second timeout. The reason:
# on s1
psql -h s3 -U kurz -d kurz -c "explain analyze select code from links
where url = 'https://example.org/artikel/1234567'" | grep -E 'Scan|Execution' | cut -c1-90Expected:
-> Parallel Seq Scan on links (cost=0.00..33988.78 rows=1 width=8) (actual time=345.528..38
Execution Time: 413.044 ms
413 ms; PostgreSQL reads all 2.2 million rows. There is no index on
url.
Save your progress? Sign up for free
Drill 4: Index Yes, but How?
CREATE INDEX locks the table against writes while the
index is being built. You can measure that: a small script writes a
record every 100 ms and notes how long each one takes. It is not a
helper script for the book but the measuring instrument of this
drill:
# on s1
cat > schreiber.sh <<'EOF'
for i in $(seq 1 120); do
s=$(date +%s.%N)
psql -h s3 -U kurz -d kurz -qtAc "insert into links (code, url) values
(substr(md5(random()::text), 1, 7), 'https://example.org/probe/' || $i) on conflict do nothing"
e=$(date +%s.%N); echo "$(date +%T) $(echo "$e - $s" | bc)"
sleep 0.1
done
EOF
nohup sh schreiber.sh > schreib-normal.log 2>&1 & P=$!
sleep 2
/usr/bin/time -f "%e s" psql -h s3 -U kurz -d kurz -c "CREATE INDEX links_url_idx ON links (url)"
sleep 3; kill $P
sort -k2 -n -r schreib-normal.log | head -2Expected:
CREATE INDEX
6.10 s
22:48:38 5.788682487
22:48:32 .254711562
One insert hung for 5.8 seconds, almost the entire build time. In
production with large tables, that means minutes. So drop it again and
try once more with CONCURRENTLY:
# on s1
psql -h s3 -U kurz -d kurz -qc "drop index links_url_idx"
nohup sh schreiber.sh > schreib-conc.log 2>&1 & P=$!
sleep 2
/usr/bin/time -f "%e s" psql -h s3 -U kurz -d kurz -c "CREATE INDEX CONCURRENTLY links_url_idx ON links (url)"
sleep 3; kill $P
sort -k2 -n -r schreib-conc.log | head -2
psql -h s3 -U kurz -d kurz -c "\di+ links_url_idx" | sed -n 4p | cut -c1-90Expected:
CREATE INDEX
7.19 s
22:48:48 .245045057
22:48:50 .244481019
public | links_url_idx | index | kurz | links | permanent | btree | 120 MB |
One second longer, but no insert above 0.25 s, and that is the normal
duration of a psql call including connection setup. The
index is 120 MB, half the size of the table: indexes cost space and make
every insert a bit more expensive.
Save your progress? Sign up for free
Drill 5: With Index
# on s1
psql -h s3 -U kurz -d kurz -c "explain analyze select code from links
where url = 'https://example.org/artikel/1234567'" | grep -E 'Scan|Execution' | cut -c1-90
for r in 10 30 300; do
echo "== mit Index $r/s"
RATE=$r DAUER=30s k6 run --quiet anlegen.js \
| grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' | sed 's/ */ /g'
doneExpected:
Index Scan using links_url_idx on links (cost=0.56..8.57 rows=1 width=8) (actual time=0.221..
Execution Time: 0.450 ms
== mit Index 10/s
http_req_duration..............: avg=5.12ms min=2.54ms med=4.72ms max=15.31ms p(90)=7.49ms p(95)=8.37ms
http_req_failed................: 0.00% 0 out of 301
http_reqs......................: 301 10.030944/s
== mit Index 30/s
http_req_duration..............: avg=5ms min=2.23ms med=4.92ms max=30.86ms p(90)=6.98ms p(95)=7.83ms
http_req_failed................: 0.00% 0 out of 901
http_reqs......................: 901 30.02858/s
== mit Index 300/s
http_req_duration..............: avg=3.81ms min=1.23ms med=3.58ms max=22.14ms p(90)=5.84ms p(95)=7ms
http_req_failed................: 0.00% 0 out of 9000
http_reqs......................: 9000 299.987586/s
From 413 ms down to 0.45 ms, a factor of 900. Instead of four create operations per second, 300 without errors, p95 7 ms.
Save your progress? Sign up for free
Drill 6: Running Out of Connections
PostgreSQL starts a separate process for each connection and allows 100 out of the box, three of them reserved for superusers. What happens if each instance wants to open 60 connections in advance?
# on s1
psql -h s3 -U kurz -d kurz -tAc "show max_connections"
for s in s1 s2; do
ssh $s "printf '[Service]\nEnvironment=KURZ_DB=postgres://kurz:lab-kurz-123@s3:5432/kurz?pool_min_conns=60&pool_max_conns=60\n' \
| sudo tee /etc/systemd/system/kurz.service.d/pool.conf >/dev/null \
&& sudo systemctl daemon-reload && sudo systemctl restart kurz"
done
sleep 15
psql -h s3 -U kurz -d kurz -tAc "select application_name, client_addr, count(*)
from pg_stat_activity where usename = 'kurz' group by 1, 2"
ssh s3 "sudo grep -c 'remaining connection slots' /var/log/postgresql/postgresql-18-main.log"
ssh s3 "sudo grep 'remaining connection slots' /var/log/postgresql/postgresql-18-main.log | tail -1 | cut -c1-140"Expected:
100
|172.16.0.126|60
|172.16.0.228|24
psql|172.16.0.126|1
27
2026-11-22 23:31:20.781 UTC [19748] kurz@kurz FATAL: remaining connection slots are reserved for ro
s1 was faster and took its 60; s2 got only 24. PostgreSQL rejected
the remaining attempts, 27 times. A third service, a migration tool or
an admin with psql would now hardly find room. More
connections don’t help PostgreSQL either: on two cores, never more than
a handful of queries truly run at the same time; the rest just wait in
memory.
Save your progress? Sign up for free
Drill 7: PgBouncer Pools
PgBouncer accepts any number of connections from apps and distributes
the work across a few real connections to PostgreSQL. In
transaction mode, a database connection belongs to an app
only for the duration of a transaction.
# on s3
sudo apt-get install -y pgbouncer >/dev/null
pgbouncer --version | head -1
sudo -u postgres psql -tAc "select concat('\"kurz\" \"', rolpassword, '\"') from pg_authid
where rolname = 'kurz'" | sudo tee /etc/pgbouncer/userlist.txt >/dev/null
sudo chown postgres:postgres /etc/pgbouncer/userlist.txt && sudo chmod 640 /etc/pgbouncer/userlist.txt
sudo tee /etc/pgbouncer/pgbouncer.ini >/dev/null <<'EOF'
[databases]
kurz = host=127.0.0.1 port=5432 dbname=kurz
[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
default_pool_size = 20
max_client_conn = 1000
max_prepared_statements = 200
admin_users = kurz
logfile = /var/log/postgresql/pgbouncer.log
pidfile = /var/run/postgresql/pgbouncer.pid
EOF
sudo systemctl restart pgbouncer
systemctl is-active pgbouncerExpected:
PgBouncer 1.26.1
active
The userlist.txt file contains the SCRAM hash from
PostgreSQL, not the password. max_prepared_statements
matters for pgx: the driver uses prepared statements, and only newer
PgBouncer versions can pass them through in transaction mode. Now both
instances on port 6432, still with 60 connections in advance:
# on s1
for s in s1 s2; do
ssh $s "printf '[Service]\nEnvironment=KURZ_DB=postgres://kurz:lab-kurz-123@s3:6432/kurz?pool_min_conns=60&pool_max_conns=60\n' \
| sudo tee /etc/systemd/system/kurz.service.d/pool.conf >/dev/null \
&& sudo systemctl daemon-reload && sudo systemctl restart kurz"
done
sleep 10
cd ~/sd/tag05
(ZIEL=http://localhost RATE=1500 DAUER=20s k6 run --quiet schief.js > /tmp/k6b.txt 2>&1 &)
sleep 8
psql -h s3 -U kurz -d kurz -tAc "select coalesce(nullif(application_name, ''), '(pgbouncer)'), state,
count(*) from pg_stat_activity where usename = 'kurz' group by 1, 2"
psql -h s3 -p 6432 -U kurz -d pgbouncer -tAc "show pools" | head -1 | cut -d'|' -f1-3
sleep 15; grep -E 'http_reqs\.|http_req_failed\.' /tmp/k6b.txt | sed 's/ */ /g'Expected:
(pgbouncer)|idle|9
psql|active|1
kurz|kurz|120
http_req_failed................: 0.00% 0 out of 29976
http_reqs......................: 29976 1498.594393/s
120 connections from the apps to PgBouncer, but only 9 from PgBouncer to PostgreSQL, while 1500 requests per second are running. Nothing more is needed, because each query holds a connection for only a fraction of a millisecond.
Finally, a sensible pool size instead of 60 connections in advance, and unique URLs for new links in the load script; otherwise the feature from Drill 2 returns 200 instead of 201 on repeats:
# on s1
for s in s1 s2; do
ssh $s "printf '[Service]\nEnvironment=KURZ_DB=postgres://kurz:lab-kurz-123@s3:6432/kurz?pool_max_conns=16\n' \
| sudo tee /etc/systemd/system/kurz.service.d/pool.conf >/dev/null \
&& sudo systemctl daemon-reload && sudo systemctl restart kurz"
done
sed -i 's#https://example.org/neu/${__VU}-${__ITER}#https://example.org/neu/${__VU}-${__ITER}-${Date.now()}#' \
~/sd/tag05/schief.js
ZIEL=http://localhost RATE=1500 DAUER=20s k6 run --quiet ~/sd/tag05/schief.js \
| grep -E 'checks_failed|http_req_duration\.|http_req_failed\.' | sed 's/ */ /g'Expected:
checks_failed......: 0.00% 0 out of 29972
http_req_duration..............: avg=5.09ms min=842.88µs med=3.36ms max=56.62ms p(90)=10.3ms p(95)=15.03ms
http_req_failed................: 0.00% 0 out of 29972
That is the starting point for the coming days: both instances via PgBouncer, p95 15 ms at 1500 requests per second.
Save your progress? Sign up for free
Exercise: Speed drills
- Show the five largest indexes in the database. Target time: 1 min
- Show how many connections PostgreSQL currently has, by state. Target time: 1 min
- Show in PgBouncer how many clients are waiting. Target time: 30 s
Solution
# on s1
psql -h s3 -U kurz -d kurz -c "select indexrelname, pg_size_pretty(pg_relation_size(indexrelid))
from pg_stat_user_indexes order by pg_relation_size(indexrelid) desc limit 5"
psql -h s3 -U kurz -d kurz -c "select state, count(*) from pg_stat_activity group by 1"
psql -h s3 -p 6432 -U kurz -d pgbouncer -c "show pools" | cut -d'|' -f1-4The cl_waiting column shows waiting clients. If it stays
above 0 permanently, default_pool_size is too small or the
database too slow.
Save your progress? Sign up for free
Checkpoint
# on s1
psql -h s3 -U kurz -d kurz -tAc "select indexname from pg_indexes where tablename = 'links' order by 1"Expected: links_pkey and
links_url_idx
# on s1
ssh s2 systemctl show kurz -p Environment | grep -o 's3:6432[^ ]*'Expected:
s3:6432/kurz?pool_max_conns=16
Challenge
CREATE INDEX CONCURRENTLY can fail, for example if a
duplicate value is supposed to go into a unique index during the build.
That leaves behind an index that is not used. How do you recognize such
a broken index, and how do you get rid of it?
Hint: pg_index has an
indisvalid column.
Solution
# on s1
psql -h s3 -U kurz -d kurz -c "select indexrelid::regclass, indisvalid from pg_index
where indrelid = 'links'::regclass"Expected:
indexrelid | indisvalid
---------------+------------
links_pkey | t
links_url_idx | t
(2 rows)
A failed build shows up there with f.
\d links shows it as INVALID. It costs work on
every insert but helps no query. Get rid of it with
DROP INDEX CONCURRENTLY <name> and rebuild.
Save your progress? Sign up for free
Clean-up
# on s1
rm -f ~/sd/tag07/schreib-*.logThe 2.2 million links, the index, PgBouncer and the pool size stay.
Interview note
- How do you find a slow query?
EXPLAIN ANALYZE; in production,pg_stat_statementssorted by total time. ASeq Scanon a large table for a query for a single value is almost always a missing index. - Why
CREATE INDEX CONCURRENTLY? A normal index build locks writes for the entire build time. On the other hand, it takes somewhat longer and can fail, so checkindisvalidafterwards. - What is a connection pooler for? PostgreSQL
connections are expensive (one process per connection). PgBouncer allows
many app connections on a few real ones. In exchange, in transaction
mode, session state such as
SETor advisory locks is lost across transactions.
Enterprise note
- In production, indexes are built with migration tools that enforce
CONCURRENTLYand check the result. An index on a table with billions of rows can take hours. - Many teams run PgBouncer on each app server instead of centrally: no extra network hop, and the failure of one PgBouncer affects only one instance.