You are on call and the database is on fire. What do you actually do?
These are the playbooks I would want next to me during an outage. Start with the first five minutes, then open the symptom you see. Each playbook goes from confirming the problem, to finding the cause, to stopping the bleeding with the least risky move first, with the commands for your engine, what to look for and where to go next. It also says when to escalate, when to get the application team on a call and what to suggest to them, what to post in the channel, and what the postmortem should change.
Before any playbook below, whatever the symptom. This is what separates a 20 minute incident from a 3 hour one.
Look at the app's error rate and latency next to the database's CPU, connections and query time. If only one app is hurting and the database graphs are flat, it is probably that app, its network or its pool. Say so early: it saves everyone an hour. On RDS or Aurora, also look at the RDS events: a failover or maintenance shows there first. On Kubernetes, look at pod restarts and recent rollouts.
Primary or replicas, one cluster or all of them, every app or one. Find the minute the graph bent. That timestamp is the most useful fact of the incident.
Deploys, migrations, config changes, feature flags, batch jobs, a traffic spike, a failover, cloud maintenance. Most outages follow a change, and undoing the change is usually the fastest fix.
One channel. One person drives the database, one talks to everyone else. Post: what is broken, what you are doing, when the next update comes. Then keep that promise.
Killing sessions and restarting destroys the clues. Thirty seconds of snapshots now is the difference between a root cause and a guess in the postmortem.
F=/tmp/incident-$(date +%Y%m%d-%H%M) psql -XAt -F'|' -c "SELECT now(), pid, usename, application_name, client_addr, state, wait_event_type, wait_event, xact_start, query_start, left(query, 300) FROM pg_stat_activity" > $F-activity.txt psql -XAt -F'|' -c "SELECT pid, pg_blocking_pids(pid), wait_event, left(query, 200) FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0" > $F-blocking.txt psql -XAt -c "SELECT * FROM pg_stat_replication" > $F-replication.txt
F=/tmp/incident-$(date +%Y%m%d-%H%M) mysql -e "SHOW FULL PROCESSLIST" > $F-processlist.txt mysql -e "SHOW ENGINE INNODB STATUS\G" > $F-innodb.txt mysql -e "SELECT * FROM sys.innodb_lock_waits\G" > $F-lockwaits.txt mysql -e "SHOW REPLICA STATUS\G" > $F-replica.txt
F=/tmp/incident-$(date +%Y%m%d-%H%M) mongosh --quiet --eval 'printjson(db.currentOp(true))' > $F-currentop.json mongosh --quiet --eval 'printjson(db.serverStatus())' > $F-serverstatus.json mongosh --quiet --eval 'printjson(rs.status())' > $F-rs.json
Post each action with its time in the channel. Two changes at once means you will not know which one fixed it, or which one made it worse.
Start here. Get in on a reserved slot, then find which app owns the connections and what state they are in. The state tells you which outage this really is.
You need a session of your own before you can fix anything. Both engines keep room for an admin.
SELECT count(*) AS in_use,
current_setting('max_connections') AS max,
current_setting('superuser_reserved_connections') AS reserved_for_admins
FROM pg_stat_activity WHERE backend_type = 'client backend';SHOW VARIABLES LIKE 'max_connections';
SHOW GLOBAL STATUS WHERE Variable_name IN
('Threads_connected', 'Threads_running', 'Max_used_connections',
'Connection_errors_max_connections');db.serverStatus().connections // current, available, totalCreated
Look for: In use within a few of the limit confirms it. PostgreSQL keeps superuser_reserved_connections for superusers: connect as postgres on the host. MySQL allows one extra connection for an account with CONNECTION_ADMIN.
This one query decides the rest of the incident.
SELECT usename, application_name, client_addr, state, count(*) FROM pg_stat_activity WHERE backend_type = 'client backend' GROUP BY 1, 2, 3, 4 ORDER BY 5 DESC LIMIT 20;
SELECT user, SUBSTRING_INDEX(host, ':', 1) AS client, command, count(*) FROM information_schema.processlist GROUP BY 1, 2, 3 ORDER BY 4 DESC LIMIT 20;
db.getSiblingDB('admin').aggregate([
{ $currentOp: { allUsers: true, idleConnections: true } },
{ $group: { _id: { app: '$appName', client: '$client' }, n: { $sum: 1 } } },
{ $sort: { n: -1 } }, { $limit: 20 }])Look for: Read the state column for the biggest group.
A deploy that doubled the pods, a new service, a failover that made every client reconnect at once.
# kubectl: did the replica count of an app change? kubectl get hpa -A kubectl rollout history deployment/<app> -n <namespace>
Look for: Pods times pool size, before and after the change. If the new number is over the limit, you have the cause.
They hold connections and locks and do nothing. Ending them is safe: their open transaction rolls back and the app gets an error on a connection it was not using.
SELECT pid, usename, application_name,
now() - xact_start AS transaction_age,
now() - state_change AS idle_for,
left(query, 80) AS last_query
FROM pg_stat_activity WHERE state = 'idle in transaction'
ORDER BY xact_start LIMIT 20;
-- then end the ones idle for more than 5 minutes
SELECT pid, pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction'
AND now() - state_change > interval '5 minutes';-- a transaction with no running query, and a Sleep thread, is idle in transaction
SELECT t.trx_mysql_thread_id AS thread, t.trx_started,
TIMESTAMPDIFF(SECOND, t.trx_started, NOW()) AS age_s, p.user, p.host
FROM information_schema.innodb_trx t
JOIN information_schema.processlist p ON p.id = t.trx_mysql_thread_id
WHERE p.command = 'Sleep' ORDER BY t.trx_started LIMIT 20;
-- then: KILL <thread>; for each one you have readdb.getSiblingDB('admin').aggregate([
{ $currentOp: { allUsers: true, idleSessions: true } },
{ $match: { transaction: { $exists: true } } },
{ $project: { appName: 1, client: 1, 'transaction.timeOpenMicros': 1 } }])
// MongoDB aborts transactions older than transactionLifetimeLimitSeconds (60 s) by itselfLook for: Connections fall right away. If they come back within minutes, the app has a code path that never commits: get the app team on the call.
Undo: Nothing to undo. The app reconnects.
The database is fine; it is being asked for more connections than it has. The app team owns this lever, so this is a call, not a command.
# with the app team, the fastest of: kubectl rollout undo deployment/<app> -n <namespace> # the deploy that caused it kubectl scale deployment/<app> --replicas=<before> -n <namespace> # or lower the pool size in the app's config and restart it
Look for: Connections fall below 80 percent within a few minutes of the change.
Undo: Roll forward again once the pool math fits.
A script or report should never take the connections your customers need. Stop new ones, then end the existing ones.
ALTER ROLE report_user CONNECTION LIMIT 0; -- no new sessions for this role SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'report_user';
ALTER USER 'report_user'@'%' ACCOUNT LOCK; -- then KILL each of its connections (see step 2 for the list)
// no server-side per-user connection cap: stop the client, or
db.getSiblingDB('admin').revokeRolesFromUser('report_user', [{ role: 'read', db: 'app' }])Look for: Its connections drop to zero and stay there.
Undo: PostgreSQL: ALTER ROLE report_user CONNECTION LIMIT -1; MySQL: ALTER USER 'report_user'@'%' ACCOUNT UNLOCK;
Only if the load is real and the server has memory for it. On PostgreSQL this needs a restart, which drops every connection: that is a bigger outage than the one you have.
-- PgBouncer in transaction mode in front of PostgreSQL is the usual answer. -- max_connections only changes with a restart: ALTER SYSTEM SET max_connections = 400; -- then a planned restart
-- takes effect at once, and survives a restart SET PERSIST max_connections = 800; -- ProxySQL multiplexes many app connections onto fewer backends
// raise net.maxIncomingConnections in mongod.conf (restart), or // connect through mongos, which pools connections to the shards
Look for: Do the memory math first. On PostgreSQL, a pooler in front (PgBouncer) is the real fix, and it can be added without a restart.
Undo: Set the old value back (PostgreSQL: another restart).
Connections under 80 percent and the app's pool wait time back to normal, for 15 minutes.
SELECT count(*) AS in_use,
current_setting('max_connections') AS max,
current_setting('superuser_reserved_connections') AS reserved_for_admins
FROM pg_stat_activity WHERE backend_type = 'client backend';SHOW VARIABLES LIKE 'max_connections';
SHOW GLOBAL STATUS WHERE Variable_name IN
('Threads_connected', 'Threads_running', 'Max_used_connections',
'Connection_errors_max_connections');db.serverStatus().connections // current, available, totalCreated
Look for: Also check the app's error rate, not just the database: that is what users feel.
CALL mysql.rds_kill(<thread id>); -- end the connection CALL mysql.rds_kill_query(<thread id>); -- cancel the statement
kubectl get hpa -A kubectl get pods -l app=<app> -n <ns> --no-headers | wc -l
kubectl exec -it <db-pod> -n <ns> -- psql -U postgres kubectl cnpg psql <cluster> -n <ns> # CloudNativePG plugin
Database <name>: connections are at the limit, so some requests fail. Cause: <app> is holding <n> connections after <change>. We are <action>. Next update <time>.
Done when: Connections stay under 80 percent for 15 minutes, the app shows no connection errors, and you know which app and which change caused it.
The pooling decision: Connection management and pooling.
Start here. Find the one query fingerprint eating the CPU right now, and what changed to make it do that. Usually it is one fast query that suddenly runs much more often, or one that lost its index.
A backup, an agent or another service on the same host looks the same from the app.
top -b -n 1 -o %CPU | head -15 # which process is using the CPU uptime # load average against the number of cores
Look for: postgres, mysqld or mongod on top: carry on.
Active sessions compared with cores tells you how bad it is. Twice the core count means everything is queueing.
SELECT left(query, 100) AS query, count(*) AS running,
max(now() - query_start) AS longest
FROM pg_stat_activity
WHERE state = 'active' AND pid <> pg_backend_pid()
GROUP BY 1 ORDER BY 2 DESC LIMIT 15;SELECT LEFT(info, 100) AS query, count(*) AS running, max(time) AS longest_s FROM information_schema.processlist WHERE command = 'Query' AND id <> CONNECTION_ID() GROUP BY 1 ORDER BY 2 DESC LIMIT 15;
db.currentOp({ active: true }).inprog
.filter(o => o.op !== 'none')
.forEach(o => print(o.opid, o.secs_running + 's', o.ns, o.planSummary))Look for: One fingerprint with dozens of copies is the usual picture.
Totals since the last reset hide what changed today. The difference over one minute shows what is burning CPU now.
-- what used the CPU in the last minute, not since the last reset
DROP TABLE IF EXISTS snap;
CREATE TEMP TABLE snap AS
SELECT userid, dbid, queryid, calls, total_exec_time FROM pg_stat_statements;
SELECT pg_sleep(60);
SELECT s.calls - p.calls AS calls_last_min,
round((s.total_exec_time - p.total_exec_time)::numeric) AS ms_last_min,
left(s.query, 80) AS query
FROM pg_stat_statements s JOIN snap p USING (userid, dbid, queryid)
ORDER BY 2 DESC LIMIT 10;-- what used the time in the last minute
DROP TEMPORARY TABLE IF EXISTS snap;
CREATE TEMPORARY TABLE snap AS
SELECT schema_name, digest, count_star, sum_timer_wait
FROM performance_schema.events_statements_summary_by_digest;
DO SLEEP(60);
SELECT d.count_star - s.count_star AS calls_last_min,
ROUND((d.sum_timer_wait - s.sum_timer_wait) / 1e9) AS ms_last_min,
LEFT(d.digest_text, 80) AS query
FROM performance_schema.events_statements_summary_by_digest d
JOIN snap s ON s.digest = d.digest AND s.schema_name <=> d.schema_name
ORDER BY 2 DESC LIMIT 10;// if profiling is off, turn it on first (changes a setting):
// db.setProfilingLevel(1, { slowms: 50 })
db.system.profile.find({}, { ns: 1, millis: 1, planSummary: 1, docsExamined: 1, nreturned: 1 })
.sort({ millis: -1 }).limit(10)Look for: The top line is usually more than half of all the time. Note its calls per minute: compare with last week if your monitoring keeps it.
A scan where there used to be an index lookup turns a cheap query into an expensive one.
-- ANALYZE runs the query. For an UPDATE or DELETE, wrap it: BEGIN; EXPLAIN (ANALYZE, BUFFERS) <the query>; ROLLBACK;
EXPLAIN ANALYZE <the query>; -- runs it (MySQL 8.0.18 and later) EXPLAIN FORMAT=TREE <the query>; -- the plan only
db.orders.find({ customer_id: 42 }).explain('executionStats')
// compare totalDocsExamined with nReturnedLook for: Seq Scan, type ALL or COLLSCAN on a big table, or rows examined far above rows returned.
The fastest and safest fix when the timing lines up. You can fix the query properly tomorrow.
kubectl rollout undo deployment/<app> -n <namespace> # or turn off the feature flag that shipped the new query
Look for: CPU falls within a couple of minutes of the rollback finishing.
Undo: Roll forward once the query is fixed.
Cancelling buys minutes. If the app retries, they come straight back, so stop the source too: the job, the endpoint, the flag.
SELECT pg_cancel_backend(pid) -- cancels the query, keeps the session FROM pg_stat_activity WHERE state = 'active' AND query LIKE '%<part of the query>%' AND now() - query_start > interval '1 minute';
KILL QUERY <thread id>; -- cancels the statement, keeps the connection
db.killOp(<opid>)
Look for: CPU drops. If it climbs back within a minute, the source is still running.
Undo: Nothing to undo. The query can be run again later.
The real fix, if the table is not huge. On a busy host, the build itself adds load: check the table size and expect it to take a while.
CREATE INDEX CONCURRENTLY orders_customer_idx ON orders (customer_id); -- if it fails it leaves an INVALID index: drop it and run it again
ALTER TABLE orders ADD INDEX orders_customer_idx (customer_id), ALGORITHM = INPLACE, LOCK = NONE;
db.orders.createIndex({ customer_id: 1 }) // holds an exclusive lock only at the start and the endLook for: The plan uses it, and the query's time per call falls.
Undo: PostgreSQL: DROP INDEX CONCURRENTLY orders_customer_idx; MySQL: ALTER TABLE orders DROP INDEX orders_customer_idx; MongoDB: db.orders.dropIndex("orders_customer_idx")
Costs money and, on most managed services, a failover. Worth it only if the load is real and nothing above helps.
# RDS: modify the instance class (Multi-AZ: a failover of a minute or two) aws rds modify-db-instance --db-instance-identifier <id> --db-instance-class <bigger> --apply-immediately
Look for: Plan it with the app owner: they will see errors during the failover.
CPU near its normal level for 15 minutes and the query's time per call back to normal.
-- what used the CPU in the last minute, not since the last reset
DROP TABLE IF EXISTS snap;
CREATE TEMP TABLE snap AS
SELECT userid, dbid, queryid, calls, total_exec_time FROM pg_stat_statements;
SELECT pg_sleep(60);
SELECT s.calls - p.calls AS calls_last_min,
round((s.total_exec_time - p.total_exec_time)::numeric) AS ms_last_min,
left(s.query, 80) AS query
FROM pg_stat_statements s JOIN snap p USING (userid, dbid, queryid)
ORDER BY 2 DESC LIMIT 10;-- what used the time in the last minute
DROP TEMPORARY TABLE IF EXISTS snap;
CREATE TEMPORARY TABLE snap AS
SELECT schema_name, digest, count_star, sum_timer_wait
FROM performance_schema.events_statements_summary_by_digest;
DO SLEEP(60);
SELECT d.count_star - s.count_star AS calls_last_min,
ROUND((d.sum_timer_wait - s.sum_timer_wait) / 1e9) AS ms_last_min,
LEFT(d.digest_text, 80) AS query
FROM performance_schema.events_statements_summary_by_digest d
JOIN snap s ON s.digest = d.digest AND s.schema_name <=> d.schema_name
ORDER BY 2 DESC LIMIT 10;// if profiling is off, turn it on first (changes a setting):
// db.setProfilingLevel(1, { slowms: 50 })
db.system.profile.find({}, { ns: 1, millis: 1, planSummary: 1, docsExamined: 1, nreturned: 1 })
.sort({ millis: -1 }).limit(10)Look for: Keep watching through the next traffic peak.
aws cloudwatch get-metric-statistics --namespace AWS/RDS --metric-name CPUCreditBalance \ --dimensions Name=DBInstanceIdentifier,Value=<id> --start-time <iso> --end-time <iso> --period 300 --statistics Minimum
kubectl top pod <db-pod> -n <ns>
kubectl get pod <db-pod> -n <ns> -o jsonpath='{.spec.containers[*].resources}'Database <name>: CPU is saturated, so most requests are slow. Cause: <query> from <app>, <why>. We are <action>. Next update <time>.
Done when: CPU is back to normal through a traffic peak, and you know which query, which change and which fix.
How plans go wrong: Queries that look fine and are not, and paste one into the query coach.
Start here. Work out the time until the disk is full. Under an hour, the first move is to grow the volume, then look for the cause. Never delete database files by hand.
Time to full decides whether you investigate first or grow the volume first.
SHOW data_directory; -- in the shell: du -sh $PGDATA/base $PGDATA/pg_wal $PGDATA/pg_replslot $PGDATA/log
SELECT @@datadir, @@log_bin_basename, @@innodb_temp_data_file_path;
const o = db.adminCommand({ getCmdLineOpts: 1 }).parsed;
print((o.storage && o.storage.dbPath) || '/data/db (the default)')df -h # run it twice, 10 minutes apart du -sh /path/to/data/dir/* | sort -h | tail -15
Look for: Run df twice, ten minutes apart, and divide.
Each has a different fix. WAL, binlogs and server logs grow fastest.
SELECT slot_name, slot_type, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS wal_kept
FROM pg_replication_slots ORDER BY restart_lsn;
-- WAL archiving failing also keeps WAL
SELECT archived_count, failed_count, last_failed_wal, last_failed_time
FROM pg_stat_archiver;SHOW BINARY LOGS; SELECT @@binlog_expire_logs_seconds / 86400 AS days_kept;
rs.printReplicationInfo() // the oplog has a fixed size, so it is rarely the cause
db.adminCommand({ getCmdLineOpts: 1 }).parsed.systemLog // where the mongod log lives; unrotated logs growLook for: Read the result against the directory sizes from step 1.
Statement logging left on after a debug session can write gigabytes an hour.
SELECT name, setting FROM pg_settings
WHERE name IN ('log_min_duration_statement', 'log_statement', 'log_connections', 'log_disconnections');SHOW VARIABLES WHERE Variable_name IN ('general_log', 'slow_query_log', 'long_query_time', 'log_output');db.getProfilingStatus()
db.adminCommand({ getParameter: 1, logLevel: 1 })Look for: log_min_duration_statement = 0, log_statement = all, or the MySQL general log ON: turn it off and delete old log files. Safe.
On cloud volumes this is online and takes minutes. It buys the time to find the cause calmly.
# grow the volume: on AWS, modify the EBS volume, then sudo growpart /dev/nvme1n1 1 # if it has a partition sudo xfs_growfs /data # or: sudo resize2fs /dev/nvme1n1p1
Look for: Free space jumps. On RDS: modify the allocated storage; you cannot change it again for six hours, so add enough.
Undo: Volumes cannot shrink. That is fine.
A CDC tool or replica that died long ago keeps every WAL file since. Find its owner first: dropping the slot means that consumer needs a full resync.
-- only after you confirm nothing will use this slot again:
SELECT pg_drop_replication_slot('old_slot'); -- its reader needs a full resync
-- fix archive_command if step 2 showed failures; WAL is then removed by itselfLook for: pg_wal shrinks at the next checkpoint.
Undo: None. The consumer has to be rebuilt from a fresh snapshot.
Check every replica first: purging a binlog a replica still needs breaks that replica.
-- check every replica has read past this point first (SHOW REPLICA STATUS) PURGE BINARY LOGS BEFORE NOW() - INTERVAL 3 DAY; SET PERSIST binlog_expire_logs_seconds = 604800; -- 7 days
Look for: Free space rises at once.
Undo: None. Keep a few days of binlogs for point-in-time recovery.
A sort or hash spilling tens of GB is usually a bad query, not a real need.
SELECT datname, temp_files, pg_size_pretty(temp_bytes) AS temp FROM pg_stat_database ORDER BY temp_bytes DESC; SELECT pid, now() - query_start AS running, left(query, 80) FROM pg_stat_activity WHERE state = 'active' ORDER BY query_start LIMIT 5;
-- the session temporary tablespace and ibtmp1 (ibtmp1 only shrinks at restart) SELECT * FROM information_schema.innodb_session_temp_tablespaces;
// aggregations with allowDiskUse spill under the dbPath, in _tmp
db.currentOp({ active: true, secs_running: { $gte: 60 } })Look for: Cancel it (see CPU at 100%, step 6), then look at its plan.
Flat or rising for 30 minutes, with the cause gone, not just pushed back.
df -h # run it twice, 10 minutes apart du -sh /path/to/data/dir/* | sort -h | tail -15
Look for: Estimate when it will fill again at normal growth, and put that date in the ticket.
CALL mysql.rds_show_configuration;
CALL mysql.rds_set_configuration('binlog retention hours', 24);kubectl get pvc -n <ns>
kubectl get storageclass <class> -o jsonpath='{.allowVolumeExpansion}'
kubectl patch pvc <pvc> -n <ns> -p '{"spec":{"resources":{"requests":{"storage":"200Gi"}}}}'Database <name>: disk is <n>% full and growing <rate>. Cause: <what>. We have <grown the volume / are freeing space>. Risk of writes stopping at <time>. Next update <time>.
Done when: Free space is stable, the cause is fixed, and the projected full date is months away.
The on-call drill for this one: On call tonight, incident 1. And why the bill is huge.
Start here. Decide two things fast: are users affected, because reads go to that replica, and is your failover target safe. Then find whether the replica is not receiving changes or not applying them.
Seconds tell you how stale reads are. Bytes tell you what a failover now would lose or have to replay.
-- on the primary
SELECT application_name, client_addr, state,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS behind,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;SHOW REPLICA STATUS\G -- Seconds_Behind_Source, Replica_IO_Running, Replica_SQL_Running, -- Last_IO_Error, Last_SQL_Error
rs.printSecondaryReplicationInfo()
Look for: One replica behind: a problem on that replica. All of them: something on the primary, usually one huge write.
The fix is in a different place for each.
-- on the replica
SELECT pg_last_wal_receive_lsn() AS received,
pg_last_wal_replay_lsn() AS applied,
pg_is_wal_replay_paused() AS paused,
now() - pg_last_xact_replay_timestamp() AS behind;
SELECT status, sender_host, last_msg_receipt_time FROM pg_stat_wal_receiver;SHOW REPLICA STATUS\G -- Retrieved_Gtid_Set (received) against Executed_Gtid_Set (applied) SELECT * FROM performance_schema.replication_applier_status_by_worker\G
rs.status().members.map(m => [m.name, m.stateStr, m.optimeDate, m.syncSourceHost])
Look for: Compare received with applied.
One giant transaction on the primary, or a long query on the replica, explains most of it.
-- on the replica: queries that delay or conflict with replay SELECT pid, now() - query_start AS running, left(query, 80) FROM pg_stat_activity WHERE state = 'active' ORDER BY query_start LIMIT 10; SELECT * FROM pg_stat_database_conflicts WHERE datname = current_database(); SHOW max_standby_streaming_delay;
SHOW VARIABLES LIKE 'replica_parallel%'; SHOW PROCESSLIST; -- the applier threads and their state
db.serverStatus().metrics.repl.buffer // and CPU and disk on the secondary: an overloaded secondary falls behind
Look for: A long report on a PostgreSQL replica can hold replay back. A big DELETE on the primary replays as one unit.
Do not skip transactions to get it going. The replica would then be wrong in a way nobody can see.
-- in the replica's log: the error, often a missing WAL file -- (the primary removed it before the replica read it)
SHOW REPLICA STATUS\G -- Last_SQL_Error, Last_IO_Error SELECT * FROM performance_schema.replication_applier_status_by_worker\G
rs.status() // look for a member in RECOVERING or with an error message
Look for: A WAL or binlog the primary no longer has means the replica cannot catch up: rebuild it.
This fixes what users see in a minute, without touching replication.
KILL QUERY <thread id>; -- the long query on the replica -- remove it from the ProxySQL reader hostgroup
// readPreference for that app: primaryPreferred, until the secondary catches up
Look for: Stale-read complaints stop. Make sure the others can carry the reads.
Undo: Put it back once lag is under your threshold.
One DELETE of 50 million rows becomes hours of lag. Stopping it, and running it in chunks later, ends the lag growth at once.
# with the job's owner: stop the job. Then, for later: # delete in chunks of a few thousand rows, with a short pause between chunks
Look for: Lag stops growing, then falls.
Undo: Restart the job in chunks.
Sometimes a fresh copy is faster than waiting. Out of the read pool while it builds.
pg_basebackup -h <primary> -D /new/data/dir -X stream -P -R
CLONE INSTANCE FROM 'clone_user'@'primary':3306 IDENTIFIED BY '...'; -- the clone plugin
// stop the secondary, empty its dbPath, start it: it runs an initial sync
Look for: Time it. That number belongs in your recovery plan.
Lag under your threshold for 15 minutes, then back into the read pool.
-- on the primary
SELECT application_name, client_addr, state,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS behind,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;SHOW REPLICA STATUS\G -- Seconds_Behind_Source, Replica_IO_Running, Replica_SQL_Running, -- Last_IO_Error, Last_SQL_Error
rs.printSecondaryReplicationInfo()
Look for: Also confirm your failover target is current again.
CALL mysql.rds_skip_repl_error; -- the same risk as sql_replica_skip_counter
kubectl cnpg status <cluster> -n <ns> # CloudNativePG kubectl exec <pod> -n <ns> -- patronictl list # Zalando and Crunchy run Patroni
kubectl get pod -o wide -n <ns>
Database <name>: replica <r> is <n> behind, so <reads may be stale / failover protection is reduced>. Cause: <what>. We are <action>. Next update <time>.
Done when: Every replica is under the lag threshold, back in the read pool, and the failover target is current.
The drill: incident 3. Side by side: a replica falls behind.
Start here. Find the one session at the front of the queue. In real outages it is usually a schema migration waiting behind a long transaction, with everything else queued behind the migration.
Lock waits look like a slow database with low CPU.
SELECT wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE state = 'active' GROUP BY 1, 2 ORDER BY 3 DESC;
SELECT count(*) AS waiting FROM information_schema.innodb_trx WHERE trx_state = 'LOCK WAIT'; SELECT state, count(*) FROM information_schema.processlist GROUP BY 1 ORDER BY 2 DESC;
db.currentOp({ waitingForLock: true }).inprog.lengthLook for: Most active sessions waiting on Lock, or in LOCK WAIT or "Waiting for table metadata lock".
A session that blocks others but is not blocked itself.
SELECT pid, usename, application_name, state,
now() - xact_start AS transaction_age, left(query, 80) AS query
FROM pg_stat_activity
WHERE pid IN (SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity)
AND cardinality(pg_blocking_pids(pid)) = 0;SELECT * FROM sys.innodb_lock_waits\G -- row locks: blocking_pid, blocking_query SELECT * FROM sys.schema_table_lock_waits\G -- metadata locks, such as an ALTER
db.getSiblingDB('admin').aggregate([
{ $currentOp: { allUsers: true, idleSessions: true } },
{ $match: { transaction: { $exists: true } } },
{ $sort: { 'transaction.timeOpenMicros': -1 } }, { $limit: 5 }])Look for: Note what it is and what it is doing.
One counter or one stock row updated by everyone queues by design.
SELECT relation::regclass, mode, granted, count(*) FROM pg_locks WHERE relation IS NOT NULL GROUP BY 1, 2, 3 ORDER BY 4 DESC LIMIT 10;
SELECT object_schema, object_name, lock_type, lock_mode, count(*) FROM performance_schema.data_locks GROUP BY 1, 2, 3, 4 ORDER BY 5 DESC LIMIT 10;
db.serverStatus().locks
Look for: That is a design problem, not an on-call one: get the app team on the call.
The migration is waiting for its lock, and everything queued behind it waits too. Cancelling it restores traffic at once and costs nothing: it can run again later with a lock timeout.
SELECT pid, pg_cancel_backend(pid) FROM pg_stat_activity WHERE query ~* '^\s*(alter|create index|drop|truncate)' AND wait_event_type = 'Lock';
-- find the ALTER waiting for its metadata lock, then KILL QUERY <thread id of the ALTER>;
db.killOp(<opid of the index build or collMod>)
Look for: The queue drains within seconds.
Undo: Rerun the migration with a lock timeout (step 6).
It holds locks and does nothing. Ending it rolls its transaction back.
SELECT pg_cancel_backend(<pid>); -- stops the running query SELECT pg_terminate_backend(<pid>); -- ends the session and rolls back
KILL QUERY <blocking_pid>; -- or KILL <blocking_pid>; to end the connection -- sys.innodb_lock_waits also prints the statements: sql_kill_blocking_connection
db.killOp(<opid>)
Look for: The queue drains. A big transaction takes time to roll back: do not end it twice.
Undo: None. The app retries the work.
An active batch job might be halfway through something important. Ask before you kill it, but do not wait long.
SELECT pg_cancel_backend(<pid>); -- stops the running query SELECT pg_terminate_backend(<pid>); -- ends the session and rolls back
KILL QUERY <blocking_pid>; -- or KILL <blocking_pid>; to end the connection -- sys.innodb_lock_waits also prints the statements: sql_kill_blocking_connection
db.killOp(<opid>)
Look for: Cancel it, then plan to rerun it in smaller transactions.
Undo: The job reruns from its start or its last checkpoint.
A short lock timeout means it gives up quickly instead of blocking everyone. Retry it in a loop until it gets the lock.
SET lock_timeout = '3s'; ALTER TABLE orders ADD COLUMN note text; -- retry until it gets the lock
SET SESSION lock_wait_timeout = 5; ALTER TABLE orders ADD COLUMN note TEXT, ALGORITHM = INSTANT;
// MongoDB schema changes are index builds and collMod; check db.currentOp() for them
Look for: It finishes in a moment or fails fast, and traffic is never stuck behind it.
No session waiting on a lock for more than a few seconds, for 15 minutes.
SELECT wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE state = 'active' GROUP BY 1, 2 ORDER BY 3 DESC;
SELECT count(*) AS waiting FROM information_schema.innodb_trx WHERE trx_state = 'LOCK WAIT'; SELECT state, count(*) FROM information_schema.processlist GROUP BY 1 ORDER BY 2 DESC;
db.currentOp({ waitingForLock: true }).inprog.lengthLook for: Check the app's error rate too.
CALL mysql.rds_kill(<blocking thread id>);
kubectl get jobs -n <ns> kubectl delete job <migration-job> -n <ns>
Database <name>: queries are waiting on locks, so <feature> is timing out. Cause: <migration / transaction> from <app>. We are <action>. Next update <time>.
Done when: No lock waits for 15 minutes, and the migration or transaction that caused it has a safer plan.
The drill: incident 2. The theory: Lost updates and write skew.
Start here. Prove it is one query, find the minute it changed, and get its real plan. Refreshing statistics is cheap and is often the whole fix.
You want the fingerprint and the time its average jumped.
-- needs the pg_stat_statements extension
SELECT calls, round(total_exec_time) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows, left(query, 80) AS query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;SELECT query, exec_count, total_latency, avg_latency,
rows_examined_avg, rows_sent_avg
FROM sys.statement_analysis LIMIT 10; -- sorted by total latencyLook for: Compare its mean time with yesterday in your monitoring.
Real timings and real row counts, not only the estimate.
BEGIN; EXPLAIN (ANALYZE, BUFFERS) <the slow query, with real values>; ROLLBACK;
EXPLAIN ANALYZE <the slow query>;
db.orders.find({ customer_id: 42 }).sort({ created_at: -1 }).explain('executionStats')Look for: Compare the estimated rows with the actual rows at each step.
A failed concurrent build leaves an index that exists but is never used.
SELECT indexrelid::regclass AS index, indisvalid, indisready FROM pg_index WHERE indrelid = 'orders'::regclass;
SHOW INDEX FROM orders; SELECT * FROM sys.schema_unused_indexes WHERE object_name = 'orders';
db.orders.getIndexes()
Look for: Invalid: drop and rebuild it concurrently. Missing: see CPU at 100%, step 7.
A big load or delete changed the table under the planner. This is cheap and takes seconds to minutes.
ANALYZE orders;
ANALYZE TABLE orders; -- for skewed columns, a histogram: ANALYZE TABLE orders UPDATE HISTOGRAM ON customer_id WITH 64 BUCKETS;
db.orders.getPlanCache().clear() // forgets cached plans; the next run plans again
Look for: Run the plan again. Back to the old plan: done.
Undo: Nothing to undo.
One customer with a million rows, or a prepared statement that switched to a generic plan.
-- see the generic plan a prepared statement may switch to (PostgreSQL 16 and later) EXPLAIN (GENERIC_PLAN) SELECT * FROM orders WHERE customer_id = $1; -- for one role, always plan with the real value: ALTER ROLE app_user SET plan_cache_mode = force_custom_plan;
-- a hint, in the query, for the big case SELECT /*+ INDEX(orders orders_customer_created_idx) */ * FROM orders WHERE customer_id = 42;
db.orders.find({ customer_id: 42 }).hint({ customer_id: 1, created_at: -1 })Look for: Pin the plan only as a bandage, and write down why.
Undo: PostgreSQL: ALTER ROLE app_user RESET plan_cache_mode;
A new filter or a new ORDER BY is a new plan.
kubectl rollout undo deployment/<app> -n <namespace>
Look for: The old query and its old plan come back.
The query's average time back to normal for an hour, through some traffic.
-- needs the pg_stat_statements extension
SELECT calls, round(total_exec_time) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows, left(query, 80) AS query
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;SELECT query, exec_count, total_latency, avg_latency,
rows_examined_avg, rows_sent_avg
FROM sys.statement_analysis LIMIT 10; -- sorted by total latencyLook for: Plans can flip back: check again tomorrow.
<feature> is slow because one query changed its plan. We are <action>. Other features are not affected. Next update <time>.
Done when: The query is back to its normal time for an hour, and you know why the plan changed.
Reading plans line by line: Reference. Try it on a real database: Guided tutorials.
Start here. Check whether you are hitting the volume's limit, then find out what is reading: hot data that no longer fits in memory, or one new scan pushing everything out.
A line flat at the provisioned IOPS or throughput is the tell. So is gp2 burst balance at zero.
iostat -x 1 5 # r_await, w_await and %util on the data volume # on AWS also look at the volume's queue length, and BurstBalance for gp2 # AWS: CloudWatch ReadIOPS, WriteIOPS, DiskQueueDepth, BurstBalance for the volume
Look for: Await in tens of ms and utilization near 100 percent, or IOPS flat at the cap.
If it fell, the working set grew or something is scanning.
SELECT blks_hit, blks_read,
round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_database WHERE datname = current_database();SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%'; -- Innodb_buffer_pool_reads (from disk) against Innodb_buffer_pool_read_requests
const c = db.serverStatus().wiredTiger.cache; [c['bytes currently in the cache'], c['maximum bytes configured'], c['pages read into cache']]
Look for: Two readings a minute apart, compared with yesterday.
One report or job usually explains it.
SELECT calls, shared_blks_read, round(total_exec_time) AS total_ms, left(query, 80) FROM pg_stat_statements ORDER BY shared_blks_read DESC LIMIT 10;
SELECT * FROM sys.statements_with_full_table_scans LIMIT 10; SELECT * FROM sys.io_global_by_file_by_latency LIMIT 10;
db.system.profile.find({}, { ns: 1, docsExamined: 1, millis: 1, planSummary: 1 })
.sort({ docsExamined: -1 }).limit(10)Look for: A new report or a scan without an index.
Backups, vacuum, checkpoints and compaction all use the disk.
SELECT pid, relid::regclass, phase, heap_blks_scanned, heap_blks_total FROM pg_stat_progress_vacuum; SELECT * FROM pg_stat_checkpointer; -- PostgreSQL 17 and later; pg_stat_bgwriter before
SHOW ENGINE INNODB STATUS\G -- BUFFER POOL AND MEMORY, and pending flushes
db.serverStatus().wiredTiger.cache['tracked dirty bytes in the cache']
ps aux | grep -E 'pg_basebackup|xtrabackup|mysqldump|mongodump' | grep -v grep
Look for: A backup at peak: move it. Checkpoints every few minutes: max_wal_size is too small.
Keep the live traffic; move the report.
SELECT pg_cancel_backend(<pid>); -- the report found in step 3
KILL QUERY <thread id>;
db.killOp(<opid>)
Look for: Disk wait falls within a minute.
Undo: Rerun it on a replica or off-peak.
gp3 and io2 can be changed online. It costs money, so use it when the load is real.
aws ec2 modify-volume --volume-id <vol> --iops <n> --throughput <MBps> # RDS: modify-db-instance --iops <n> (and --storage-type gp3)
Look for: Latency falls as the change applies.
Disk wait and the hit ratio back to normal for 15 minutes.
SELECT blks_hit, blks_read,
round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_database WHERE datname = current_database();SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%'; -- Innodb_buffer_pool_reads (from disk) against Innodb_buffer_pool_read_requests
const c = db.serverStatus().wiredTiger.cache; [c['bytes currently in the cache'], c['maximum bytes configured'], c['pages read into cache']]
Look for: Watch the next peak.
kubectl get pvc <pvc> -n <ns> -o jsonpath='{.spec.storageClassName}'Database <name>: storage is saturated, so reads are slow. Cause: <what>. We are <action>. Next update <time>.
Done when: Disk latency and hit ratio are back to normal, and the heavy reader has a new home or an index.
How big the hot data is: Capacity calculator.
Start here. First make sure the database is up, in the right role, and not in a crash loop, and that only one node thinks it is the primary. Root cause comes after.
After a crash the database replays its log first. On a cluster, a failover may have happened.
SELECT pg_is_in_recovery(), now() - pg_postmaster_start_time() AS up_for;
SHOW GLOBAL STATUS LIKE 'Uptime'; SELECT @@read_only, @@super_read_only;
rs.status().members.map(m => [m.name, m.stateStr])
Look for: Up and with the expected role: step 3.
The kernel log names the process and the minute.
-- in the PostgreSQL log: -- server process (PID ...) was terminated by signal 9: Killed
-- in the MySQL error log: mysqld restarted, then InnoDB crash recovery
// in the mongod log: no shutdown message before the next startup
dmesg -T | grep -i -E 'killed process|out of memory' journalctl -k --since '2 hours ago' | grep -i -E 'oom|killed process'
Look for: Line it up with your graphs: what spiked at that minute?
Cache plus per-connection memory times connections must fit with room to spare.
SELECT name, setting, unit FROM pg_settings
WHERE name IN ('shared_buffers', 'work_mem', 'maintenance_work_mem',
'hash_mem_multiplier', 'max_connections', 'autovacuum_max_workers');
-- work_mem is per sort or hash, so one query can use it several timesSELECT @@innodb_buffer_pool_size / 1024 / 1024 / 1024 AS buffer_pool_gb,
@@max_connections, @@sort_buffer_size, @@join_buffer_size, @@tmp_table_size;
SELECT * FROM sys.memory_global_by_current_bytes LIMIT 10;db.serverStatus().wiredTiger.cache['maximum bytes configured'] // default: 50 percent of (RAM - 1 GB)
free -g
Look for: A cache near total RAM, or many connections each allowed big sorts.
One query with a huge sort or hash is a common trigger.
-- the log lines just before the kill; to log big sorts from now on: ALTER SYSTEM SET log_temp_files = '100MB'; SELECT pg_reload_conf();
SELECT * FROM performance_schema.memory_summary_by_thread_by_event_name ORDER BY current_number_of_bytes_used DESC LIMIT 10;
// the slow operations in the mongod log just before the restart
Look for: Write it down: it is the one to fix.
If it is killed again as soon as traffic returns, take load off before it comes back: fewer connections, the heavy job stopped.
# stop the job or app that triggered it, or lower its pool, then start the database systemctl status postgresql mysql mongod 2>/dev/null | head -20
Look for: It stays up for 15 minutes with traffic.
Lower the memory for the role that runs big queries; leave room for the OS.
-- lower work_mem for the role that runs big reports, not for everyone ALTER ROLE report_user SET work_mem = '64MB'; -- PostgreSQL's docs recommend vm.overcommit_memory = 2 on dedicated servers
-- leave room: a buffer pool around 70 to 75 percent of RAM on a dedicated server SET PERSIST innodb_buffer_pool_size = <bytes>; -- resizes online
# mongod.conf
storage:
wiredTiger:
engineConfig:
cacheSizeGB: <smaller value>Look for: No OOM through the next peak.
Undo: Set the old values back.
Up, the right role, memory below 85 percent through a peak.
SELECT pg_is_in_recovery(), now() - pg_postmaster_start_time() AS up_for;
SHOW GLOBAL STATUS LIKE 'Uptime'; SELECT @@read_only, @@super_read_only;
rs.status().members.map(m => [m.name, m.stateStr])
Look for: Watch the next day's peak too.
aws rds describe-events --source-type db-instance --source-identifier <id> --duration 1440
kubectl describe pod <db-pod> -n <ns> | grep -A5 'Last State' kubectl logs <db-pod> -n <ns> --previous | tail -50
Database <name> restarted at <time> because it ran out of memory. It is <up / recovering>. Cause: <what>. We are <action>. Next update <time>.
Done when: The database has been stable through a peak, and the memory budget adds up with room to spare.
Where memory goes in each engine: PostgreSQL, MySQL, MongoDB.
Start here. Find what commits are waiting on. All writes hanging at once usually means a synchronous standby is gone; slower writes usually mean the log disk.
This decides the rest.
SELECT wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE state = 'active' GROUP BY 1, 2 ORDER BY 3 DESC; -- WALSync or WALWrite: the disk. SyncRep: a synchronous standby.
SELECT event_name, count_star, sum_timer_wait / 1e12 AS total_s FROM performance_schema.file_summary_by_event_name WHERE event_name LIKE '%innodb_log_file%'; SHOW GLOBAL STATUS LIKE 'Rpl_semi_sync_source%';
db.serverStatus().opLatencies.writes // with writeConcern majority, writes also wait for secondaries
Look for: Read the wait events.
With synchronous replication every commit waits for it. If it is gone, every commit waits forever.
SHOW synchronous_standby_names; SELECT application_name, sync_state, state, flush_lag FROM pg_stat_replication;
SHOW GLOBAL STATUS LIKE 'Rpl_semi_sync_source_status'; SHOW VARIABLES LIKE 'rpl_semi_sync_source_timeout';
rs.printSecondaryReplicationInfo()
Look for: A missing or far-behind sync standby.
Every durable commit waits for one flush.
iostat -x 1 5 # w_await on the log volume pg_test_fsync -f /data/test # PostgreSQL's tool: flushes per second on this disk
Look for: A flush in milliseconds: the volume is slow, shared or throttled.
Every insert updates every index.
SELECT indexrelid::regclass AS index, idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC LIMIT 10;SELECT * FROM sys.schema_unused_indexes;
db.orders.aggregate([{ $indexStats: {} }]) // accesses.ops near 0 means unusedLook for: Not a mid-incident fix: put it in the postmortem.
Dropping to async restores writes at once, and for that time a failover can lose the last commits. This is the service owner's decision, made in the channel, in writing.
-- a dead synchronous standby: commits stop waiting for it ALTER SYSTEM SET synchronous_standby_names = ''; SELECT pg_reload_conf(); -- for a non-critical role only: commits return before the flush ALTER ROLE events_user SET synchronous_commit = off;
-- semi-sync falls back to async after this many ms without an ack SET PERSIST rpl_semi_sync_source_timeout = 1000;
// for non-critical writes only, in the app:
// { writeConcern: { w: 1 } } instead of majorityLook for: Writes flow again.
Undo: Set synchronous_standby_names back once the standby is healthy.
Commit latency back to baseline.
SELECT wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE state = 'active' GROUP BY 1, 2 ORDER BY 3 DESC; -- WALSync or WALWrite: the disk. SyncRep: a synchronous standby.
SELECT event_name, count_star, sum_timer_wait / 1e12 AS total_s FROM performance_schema.file_summary_by_event_name WHERE event_name LIKE '%innodb_log_file%'; SHOW GLOBAL STATUS LIKE 'Rpl_semi_sync_source%';
db.serverStatus().opLatencies.writes // with writeConcern majority, writes also wait for secondaries
Look for: If you dropped to async: a ticket to restore it, with an owner.
kubectl get cluster <name> -n <ns> -o yaml | grep -i -A3 sync
Database <name>: writes are <slow / stopped>. Cause: <standby / disk>. We are <action>. <If async: until fixed, a failover could lose the last seconds of writes.> Next update <time>.
Done when: Commit latency is normal, and any durability change has a ticket and an owner to restore it.
What a commit waits for: Synchronous replication and failover.
Start here. If PostgreSQL is warning about wraparound, everything else waits: find what holds the oldest snapshot, remove it, and vacuum the oldest tables. Bloat on its own is a planning problem, not an outage.
Writes stop near 2 billion. This number decides how urgent the next hour is.
SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY 2 DESC; SELECT relname, age(relfrozenxid) AS xid_age FROM pg_class WHERE relkind = 'r' ORDER BY 2 DESC LIMIT 10;
-- not applicable to MySQL
// not applicable to MongoDB
Look for: Over a billion and climbing: treat it as an outage.
An old transaction, an abandoned replication slot, a forgotten prepared transaction, or a replica with hot_standby_feedback.
-- the oldest snapshots SELECT pid, usename, state, now() - xact_start AS age, backend_xmin FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY age(backend_xmin) DESC LIMIT 5; SELECT slot_name, active, xmin, catalog_xmin FROM pg_replication_slots; SELECT gid, prepared FROM pg_prepared_xacts;
SELECT trx_mysql_thread_id, trx_started, trx_state FROM information_schema.innodb_trx ORDER BY trx_started LIMIT 5;
db.getSiblingDB('admin').aggregate([
{ $currentOp: { allUsers: true, idleSessions: true } },
{ $match: { transaction: { $exists: true } } }])Look for: The oldest of these is the blocker.
Not urgent unless the disk is filling.
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum,
pg_size_pretty(pg_total_relation_size(relid)) AS size
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;SELECT table_name, ROUND(data_free / 1024 / 1024) AS free_mb,
ROUND((data_length + index_length) / 1024 / 1024) AS used_mb
FROM information_schema.tables WHERE table_schema = DATABASE()
ORDER BY data_free DESC LIMIT 10;
SELECT count FROM information_schema.innodb_metrics WHERE name = 'trx_rseg_history_len';db.orders.stats().wiredTiger['block-manager']['file bytes available for reuse']
Look for: Plan the fix; do not rebuild tables in the middle of the day.
Nothing else helps until the oldest snapshot is gone.
SELECT pg_terminate_backend(<pid>); -- the old transaction
SELECT pg_drop_replication_slot('old_slot'); -- only if nobody will read it again
ROLLBACK PREPARED '<gid>'; -- a forgotten prepared transactionKILL <thread id>; -- the old transaction; its rollback can take a while
db.killOp(<opid>)
Look for: The oldest xmin moves forward.
Undo: None. A dropped slot's consumer needs a rebuild.
Start with the tables with the oldest relfrozenxid. Since PostgreSQL 14, vacuum switches to a faster failsafe mode by itself when wraparound is close. Single-user mode is no longer needed in typical cases.
VACUUM (FREEZE, VERBOSE) <the oldest table>; -- watch it from another session SELECT * FROM pg_stat_progress_vacuum;
Look for: age(datfrozenxid) falls after each table.
age(datfrozenxid) well under autovacuum_freeze_max_age, and autovacuum keeping up.
SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY 2 DESC; SELECT relname, age(relfrozenxid) AS xid_age FROM pg_class WHERE relkind = 'r' ORDER BY 2 DESC LIMIT 10;
-- not applicable to MySQL
// not applicable to MongoDB
Database <name>: PostgreSQL needs an urgent vacuum to keep accepting writes. Cause: <blocker>. We have <removed it> and are vacuuming. Writes <are / are not> affected. Next update <time>.
Done when: The age is falling and well below the alert line, the blocker is gone, and autovacuum keeps up on its own.
Why it happens: Start here, and the MVCC timeline lab.
The failures that come from the HA layer itself: Patroni and etcd, InnoDB Cluster, MongoDB replica sets, managed failovers on RDS and Aurora, and databases running in pods. First what high availability means and how each engine does it, then, for each setup, the issues DBAs keep seeing with the usual fix, and the playbooks.
High availability means the database keeps taking reads and writes when one server, one disk or one zone fails. It never means zero downtime: there is always a gap while the system notices the failure and switches. Two numbers describe any setup:
Every HA setup does the same three jobs. The engines differ in which of them are built in.
Another server has the data, current to the last second or the last commit. That is replication.
Something notices the primary is gone and picks exactly one replacement. Exactly one is the hard part: two primaries taking different writes is worse than an outage.
Apps have to find the new primary: a router, a proxy, DNS, or a driver that watches the cluster.
HA is not a backup. A DROP TABLE or a bad UPDATE reaches every replica in milliseconds. You still need backups and point-in-time recovery: see Backups and restore time.
| PostgreSQL + Patroni | MySQL InnoDB Cluster | MongoDB replica set | RDS and Aurora | |
|---|---|---|---|---|
| Keeps a copy with | Streaming WAL replication. Asynchronous by default; synchronous if you ask for it. | Group Replication: a majority agrees on every transaction before it commits. | The oplog, replayed by secondaries. w: majority is the default write concern since 5.0. | Multi-AZ: a synchronous standby. Aurora: six copies across three zones, four needed for a write. |
| Who decides the new primary | Not built in. Patroni runs on every node and uses etcd (or Consul, ZooKeeper) to hold one leader key. | Built in. Group Replication elects a new primary; MySQL Shell (AdminAPI) sets it up and repairs it. | Built in. Members hold an election, using a Raft-like consensus protocol. | AWS. |
| How clients find it | HAProxy checking Patroni's REST API, a virtual IP, or a multi-host connection string with target_session_attrs=read-write. | MySQL Router: port 6446 for writes, 6447 for reads. | The drivers discover the set and follow the primary. | A DNS endpoint that moves to the new primary. |
| Typical time to switch | Up to about 30 seconds with the default ttl, plus the time for clients to reconnect. | Seconds: about 5 to suspect a member and 5 more to expel it, by default. | A median of 12 seconds or less with default settings (MongoDB docs). | Multi-AZ instance 60 to 120 s. Multi-AZ cluster under 35 s. Aurora under 60 s, often under 30 s (AWS docs). |
| What a failover can lose | With async replication, the last commits not yet streamed. Patroni will not promote a replica more than 1 MB behind by default. With synchronous_mode on, nothing confirmed is lost. | Nothing it confirmed, in single-primary mode: a majority already had it. | Nothing written with w: majority. Writes with w: 1 can be rolled back. | Multi-AZ and Aurora: nothing committed. |
| What you run | PostgreSQL on 2 or more nodes, Patroni, a 3-node etcd, HAProxy. | 3 or more MySQL servers, MySQL Router, MySQL Shell. | 3 data-bearing mongod (avoid arbiters). | Nothing yourself. You pay for the standby. |
The short version: MongoDB has all three jobs built in. MySQL has the copy and the election built in with Group Replication, and adds Router to send clients. PostgreSQL has only the copy built in; the decision and the routing come from tools around it, most often Patroni with etcd and HAProxy. RDS and Aurora do all three for you, at the cost of control and a longer switch on a Multi-AZ instance.
Pick the engine. Each one stops once to ask you a question.
Why majorities and leader keys matter: Consensus and leaders and CAP as settings you choose. The trade-off between waiting for a standby and losing writes: What a commit waits for.
| Issue | What you see | What we do |
|---|---|---|
| etcd loses quorum | Primary demotes to read-only; no Leader | Restore etcd majority; Patroni elects by itself Playbook → |
| etcd NOSPACE alarm | Patroni cannot write its key; cluster goes read-only | Compact, defrag, disarm; schedule auto-compaction Playbook → |
| Slow etcd disk | Leader changes, "failed to update leader lock" | Move etcd to its own fast disk Playbook → |
| Short pauses trigger failovers | Failovers with nothing really broken | Pause, fix the cause, set ttl and retry_timeout to fit Playbook → |
| Old primary diverged | Will not rejoin: timeline errors | use_pg_rewind, else patronictl reinit Playbook → |
| synchronous_mode_strict with no sync standby | All writes hang | Bring a standby back, or turn strict off with the owner agreeing Playbook → |
| Apps keep old connections | Errors after the failover finished | Restart pools; route through HAProxy on the REST API Playbook → |
Start here. Look at etcd before PostgreSQL. A Patroni cluster with no leader is almost always a DCS problem, and PostgreSQL is doing exactly what it should.
Roles, states, lag and timeline for every member.
patronictl -c /etc/patroni/patroni.yml list patronictl -c /etc/patroni/patroni.yml history | tail -5
Look for: No Leader, or a Leader whose state is not running.
Patroni needs a majority of etcd members to keep the leader key.
etcdctl endpoint health --cluster etcdctl endpoint status --cluster -w table # leader, DB size, raft term etcdctl alarm list
Look for: Read the result.
They say why it stepped down.
journalctl -u patroni --since '30 min ago' | grep -i -E 'demot|lock|dcs|timeout' | tail -30
Look for: "failed to update leader lock" means it could not reach etcd in time; look at the network and etcd disk latency.
Start the stopped members or fix the network between them. Patroni elects a leader by itself once etcd answers.
systemctl status etcd systemctl start etcd # on the members that are down etcdctl member list -w table
Look for: A leader appears in patronictl list within a loop or two (10 to 30 seconds).
etcd keeps old revisions until compacted. At the quota (2 GB by default) it refuses writes, so Patroni cannot write its key.
rev=$(etcdctl endpoint status --write-out=json | grep -o '"revision":[0-9]*' | head -1 | cut -d: -f2) etcdctl compact $rev etcdctl defrag --cluster etcdctl alarm disarm
Look for: alarm list is empty and Patroni elects a leader.
Undo: Nothing to undo.
Last resort. Patroni will not promote without a DCS. Pausing Patroni and promoting one node by hand means you, not Patroni, now guarantee there is only one primary.
patronictl -c /etc/patroni/patroni.yml pause # on the node you choose, after checking it has the most WAL: sudo -u postgres pg_ctl promote -D <data dir>
Look for: One writable primary, and every app pointed at it.
Undo: patronictl -c /etc/patroni/patroni.yml resume, once etcd is healthy and the others follow this primary.
SELECT pg_is_in_recovery();
patronictl -c /etc/patroni/patroni.yml list
Look for: One Leader, replicas streaming, lag near zero.
PostgreSQL cluster <name> has no writable primary because <etcd / network>. Reads work, writes fail. We are <action>. Next update <time>.
Done when: One leader, every replica streaming, etcd healthy with room under its quota.
Why Patroni demotes instead of guessing: Consensus and leaders.
Start here. Find out why the old primary lost its lease, then make sure the old primary came back as a replica and the apps follow the new one. Pause Patroni if it keeps flapping.
The history shows each failover with its time and the new leader.
patronictl -c /etc/patroni/patroni.yml history patronictl -c /etc/patroni/patroni.yml list
Look for: A new leader, and whether the old one is back.
Its Patroni log just before the failover.
journalctl -u patroni --since '<time - 5 min>' --until '<time + 2 min>' | grep -v -i 'no action' journalctl -k --since '<time - 5 min>' | tail -20 # OOM or I/O errors
Look for: "failed to update leader lock", a missing heartbeat, or a crash.
Apps that cached the old address, or pools that never reconnect, keep failing after the database is fine.
SELECT client_addr, application_name, count(*) FROM pg_stat_activity GROUP BY 1, 2 ORDER BY 3 DESC;
curl -s http://<node>:8008/primary -o /dev/null -w '%{http_code}\n' # 200 only on the leaderLook for: Apps missing from the new primary: their pools hold dead connections. Restart those pods or services.
Pausing stops automatic failover while you fix the cause. The current primary stays primary.
patronictl -c /etc/patroni/patroni.yml pause --wait
Look for: No new failovers. Remember to resume.
Undo: patronictl -c /etc/patroni/patroni.yml resume
If short pauses trigger failovers, the timings are tighter than your infrastructure.
patronictl -c /etc/patroni/patroni.yml edit-config # ttl, loop_wait, retry_timeout: keep loop_wait + 2*retry_timeout <= ttl
Look for: Longer ttl means slower failover but fewer false ones. Pick on purpose.
patronictl -c /etc/patroni/patroni.yml list
Look for: One leader, replicas streaming, no new history entries for an hour.
PostgreSQL cluster <name> failed over at <time> from <old> to <new>. Writes failed for <n> seconds. Cause: <what>. Next update <time>.
Done when: One leader for an hour, the old primary back as a replica, and the reason written down.
Start here. Do not force it. Let Patroni rewind it, and if that cannot work, rebuild it from the new primary.
patronictl -c /etc/patroni/patroni.yml list journalctl -u patroni -n 50 | grep -i -E 'timeline|rewind|wal'
Look for: A timeline or rewind error.
pg_rewind copies back only the blocks that changed. It needs use_pg_rewind and wal_log_hints or checksums.
patronictl -c /etc/patroni/patroni.yml edit-config # postgresql.use_pg_rewind: true patronictl -c /etc/patroni/patroni.yml restart <cluster> <member>
Look for: It starts as a replica on the new timeline.
Takes a fresh copy. The writes it had that never reached the new primary are lost: save its data directory first if anyone needs them.
patronictl -c /etc/patroni/patroni.yml reinit <cluster> <member>
Look for: It streams again. Time it.
Undo: None. The old data is replaced.
patronictl -c /etc/patroni/patroni.yml list
Look for: Running, the new timeline, lag near zero.
The old primary <node> is being rebuilt as a replica. No user impact; failover protection is reduced until it finishes at about <time>.
Done when: Every member streams on the current timeline.
| Issue | What you see | What we do |
|---|---|---|
| Majority of members lost | Writes hang, NO_QUORUM | Prove the others are down, then forceQuorumUsingPartitionOf Playbook → |
| All members restarted | Cluster OFFLINE | rebootClusterFromCompleteOutage on the most advanced member Playbook → |
| One slow member | Primary writes slow, applier queue growing on one member | Remove it from the group, fix, add back with clone Playbook → |
| Huge transaction | Member expelled, error about transaction size | Chunk the write; rejoin the member Playbook → |
| Errant GTIDs | Member will not rejoin | Remove and re-add with clone Playbook → |
| Apps bypass Router | Writes fail on the old primary after failover | Connect through Router 6446; restart pools Playbook → |
Start here. Find out which members are truly down and which are only unreachable. Forcing quorum on the wrong side creates two clusters accepting writes.
The Shell view and the server view.
SELECT MEMBER_HOST, MEMBER_STATE, MEMBER_ROLE FROM performance_schema.replication_group_members;
mysqlsh --js clusteradmin@<node>:3306 -e "print(dba.getCluster().status({extended: 1}))"Look for: Read the states.
If they are alive on the other side of a network split, forcing quorum here gives you two primaries.
# on each unreachable host, or through your cloud console: systemctl status mysqld ping <host>
Look for: Down for certain: step 3. Alive but cut off: fix the network instead.
Tells the group to continue with only the members you name.
mysqlsh --js clusteradmin@<node>:3306 -e "dba.getCluster().forceQuorumUsingPartitionOf('<surviving node>:3306')"Look for: Writes resume on the surviving primary.
Undo: Rejoin the other members once they are back (rejoinInstance).
Run it on the member with the most transactions (the most complete GTID set). Shell checks and tells you if another member is ahead.
mysqlsh --js clusteradmin@<node>:3306 -e "dba.rebootClusterFromCompleteOutage()"
Look for: The cluster is ONLINE with that member as primary; the others rejoin.
SELECT MEMBER_HOST, MEMBER_STATE, MEMBER_ROLE FROM performance_schema.replication_group_members;
mysqlsh --js clusteradmin@<node>:3306 -e "print(dba.getCluster().status())"
Look for: Status OK, every member ONLINE.
MySQL cluster <name> lost quorum at <time>; writes are failing. We are <action>. Next update <time>.
Done when: Every member ONLINE, status OK, Router routing writes to the primary.
How Group Replication decides: Consensus and leaders.
Start here. Find out whether the member is slowing the group (remove it fast) or just missing (rejoin it). Then rejoin, or rebuild it with clone.
Large queues on one member mean it cannot keep up.
SELECT m.MEMBER_HOST, m.MEMBER_STATE, s.COUNT_TRANSACTIONS_IN_QUEUE AS certify_queue,
s.COUNT_TRANSACTIONS_REMOTE_IN_APPLIER_QUEUE AS apply_queue
FROM performance_schema.replication_group_members m
JOIN performance_schema.replication_group_member_stats s USING (MEMBER_ID);mysqlsh --js clusteradmin@<node>:3306 -e "print(dba.getCluster().status({extended: 1}))"Look for: Read the states and queues.
The member's error log says expelled, errant GTIDs or a failed recovery.
grep -i -E 'group_replication|expel|errant|gtid' /var/log/mysqld.log | tail -30
Look for: Errant GTIDs or missing binlogs: rebuild it (step 4).
Flow control slows every write to the speed of the slowest member. Removing it restores the primary at once.
mysqlsh --js clusteradmin@<node>:3306 -e "dba.getCluster().removeInstance('<slow node>:3306', {force: true})"Look for: Primary write latency recovers.
Undo: addInstance it back once its disk or load is fixed.
rejoinInstance for a member that only fell out. Clone replaces its data with a fresh copy when GTIDs do not match.
mysqlsh --js clusteradmin@<node>:3306 -e "dba.getCluster().rejoinInstance('<node>:3306')"
# if that fails:
mysqlsh --js clusteradmin@<node>:3306 -e "var c = dba.getCluster(); c.removeInstance('<node>:3306', {force: true}); c.addInstance('<node>:3306', {recoveryMethod: 'clone'})"Look for: The member goes RECOVERING, then ONLINE.
SELECT MEMBER_HOST, MEMBER_STATE FROM performance_schema.replication_group_members;
Look for: Every member ONLINE, queues near zero.
One member of MySQL cluster <name> is <out / slow>. <Writes are affected / not affected.> We are <action>. Next update <time>.
Done when: Every member ONLINE with empty queues.
Start here. Check what the apps connect to, then what Router thinks the primary is.
mysqlsh --js clusteradmin@<node>:3306 -e "print(dba.getCluster().listRouters())" tail -50 /var/log/mysqlrouter/mysqlrouter.log
Look for: Errors fetching metadata, or a router that has not checked in recently.
Router listens on 6446 for read-write and 6447 for read-only by default (classic protocol).
SELECT user, SUBSTRING_INDEX(host, ':', 1) AS client, count(*) FROM information_schema.processlist GROUP BY 1, 2 ORDER BY 3 DESC;
Look for: Apps connected straight to the old primary's address bypass Router.
A restart makes Router reload metadata. Restarting app pods clears pools holding old connections.
systemctl restart mysqlrouter # or restart the app instances whose pools hold old connections
Look for: Writes succeed through 6446.
SELECT @@hostname, @@read_only, @@super_read_only;
Look for: Through port 6446 this returns the primary with read_only = 0.
MySQL cluster <name> failed over to <node>. The database is healthy; <apps> are still pointed at the old primary and we are restarting their connections.
Done when: All apps write through Router to the new primary.
| Issue | What you see | What we do |
|---|---|---|
| Majority of voters down | No PRIMARY, NotWritablePrimary errors | Bring members back; force reconfig only as last resort Playbook → |
| Network flaps | Elections every few minutes | Fix the network; check heartbeats and an overloaded primary Playbook → |
| PSA with the secondary down | Majority writes hang, cache pressure on the primary | Set the down member to votes 0, priority 0 Playbook → |
| Member down too long | Too stale to catch up | Initial sync; a larger oplog Playbook → |
| w: 1 writes before a failover | Rollback files on the old primary, writes missing | w: majority for data that matters Playbook → |
Start here. Count the healthy voting members against the majority. With a majority, the set elects by itself; without one, you either bring members back or force a reconfig, which can lose writes.
rs.status().members.map(m => [m.name, m.stateStr, m.health, m.lastHeartbeatMessage]) rs.conf().members.map(m => [m.host, m.votes, m.priority, m.arbiterOnly])
Look for: Count healthy voters against the total.
The logs say which member called the election and why.
grep -E 'Starting an election|stepping down|heartbeat' /var/log/mongodb/mongod.log | tail -30
Look for: Heartbeat timeouts point at the network or an overloaded primary (see CPU at 100%).
The safe fix: start them, fix the network. The set elects a primary by itself once a majority sees each other.
systemctl status mongod systemctl start mongod
Look for: A PRIMARY appears within seconds of a majority.
Run on a healthy secondary. It drops the missing members from the config so the rest can elect. Writes the old primary had that never replicated will be rolled back later.
cfg = rs.conf()
cfg.members = cfg.members.filter(m => ['<host1>:27017', '<host2>:27017'].includes(m.host))
rs.reconfig(cfg, { force: true })Look for: One PRIMARY. Add the others back when they return.
Undo: Reconfig again to add the members back once they are healthy.
rs.status().members.map(m => [m.name, m.stateStr])
Look for: One PRIMARY, no new elections for an hour.
MongoDB replica set <name> has no primary since <time>; writes fail. We are <action>. Next update <time>.
Done when: One primary for an hour, every member healthy.
Elections and majorities: CAP as settings you choose.
Start here. Check the oplog window against how long the member was gone, and whether a majority of data-bearing members is up for majority writes.
rs.printReplicationInfo() // the oplog window on this member rs.printSecondaryReplicationInfo() rs.status().members.map(m => [m.name, m.stateStr, m.optimeDate])
Look for: Read the states.
In a PSA set, set the unavailable secondary to votes 0 and priority 0. The majority then forms without it and majority writes flow.
cfg = rs.conf() m = cfg.members.find(x => x.host === '<down host>:27017') m.votes = 0; m.priority = 0 rs.reconfig(cfg)
Look for: Majority writes succeed again.
Undo: Set votes and priority back once the member has caught up.
Stop it, empty its data directory, start it: it runs an initial sync from another member.
systemctl stop mongod mv /var/lib/mongodb /var/lib/mongodb.old && mkdir /var/lib/mongodb && chown mongodb: /var/lib/mongodb systemctl start mongod
Look for: It goes STARTUP2, then SECONDARY. Initial sync on a big set takes hours.
So a member can be down longer next time.
db.adminCommand({ replSetResizeOplog: 1, size: <megabytes> }) // on each memberLook for: rs.printReplicationInfo() shows a longer window.
rs.status().members.map(m => [m.name, m.stateStr])
MongoDB replica set <name>: member <host> is <stale / down>. <Majority writes are affected / not affected.> We are <action>.
Done when: Every member healthy and a comfortable oplog window.
| Issue | What you see | What we do |
|---|---|---|
| Multi-AZ failover | A minute or two of errors, same endpoint | Read RDS events; restart pools that did not follow Playbook → |
| JVM caches DNS | Errors long after the failover completed | Short DNS TTL, RDS Proxy or the AWS JDBC wrapper Playbook → |
| Burstable instance out of CPU credits | Slow everything in Standard mode, CPU capped to baseline; surplus-credit charges in Unlimited mode | Move off t-class, or check the credit mode Playbook → |
| Storage full on RDS | Instance in storage-full, writes stop | Modify allocated storage; turn on autoscaling Playbook → |
| Liveness probe kills a busy database | CrashLoopBackOff under load or during recovery | Lenient liveness, a startupProbe Playbook → |
| Memory settings sized for the node | OOMKilled, exit code 137 | Fit buffers to the container limit Playbook → |
| Volume pinned to one zone | Pod Pending after a node loss | Capacity in that zone; never delete the PVC Playbook → |
Start here. Read the RDS events first: they tell you what AWS did and when. Then make sure the apps followed the endpoint.
aws rds describe-events --source-type db-instance --source-identifier <id> --duration 180 aws rds describe-db-instances --db-instance-identifier <id> --query 'DBInstances[0].[DBInstanceStatus,AvailabilityZone,SecondaryAvailabilityZone]'
Look for: A failover with its reason, or a status such as storage-full.
aws rds describe-db-clusters --db-cluster-identifier <cluster> --query 'DBClusters[0].DBClusterMembers'
Look for: The member with IsClusterWriter true.
The endpoint name moved; apps that cached the IP, or pools with old connections, keep failing.
dig +short <endpoint> # should resolve to the new writer
Look for: Errors continue after the event says completed: restart the app pools.
kubectl rollout restart deployment/<app> -n <ns>
Look for: Errors stop.
aws rds describe-db-instances --db-instance-identifier <id> --query 'DBInstances[0].DBInstanceStatus'
Look for: available, and the apps' error rates are back to normal.
Database <name> on RDS failed over at <time> (<reason from the event>). It is available again. <Apps> are <reconnected / being restarted>.
Done when: Available, the apps reconnected, and the reason from the event written down.
Start here. Read why the last container ended before changing anything. A probe kill and an OOM kill look the same from the app and need opposite fixes.
kubectl get pod <db-pod> -n <ns> -o wide kubectl describe pod <db-pod> -n <ns> | grep -A8 -E 'Last State|Events' kubectl logs <db-pod> -n <ns> --previous | tail -40
Look for: Read the reason.
kubectl describe pod <db-pod> -n <ns> | grep -A10 Events
kubectl get pvc -n <ns>
kubectl get pv <pv> -o jsonpath='{.spec.nodeAffinity}'Look for: A volume pinned to a zone with no free node: add capacity in that zone. Do not delete the PVC.
A database replaying its log or under heavy load can miss a short probe. Give it a longer timeout, or a startupProbe for crash recovery.
kubectl edit <operator resource or statefulset> -n <ns> # livenessProbe: timeoutSeconds 10+, failureThreshold 6+; add a startupProbe for recovery
Look for: Restarts stop climbing.
Either raise the limit, or lower the database's memory settings so they fit inside it.
kubectl get pod <db-pod> -n <ns> -o jsonpath='{.spec.containers[*].resources.limits.memory}'
# then change the limit or the database settings in the operator's resourceLook for: No more OOMKilled through a peak.
kubectl get pods -n <ns> kubectl cnpg status <cluster> -n <ns> # or the operator's equivalent
Look for: Ready, no new restarts for an hour, replicas healthy.
Database <name> on Kubernetes is restarting because <reason>. <Impact>. We are <action>. Next update <time>.
Done when: The pod is Ready with no new restarts for an hour.
Start here. Redis runs one command at a time, so one slow command or a full memory affects everyone. Check memory and the slow log, then find the client causing it.
Writes are refused when memory hits maxmemory with noeviction.
redis-cli INFO memory | grep -E 'used_memory_human|maxmemory_human|maxmemory_policy|mem_fragmentation_ratio' redis-cli INFO stats | grep -E 'evicted_keys|rejected_connections'
Look for: Near the limit: step 5.
One slow command delays every client.
redis-cli SLOWLOG GET 10 redis-cli --latency # live latency from this client redis-cli LATENCY DOCTOR # needs latency-monitor-threshold set
Look for: KEYS, big SMEMBERS or HGETALL, or a long script.
CLIENT LIST shows each connection's last command and its address.
redis-cli CLIENT LIST | grep -E 'cmd=(keys|smembers|hgetall|eval)' # each line has id=, addr= and name=: the address tells you which app
Look for: Note the address and name. That is the team to call.
One key with millions of members makes every command on it slow.
redis-cli --bigkeys # scans with SCAN; run it on a replica if you can redis-cli --memkeys redis-cli MEMORY USAGE <key>
Look for: Split it in the app; delete with UNLINK.
For a cache, let Redis evict. Remove the big key without blocking, and disconnect the client running KEYS.
redis-cli CONFIG SET maxmemory-policy allkeys-lru # only if every key can be rebuilt redis-cli UNLINK <big key> redis-cli CONFIG REWRITE # keep the change after a restart redis-cli CLIENT KILL ID <id>
Look for: Writes succeed and latency falls.
Undo: CONFIG SET maxmemory-policy <old policy>
p99 back to normal, memory below the limit.
redis-cli SLOWLOG GET 10 redis-cli --latency # live latency from this client redis-cli LATENCY DOCTOR # needs latency-monitor-threshold set
Redis <name>: <slow / refusing writes>. Cause: <what>. We are <action>. Next update <time>.
Done when: Latency is normal, memory is below the limit, and the key or client that caused it has an owner and a fix.
How Redis works and where it breaks: Redis, the cache in front.
Start here. With replication factor 3, one sick node should not be an outage. Find it, take client traffic off it, then fix the table that makes it sick.
Pending reads and dropped messages show which nodes are struggling.
nodetool status # every node should be UN (up, normal) nodetool tpstats # Pending and Blocked tasks, and dropped messages
Look for: One or two nodes stand out: step 2.
Partition size and SSTables per read.
nodetool tablehistograms <keyspace> <table> # partition size and SSTables per read nodetool tablestats <keyspace>.<table> # max partition bytes, tombstones per slice
Look for: Huge partitions or many SSTables per read.
Deletes and TTLs pile up.
grep -i tombstone /var/log/cassandra/system.log | tail -20
Look for: A data model problem: get the app team on the call.
Behind on compaction, or long GC pauses.
nodetool compactionstats # pending tasks nodetool gcstats grep GCInspector /var/log/cassandra/system.log | tail -10
The other replicas serve the reads. The node keeps receiving writes and catches up.
nodetool disablebinary # stop serving CQL clients on this node # later: nodetool enablebinary
Look for: Read latency falls for clients.
Undo: nodetool enablebinary
A replica missed a delete.
nodetool repair -pr <keyspace> # on every node in turn, primary ranges only
Look for: Schedule repair within gc_grace_seconds.
Then put the node back.
nodetool enablebinary nodetool tpstats
kubectl exec -it <cassandra-pod> -n <ns> -c cassandra -- nodetool status
Cassandra <cluster>: reads are slow on <nodes>. We have taken them out of client traffic. Cause: <what>. Next update <time>.
Done when: Latency is even across nodes, every node is serving again, and the table has a fix planned.
How Cassandra spreads data and where it breaks: Cassandra, built to spread. A real case: Discord's 20 second channel.
Start here. Measure recall against an exact search on a real query first. "The answers got worse" is not a database finding until you have that number. Commands are for pgvector.
Recall is how many true nearest neighbours the index found.
-- approximate, using the index SELECT id FROM items ORDER BY embedding <=> :q LIMIT 10; -- exact, without the index BEGIN; SET LOCAL enable_indexscan = off; SELECT id FROM items ORDER BY embedding <=> :q LIMIT 10; COMMIT;
Look for: 9 or 10 of 10 is good.
The index returns its candidates, then the filter throws most away.
EXPLAIN ANALYZE SELECT id FROM items WHERE tenant_id = 7 ORDER BY embedding <=> :q LIMIT 10; -- an index scan, then Filter with many Rows Removed
Look for: Many rows removed by the filter.
From disk, every hop in the graph is a read.
SELECT pg_size_pretty(pg_relation_size('items_embedding_idx'));
SHOW shared_buffers;Look for: Much bigger than memory: more RAM, halfvec, or partitions.
Let the index keep scanning, or give the big tenant its own index.
-- pgvector 0.8 and later: keep scanning until LIMIT rows pass the filter SET hnsw.iterative_scan = relaxed_order; -- or a partial index for a big tenant CREATE INDEX CONCURRENTLY items_t7_emb ON items USING hnsw (embedding vector_cosine_ops) WHERE tenant_id = 7;
Look for: The filtered query returns the full LIMIT.
More of the graph searched, more true neighbours found.
SET hnsw.ef_search = 100; -- default 40; must be at least LIMIT SET ivfflat.probes = 10; -- default 1
Look for: Recall up and latency acceptable.
Undo: RESET hnsw.ef_search;
One query is not a test.
-- approximate, using the index SELECT id FROM items ORDER BY embedding <=> :q LIMIT 10; -- exact, without the index BEGIN; SET LOCAL enable_indexscan = off; SELECT id FROM items ORDER BY embedding <=> :q LIMIT 10; COMMIT;
<feature> search is <missing results / slow>. Cause: <what>. We are <action>. Next update <time>.
Done when: Recall on real queries is back where you want it, and filtered searches return the full number of results.
How vector indexes work: Vector databases. Measured (lab run Nov 19, 2026): a tenant filter after HNSW returned 1.3 rows instead of 10.
To practise before it is real, work through On call tonight.
The same mechanism, old row versions, vacuum and long transactions, replication and failover, indexes and plans, elsewhere on the site: in real incidents, in measurements, and in designs.
How do I run it in production? What to check when it is slow or broken, where it runs and what it costs, how big it must be, pooling, backups, security, upgrades and other changes made safely.