{
 "_about": "On-call playbooks, written the way a staff DBA runs an outage, and structured for a DBA agent. Rendered on symptoms/index.html. Risk: read (only reads), low (a change that is easy to undo), high (a human decides). platform: what changes on RDS/Aurora (rds) and Kubernetes (k8s). HA playbooks carry group and eng.",
 "version": 3,
 "first5": [
  {
   "t": "Is it the database at all?",
   "d": "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."
  },
  {
   "t": "How wide, and since when?",
   "d": "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."
  },
  {
   "t": "What changed just before that minute?",
   "d": "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."
  },
  {
   "t": "Open the incident and say who drives",
   "d": "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."
  },
  {
   "t": "Save the evidence before you change anything",
   "d": "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.",
   "cmd": {
    "shell": {
     "pg": "F=/tmp/incident-$(date +%Y%m%d-%H%M)\npsql -XAt -F'|' -c \"SELECT now(), pid, usename, application_name, client_addr, state,\n  wait_event_type, wait_event, xact_start, query_start, left(query, 300)\n  FROM pg_stat_activity\" > $F-activity.txt\npsql -XAt -F'|' -c \"SELECT pid, pg_blocking_pids(pid), wait_event, left(query, 200)\n  FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0\" > $F-blocking.txt\npsql -XAt -c \"SELECT * FROM pg_stat_replication\" > $F-replication.txt",
     "my": "F=/tmp/incident-$(date +%Y%m%d-%H%M)\nmysql -e \"SHOW FULL PROCESSLIST\" > $F-processlist.txt\nmysql -e \"SHOW ENGINE INNODB STATUS\\G\" > $F-innodb.txt\nmysql -e \"SELECT * FROM sys.innodb_lock_waits\\G\" > $F-lockwaits.txt\nmysql -e \"SHOW REPLICA STATUS\\G\" > $F-replica.txt",
     "mo": "F=/tmp/incident-$(date +%Y%m%d-%H%M)\nmongosh --quiet --eval 'printjson(db.currentOp(true))' > $F-currentop.json\nmongosh --quiet --eval 'printjson(db.serverStatus())' > $F-serverstatus.json\nmongosh --quiet --eval 'printjson(rs.status())' > $F-rs.json"
    }
   }
  },
  {
   "t": "One change at a time, written down",
   "d": "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."
  }
 ],
 "agent": {
  "policy": {
   "read": "An agent may run it without asking.",
   "low": "An agent proposes it with the evidence, and runs it after one human approves.",
   "high": "An agent prepares it and explains the trade-off. A human decides and runs it, ideally with a second person agreeing."
  },
  "order": [
   "Match signals to a playbook.",
   "Run the first five minutes: scope, what changed, save evidence.",
   "Run the confirm and cause steps (read only), following the branches.",
   "Propose mitigations in the order given, least risky first, each with its risk, undo and time box.",
   "Verify, post the status update, and draft the postmortem from the evidence."
  ]
 },
 "issues": {
  "patroni": [
   "Patroni with etcd (PostgreSQL)",
   [
    [
     "etcd loses quorum",
     "Primary demotes to read-only; no Leader",
     "Restore etcd majority; Patroni elects by itself",
     "patroni-readonly"
    ],
    [
     "etcd NOSPACE alarm",
     "Patroni cannot write its key; cluster goes read-only",
     "Compact, defrag, disarm; schedule auto-compaction",
     "patroni-readonly"
    ],
    [
     "Slow etcd disk",
     "Leader changes, \"failed to update leader lock\"",
     "Move etcd to its own fast disk",
     "patroni-failover"
    ],
    [
     "Short pauses trigger failovers",
     "Failovers with nothing really broken",
     "Pause, fix the cause, set ttl and retry_timeout to fit",
     "patroni-failover"
    ],
    [
     "Old primary diverged",
     "Will not rejoin: timeline errors",
     "use_pg_rewind, else patronictl reinit",
     "patroni-rejoin"
    ],
    [
     "synchronous_mode_strict with no sync standby",
     "All writes hang",
     "Bring a standby back, or turn strict off with the owner agreeing",
     "commits"
    ],
    [
     "Apps keep old connections",
     "Errors after the failover finished",
     "Restart pools; route through HAProxy on the REST API",
     "patroni-failover"
    ]
   ]
  ],
  "innodb": [
   "InnoDB Cluster (Group Replication and MySQL Router)",
   [
    [
     "Majority of members lost",
     "Writes hang, NO_QUORUM",
     "Prove the others are down, then forceQuorumUsingPartitionOf",
     "innodb-quorum"
    ],
    [
     "All members restarted",
     "Cluster OFFLINE",
     "rebootClusterFromCompleteOutage on the most advanced member",
     "innodb-quorum"
    ],
    [
     "One slow member",
     "Primary writes slow, applier queue growing on one member",
     "Remove it from the group, fix, add back with clone",
     "innodb-member"
    ],
    [
     "Huge transaction",
     "Member expelled, error about transaction size",
     "Chunk the write; rejoin the member",
     "innodb-member"
    ],
    [
     "Errant GTIDs",
     "Member will not rejoin",
     "Remove and re-add with clone",
     "innodb-member"
    ],
    [
     "Apps bypass Router",
     "Writes fail on the old primary after failover",
     "Connect through Router 6446; restart pools",
     "innodb-router"
    ]
   ]
  ],
  "mongo": [
   "MongoDB replica set",
   [
    [
     "Majority of voters down",
     "No PRIMARY, NotWritablePrimary errors",
     "Bring members back; force reconfig only as last resort",
     "mongo-noprimary"
    ],
    [
     "Network flaps",
     "Elections every few minutes",
     "Fix the network; check heartbeats and an overloaded primary",
     "mongo-noprimary"
    ],
    [
     "PSA with the secondary down",
     "Majority writes hang, cache pressure on the primary",
     "Set the down member to votes 0, priority 0",
     "mongo-member"
    ],
    [
     "Member down too long",
     "Too stale to catch up",
     "Initial sync; a larger oplog",
     "mongo-member"
    ],
    [
     "w: 1 writes before a failover",
     "Rollback files on the old primary, writes missing",
     "w: majority for data that matters",
     "mongo-noprimary"
    ]
   ]
  ],
  "cloud": [
   "RDS, Aurora and Kubernetes",
   [
    [
     "Multi-AZ failover",
     "A minute or two of errors, same endpoint",
     "Read RDS events; restart pools that did not follow",
     "rds-failover"
    ],
    [
     "JVM caches DNS",
     "Errors long after the failover completed",
     "Short DNS TTL, RDS Proxy or the AWS JDBC wrapper",
     "rds-failover"
    ],
    [
     "Burstable instance out of CPU credits",
     "Slow everything, CPU capped",
     "Move off t-class, or unlimited mode",
     "cpu"
    ],
    [
     "Storage full on RDS",
     "Instance in storage-full, writes stop",
     "Modify allocated storage; turn on autoscaling",
     "disk"
    ],
    [
     "Liveness probe kills a busy database",
     "CrashLoopBackOff under load or during recovery",
     "Lenient liveness, a startupProbe",
     "k8s-pod"
    ],
    [
     "Memory settings sized for the node",
     "OOMKilled, exit code 137",
     "Fit buffers to the container limit",
     "k8s-pod"
    ],
    [
     "Volume pinned to one zone",
     "Pod Pending after a node loss",
     "Capacity in that zone; never delete the PVC",
     "k8s-pod"
    ]
   ]
  ]
 },
 "runbooks": {
  "connections": {
   "signals": [
    "\"too many connections\" (MySQL) or \"remaining connection slots are reserved\" (PostgreSQL) in app logs",
    "Pool timeouts in the app: \"timed out waiting for a connection\"",
    "Connections above 80 percent of the limit",
    "Often right after a deploy, an autoscaling event or a failover"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "in",
     "phase": "confirm",
     "t": "Get in, and measure how close to the limit you are",
     "why": "You need a session of your own before you can fix anything. Both engines keep room for an admin.",
     "cmd": {
      "pg": "SELECT count(*) AS in_use,\n       current_setting('max_connections') AS max,\n       current_setting('superuser_reserved_connections') AS reserved_for_admins\nFROM pg_stat_activity WHERE backend_type = 'client backend';",
      "my": "SHOW VARIABLES LIKE 'max_connections';\nSHOW GLOBAL STATUS WHERE Variable_name IN\n  ('Threads_connected', 'Threads_running', 'Max_used_connections',\n   'Connection_errors_max_connections');",
      "mo": "db.serverStatus().connections   // current, available, totalCreated"
     },
     "look": "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.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "who",
     "phase": "cause",
     "t": "Group the connections by app and state",
     "why": "This one query decides the rest of the incident.",
     "cmd": {
      "pg": "SELECT usename, application_name, client_addr, state, count(*)\nFROM pg_stat_activity WHERE backend_type = 'client backend'\nGROUP BY 1, 2, 3, 4 ORDER BY 5 DESC LIMIT 20;",
      "my": "SELECT user, SUBSTRING_INDEX(host, ':', 1) AS client, command, count(*)\nFROM information_schema.processlist\nGROUP BY 1, 2, 3 ORDER BY 4 DESC LIMIT 20;",
      "mo": "db.getSiblingDB('admin').aggregate([\n  { $currentOp: { allUsers: true, idleConnections: true } },\n  { $group: { _id: { app: '$appName', client: '$client' }, n: { $sum: 1 } } },\n  { $sort: { n: -1 } }, { $limit: 20 }])"
     },
     "look": "Read the state column for the biggest group.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Most are active (running queries)",
       "go": "This is a slowness outage wearing a connection costume: queries got slower, so each holds its connection longer. Killing connections will not help. Go to CPU at 100% or Queries waiting on locks."
      },
      {
       "if": "Most are idle in transaction",
       "go": "idle-tx"
      },
      {
       "if": "Most are idle, from one app",
       "go": "source"
      },
      {
       "if": "A user or host you do not expect: a report, a script, an analyst",
       "go": "fence"
      }
     ]
    },
    {
     "key": "changed",
     "phase": "cause",
     "t": "Line it up with what changed",
     "why": "A deploy that doubled the pods, a new service, a failover that made every client reconnect at once.",
     "cmd": {
      "all": "# kubectl: did the replica count of an app change?\nkubectl get hpa -A\nkubectl rollout history deployment/<app> -n <namespace>"
     },
     "look": "Pods times pool size, before and after the change. If the new number is over the limit, you have the cause.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "idle-tx",
     "phase": "mitigate",
     "t": "End sessions stuck idle in a transaction",
     "why": "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.",
     "cmd": {
      "pg": "SELECT pid, usename, application_name,\n       now() - xact_start   AS transaction_age,\n       now() - state_change AS idle_for,\n       left(query, 80)      AS last_query\nFROM pg_stat_activity WHERE state = 'idle in transaction'\nORDER BY xact_start LIMIT 20;\n\n-- then end the ones idle for more than 5 minutes\nSELECT pid, pg_terminate_backend(pid)\nFROM pg_stat_activity\nWHERE state = 'idle in transaction'\n  AND now() - state_change > interval '5 minutes';",
      "my": "-- a transaction with no running query, and a Sleep thread, is idle in transaction\nSELECT t.trx_mysql_thread_id AS thread, t.trx_started,\n       TIMESTAMPDIFF(SECOND, t.trx_started, NOW()) AS age_s, p.user, p.host\nFROM information_schema.innodb_trx t\nJOIN information_schema.processlist p ON p.id = t.trx_mysql_thread_id\nWHERE p.command = 'Sleep' ORDER BY t.trx_started LIMIT 20;\n\n-- then: KILL <thread>; for each one you have read",
      "mo": "db.getSiblingDB('admin').aggregate([\n  { $currentOp: { allUsers: true, idleSessions: true } },\n  { $match: { transaction: { $exists: true } } },\n  { $project: { appName: 1, client: 1, 'transaction.timeOpenMicros': 1 } }])\n// MongoDB aborts transactions older than transactionLifetimeLimitSeconds (60 s) by itself"
     },
     "look": "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.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Nothing to undo. The app reconnects.",
     "timebox": "5 minutes"
    },
    {
     "key": "source",
     "phase": "mitigate",
     "t": "Fix it at the source: roll back, scale down, or shrink the pool",
     "why": "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.",
     "cmd": {
      "all": "# with the app team, the fastest of:\nkubectl rollout undo deployment/<app> -n <namespace>     # the deploy that caused it\nkubectl scale deployment/<app> --replicas=<before> -n <namespace>\n# or lower the pool size in the app's config and restart it"
     },
     "look": "Connections fall below 80 percent within a few minutes of the change.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Roll forward again once the pool math fits.",
     "timebox": "10 minutes"
    },
    {
     "key": "fence",
     "phase": "mitigate",
     "t": "Fence off the user that is flooding you",
     "why": "A script or report should never take the connections your customers need. Stop new ones, then end the existing ones.",
     "cmd": {
      "pg": "ALTER ROLE report_user CONNECTION LIMIT 0;   -- no new sessions for this role\nSELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'report_user';",
      "my": "ALTER USER 'report_user'@'%' ACCOUNT LOCK;\n-- then KILL each of its connections (see step 2 for the list)",
      "mo": "// no server-side per-user connection cap: stop the client, or\ndb.getSiblingDB('admin').revokeRolesFromUser('report_user', [{ role: 'read', db: 'app' }])"
     },
     "look": "Its connections drop to zero and stay there.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "PostgreSQL: ALTER ROLE report_user CONNECTION LIMIT -1;  MySQL: ALTER USER 'report_user'@'%' ACCOUNT UNLOCK;",
     "timebox": "5 minutes"
    },
    {
     "key": "raise",
     "phase": "mitigate",
     "t": "Last resort: raise the limit",
     "why": "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.",
     "cmd": {
      "pg": "-- PgBouncer in transaction mode in front of PostgreSQL is the usual answer.\n-- max_connections only changes with a restart:\nALTER SYSTEM SET max_connections = 400;   -- then a planned restart",
      "my": "-- takes effect at once, and survives a restart\nSET PERSIST max_connections = 800;\n-- ProxySQL multiplexes many app connections onto fewer backends",
      "mo": "// raise net.maxIncomingConnections in mongod.conf (restart), or\n// connect through mongos, which pools connections to the shards"
     },
     "look": "Do the memory math first. On PostgreSQL, a pooler in front (PgBouncer) is the real fix, and it can be added without a restart.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "Set the old value back (PostgreSQL: another restart)."
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm it held",
     "why": "Connections under 80 percent and the app's pool wait time back to normal, for 15 minutes.",
     "cmd": {
      "pg": "SELECT count(*) AS in_use,\n       current_setting('max_connections') AS max,\n       current_setting('superuser_reserved_connections') AS reserved_for_admins\nFROM pg_stat_activity WHERE backend_type = 'client backend';",
      "my": "SHOW VARIABLES LIKE 'max_connections';\nSHOW GLOBAL STATUS WHERE Variable_name IN\n  ('Threads_connected', 'Threads_running', 'Max_used_connections',\n   'Connection_errors_max_connections');",
      "mo": "db.serverStatus().connections   // current, available, totalCreated"
     },
     "look": "Also check the app's error rate, not just the database: that is what users feel.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Most connections are active: this is a slowness incident, bring in whoever owns the slow query.",
    "Anyone proposes restarting the database, or raising max_connections on PostgreSQL.",
    "It comes back after every fix: the app is leaking connections, and the app team has to be on the call."
   ],
   "call": {
    "when": [
     "The connections belong to one app, and the fix is its pool, its replica count or a rollback.",
     "Sessions sit idle in a transaction: that is a code path that never commits."
    ],
    "ask": [
     "How many instances do you run, and what is the pool size per instance? During a deploy, how many run at once?",
     "Do you open a transaction and then call another service, or wait on a user, before committing?",
     "Did anything change today: a deploy, autoscaling settings, a new service using the same database?",
     "Do workers, cron jobs or Lambdas open their own connections?"
    ],
    "suggest": [
     [
      "Shrink the pool",
      "Most apps need far fewer connections than they ask for. A pool of 5 to 10 per instance is plenty for many web apps."
     ],
     [
      "Put a pooler in front",
      "Many instances or serverless functions: PgBouncer or RDS Proxy for PostgreSQL, ProxySQL for MySQL."
     ],
     [
      "Keep transactions short",
      "Never hold a transaction open across a network call. Commit, then call."
     ],
     [
      "Set timeouts in the driver",
      "A connection timeout and a pool wait timeout, so a slow database fails fast instead of piling up."
     ]
    ]
   },
   "comms": "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>.",
   "postmortem": {
    "prevent": [
     "Write the pool math into the deploy checklist: instances times pool size, at peak and during a rolling deploy, stays under 70 percent of the limit.",
     "idle_in_transaction_session_timeout (PostgreSQL) or a short wait_timeout (MySQL) for app users.",
     "A pooler in front of PostgreSQL once there are more than a few app instances."
    ],
    "detect": [
     "Alert at 80 percent of max_connections, not at 100.",
     "Alert on any session idle in a transaction for more than 5 minutes.",
     "A per-app connection count on the dashboard, so the owner is obvious."
    ],
    "automate": [
     "An agent can end sessions idle in a transaction past a threshold, post what it ended, and page if they come back.",
     "A pre-deploy check that compares the new replica count times pool size with the database limit, and blocks the deploy if it does not fit."
    ]
   },
   "done": "Connections stay under 80 percent for 15 minutes, the app shows no connection errors, and you know which app and which change caused it.",
   "dont": [
    "Restart the database to clear connections. Every client reconnects at once into the same storm, and the evidence is gone.",
    "Raise max_connections on PostgreSQL in the middle of an incident. It needs a restart, and more processes make a slow server slower."
   ],
   "platform": {
    "rds": [
     {
      "t": "There is no shell on the host. Use Performance Insights (top SQL, waits, hosts and users) and the DatabaseConnections metric in CloudWatch."
     },
     {
      "t": "PostgreSQL: rds_superuser can end other users' sessions with pg_terminate_backend. MySQL: KILL is not allowed for other users; use the RDS procedures.",
      "cmd": "CALL mysql.rds_kill(<thread id>);         -- end the connection\nCALL mysql.rds_kill_query(<thread id>);   -- cancel the statement"
     },
     {
      "t": "max_connections comes from the parameter group, often a formula on instance memory. Changing it on PostgreSQL needs a reboot. RDS Proxy is the managed pooler, and it also hides failovers from the app."
     }
    ],
    "k8s": [
     {
      "t": "Pods times pool size is the math, and a HorizontalPodAutoscaler can double pods in a minute. Check it first.",
      "cmd": "kubectl get hpa -A\nkubectl get pods -l app=<app> -n <ns> --no-headers | wc -l"
     },
     {
      "t": "Get into the database through its pod. With an operator, use its tooling.",
      "cmd": "kubectl exec -it <db-pod> -n <ns> -- psql -U postgres\nkubectl cnpg psql <cluster> -n <ns>     # CloudNativePG plugin"
     },
     {
      "t": "Change max_connections in the operator's custom resource, not in the config file inside the pod: the operator puts its own version back."
     }
    ]
   }
  },
  "cpu": {
   "signals": [
    "Database CPU above 90 percent for several minutes",
    "Latency up across many endpoints at once",
    "Load average well above the number of cores",
    "Active sessions far above the number of cores"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "proc",
     "phase": "confirm",
     "t": "Make sure it is the database process",
     "why": "A backup, an agent or another service on the same host looks the same from the app.",
     "cmd": {
      "all": "top -b -n 1 -o %CPU | head -15      # which process is using the CPU\nuptime                                 # load average against the number of cores"
     },
     "look": "postgres, mysqld or mongod on top: carry on.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Something else is on top",
       "go": "Stop or move it. That is your fix."
      }
     ]
    },
    {
     "key": "now",
     "phase": "cause",
     "t": "See which query fills the active sessions",
     "why": "Active sessions compared with cores tells you how bad it is. Twice the core count means everything is queueing.",
     "cmd": {
      "pg": "SELECT left(query, 100) AS query, count(*) AS running,\n       max(now() - query_start) AS longest\nFROM pg_stat_activity\nWHERE state = 'active' AND pid <> pg_backend_pid()\nGROUP BY 1 ORDER BY 2 DESC LIMIT 15;",
      "my": "SELECT LEFT(info, 100) AS query, count(*) AS running, max(time) AS longest_s\nFROM information_schema.processlist\nWHERE command = 'Query' AND id <> CONNECTION_ID()\nGROUP BY 1 ORDER BY 2 DESC LIMIT 15;",
      "mo": "db.currentOp({ active: true }).inprog\n  .filter(o => o.op !== 'none')\n  .forEach(o => print(o.opid, o.secs_running + 's', o.ns, o.planSummary))"
     },
     "look": "One fingerprint with dozens of copies is the usual picture.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "One query, many copies",
       "go": "delta"
      },
      {
       "if": "One or two huge queries running for minutes",
       "go": "cancel"
      },
      {
       "if": "Nothing stands out",
       "go": "delta"
      }
     ]
    },
    {
     "key": "delta",
     "phase": "cause",
     "t": "Rank by time used in the last minute",
     "why": "Totals since the last reset hide what changed today. The difference over one minute shows what is burning CPU now.",
     "cmd": {
      "pg": "-- what used the CPU in the last minute, not since the last reset\nDROP TABLE IF EXISTS snap;\nCREATE TEMP TABLE snap AS\n  SELECT userid, dbid, queryid, calls, total_exec_time FROM pg_stat_statements;\nSELECT pg_sleep(60);\nSELECT s.calls - p.calls AS calls_last_min,\n       round((s.total_exec_time - p.total_exec_time)::numeric) AS ms_last_min,\n       left(s.query, 80) AS query\nFROM pg_stat_statements s JOIN snap p USING (userid, dbid, queryid)\nORDER BY 2 DESC LIMIT 10;",
      "my": "-- what used the time in the last minute\nDROP TEMPORARY TABLE IF EXISTS snap;\nCREATE TEMPORARY TABLE snap AS\n  SELECT schema_name, digest, count_star, sum_timer_wait\n  FROM performance_schema.events_statements_summary_by_digest;\nDO SLEEP(60);\nSELECT d.count_star - s.count_star AS calls_last_min,\n       ROUND((d.sum_timer_wait - s.sum_timer_wait) / 1e9) AS ms_last_min,\n       LEFT(d.digest_text, 80) AS query\nFROM performance_schema.events_statements_summary_by_digest d\nJOIN snap s ON s.digest = d.digest AND s.schema_name <=> d.schema_name\nORDER BY 2 DESC LIMIT 10;",
      "mo": "// if profiling is off, turn it on first (changes a setting):\n// db.setProfilingLevel(1, { slowms: 50 })\ndb.system.profile.find({}, { ns: 1, millis: 1, planSummary: 1, docsExamined: 1, nreturned: 1 })\n  .sort({ millis: -1 }).limit(10)"
     },
     "look": "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.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Its calls per minute jumped",
       "go": "A deploy, a retry loop or a traffic spike. Ask what changed, and get the app team on the call."
      },
      {
       "if": "Same calls, each one slower",
       "go": "plan"
      }
     ]
    },
    {
     "key": "plan",
     "phase": "cause",
     "t": "Read the plan of that query",
     "why": "A scan where there used to be an index lookup turns a cheap query into an expensive one.",
     "cmd": {
      "pg": "-- ANALYZE runs the query. For an UPDATE or DELETE, wrap it:\nBEGIN;\nEXPLAIN (ANALYZE, BUFFERS) <the query>;\nROLLBACK;",
      "my": "EXPLAIN ANALYZE <the query>;   -- runs it (MySQL 8.0.18 and later)\nEXPLAIN FORMAT=TREE <the query>;   -- the plan only",
      "mo": "db.orders.find({ customer_id: 42 }).explain('executionStats')\n// compare totalDocsExamined with nReturned"
     },
     "look": "Seq Scan, type ALL or COLLSCAN on a big table, or rows examined far above rows returned.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "The plan changed but an index exists",
       "go": "See One query suddenly got slow."
      },
      {
       "if": "There is no usable index",
       "go": "index"
      }
     ]
    },
    {
     "key": "rollback",
     "phase": "mitigate",
     "t": "If it started with a deploy: roll it back",
     "why": "The fastest and safest fix when the timing lines up. You can fix the query properly tomorrow.",
     "cmd": {
      "all": "kubectl rollout undo deployment/<app> -n <namespace>\n# or turn off the feature flag that shipped the new query"
     },
     "look": "CPU falls within a couple of minutes of the rollback finishing.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Roll forward once the query is fixed.",
     "timebox": "10 minutes"
    },
    {
     "key": "cancel",
     "phase": "mitigate",
     "t": "Cancel the runaway queries and turn off their source",
     "why": "Cancelling buys minutes. If the app retries, they come straight back, so stop the source too: the job, the endpoint, the flag.",
     "cmd": {
      "pg": "SELECT pg_cancel_backend(pid)      -- cancels the query, keeps the session\nFROM pg_stat_activity\nWHERE state = 'active' AND query LIKE '%<part of the query>%'\n  AND now() - query_start > interval '1 minute';",
      "my": "KILL QUERY <thread id>;   -- cancels the statement, keeps the connection",
      "mo": "db.killOp(<opid>)"
     },
     "look": "CPU drops. If it climbs back within a minute, the source is still running.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Nothing to undo. The query can be run again later.",
     "timebox": "5 minutes"
    },
    {
     "key": "index",
     "phase": "mitigate",
     "t": "Add the missing index, online",
     "why": "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.",
     "cmd": {
      "pg": "CREATE INDEX CONCURRENTLY orders_customer_idx ON orders (customer_id);\n-- if it fails it leaves an INVALID index: drop it and run it again",
      "my": "ALTER TABLE orders ADD INDEX orders_customer_idx (customer_id),\n  ALGORITHM = INPLACE, LOCK = NONE;",
      "mo": "db.orders.createIndex({ customer_id: 1 })   // holds an exclusive lock only at the start and the end"
     },
     "look": "The plan uses it, and the query's time per call falls.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "PostgreSQL: DROP INDEX CONCURRENTLY orders_customer_idx;  MySQL: ALTER TABLE orders DROP INDEX orders_customer_idx;  MongoDB: db.orders.dropIndex(\"orders_customer_idx\")"
    },
    {
     "key": "scale",
     "phase": "mitigate",
     "t": "Last resort: a bigger instance or more read replicas",
     "why": "Costs money and, on most managed services, a failover. Worth it only if the load is real and nothing above helps.",
     "cmd": {
      "all": "# RDS: modify the instance class (Multi-AZ: a failover of a minute or two)\naws rds modify-db-instance --db-instance-identifier <id> --db-instance-class <bigger> --apply-immediately"
     },
     "look": "Plan it with the app owner: they will see errors during the failover.",
     "risk": "high",
     "approval": true,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm it held",
     "why": "CPU near its normal level for 15 minutes and the query's time per call back to normal.",
     "cmd": {
      "pg": "-- what used the CPU in the last minute, not since the last reset\nDROP TABLE IF EXISTS snap;\nCREATE TEMP TABLE snap AS\n  SELECT userid, dbid, queryid, calls, total_exec_time FROM pg_stat_statements;\nSELECT pg_sleep(60);\nSELECT s.calls - p.calls AS calls_last_min,\n       round((s.total_exec_time - p.total_exec_time)::numeric) AS ms_last_min,\n       left(s.query, 80) AS query\nFROM pg_stat_statements s JOIN snap p USING (userid, dbid, queryid)\nORDER BY 2 DESC LIMIT 10;",
      "my": "-- what used the time in the last minute\nDROP TEMPORARY TABLE IF EXISTS snap;\nCREATE TEMPORARY TABLE snap AS\n  SELECT schema_name, digest, count_star, sum_timer_wait\n  FROM performance_schema.events_statements_summary_by_digest;\nDO SLEEP(60);\nSELECT d.count_star - s.count_star AS calls_last_min,\n       ROUND((d.sum_timer_wait - s.sum_timer_wait) / 1e9) AS ms_last_min,\n       LEFT(d.digest_text, 80) AS query\nFROM performance_schema.events_statements_summary_by_digest d\nJOIN snap s ON s.digest = d.digest AND s.schema_name <=> d.schema_name\nORDER BY 2 DESC LIMIT 10;",
      "mo": "// if profiling is off, turn it on first (changes a setting):\n// db.setProfilingLevel(1, { slowms: 50 })\ndb.system.profile.find({}, { ns: 1, millis: 1, planSummary: 1, docsExamined: 1, nreturned: 1 })\n  .sort({ millis: -1 }).limit(10)"
     },
     "look": "Keep watching through the next traffic peak.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "CPU stays above 90 percent for 15 minutes after you acted.",
    "The fix needs an index build on a large table, a rollback, or an instance resize.",
    "The top query belongs to a team that is not on the call yet."
   ],
   "call": {
    "when": [
     "One query fingerprint uses most of the CPU, and it comes from an application.",
     "Its calls per minute jumped: something in the app changed, or it is retrying in a loop."
    ],
    "ask": [
     "What does this query serve: a page users wait on, an API, a background job? How often does it run, and how often should it?",
     "Did a deploy or a feature flag change it today?",
     "Does the result change often, or could it be the same for seconds or minutes?",
     "Is it run once per item in a loop (the N+1 pattern)?",
     "Does it need to be exact and current, or could it read from a replica?"
    ],
    "suggest": [
     [
      "Add an index",
      "The query is right but scans. A composite index that matches its WHERE and ORDER BY usually fixes it for good."
     ],
     [
      "Rewrite the query",
      "It fetches more than it uses, has a function on the indexed column, or uses OFFSET paging on deep pages. Fetch less, keep the column bare, use keyset paging."
     ],
     [
      "Cache the result",
      "Read far more often than it changes, and a few seconds stale is fine: product pages, settings, counts. Redis in front, with a TTL."
     ],
     [
      "Batch it",
      "One query per item in a loop: fetch them all with one IN list or a join."
     ],
     [
      "Move it off the primary",
      "Reports and exports go to a replica or a warehouse, not the primary that serves customers."
     ],
     [
      "Rate limit or queue it",
      "A job or endpoint that can flood the database: cap its concurrency."
     ]
    ]
   },
   "comms": "Database <name>: CPU is saturated, so most requests are slow. Cause: <query> from <app>, <why>. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Every new query gets an EXPLAIN on production-sized data in code review.",
     "Reports and batch jobs run on replicas, with their own users and limits.",
     "Per-user statement_timeout so one runaway query cannot hold the CPU for an hour."
    ],
    "detect": [
     "Alert on CPU above 80 percent for 10 minutes.",
     "Track the top queries by total time every day, and alert when a new one enters the top five.",
     "Alert on calls per minute of the top fingerprints jumping."
    ],
    "automate": [
     "An agent can take the one-minute snapshot, name the top fingerprint, its owner app and its plan, and post it in the channel within a minute of the alert.",
     "Run the plans of new queries in CI against a copy of production statistics, and flag scans on big tables before they ship."
    ]
   },
   "done": "CPU is back to normal through a traffic peak, and you know which query, which change and which fix.",
   "dont": [
    "Buy a bigger instance before you know the query. A scan at twice the traffic eats the new CPU too.",
    "Keep cancelling the same query every few minutes. Stop its source."
   ],
   "platform": {
    "rds": [
     {
      "t": "Performance Insights is the fastest view: database load by wait and by SQL, against the vCPU line. Load above the vCPU line means queueing."
     },
     {
      "t": "On burstable classes (db.t3, db.t4g), CPUCreditBalance at zero throttles the instance. It looks like a CPU incident and is a billing setting.",
      "cmd": "aws cloudwatch get-metric-statistics --namespace AWS/RDS --metric-name CPUCreditBalance \\\n  --dimensions Name=DBInstanceIdentifier,Value=<id> --start-time <iso> --end-time <iso> --period 300 --statistics Minimum"
     },
     {
      "t": "Scaling the instance class on Multi-AZ fails over to the standby first: one to two minutes of errors. Plan it with the app owner."
     }
    ],
    "k8s": [
     {
      "t": "Check the CPU limit on the database container. A limit causes throttling (CFS) long before the node is busy: latency rises while CPU looks under 100 percent.",
      "cmd": "kubectl top pod <db-pod> -n <ns>\nkubectl get pod <db-pod> -n <ns> -o jsonpath='{.spec.containers[*].resources}'"
     },
     {
      "t": "Many teams run databases with a CPU request but no CPU limit for exactly this reason."
     }
    ]
   }
  },
  "disk": {
   "signals": [
    "Disk usage alert, or free space falling quickly",
    "\"No space left on device\", \"could not write to file\", errno 28 in the database log",
    "PostgreSQL PANIC on pg_wal: the server stops"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "rate",
     "phase": "confirm",
     "t": "How long until full, and which directory is growing",
     "why": "Time to full decides whether you investigate first or grow the volume first.",
     "cmd": {
      "all": "df -h                                   # run it twice, 10 minutes apart\ndu -sh /path/to/data/dir/* | sort -h | tail -15",
      "pg": "SHOW data_directory;\n-- in the shell: du -sh $PGDATA/base $PGDATA/pg_wal $PGDATA/pg_replslot $PGDATA/log",
      "my": "SELECT @@datadir, @@log_bin_basename, @@innodb_temp_data_file_path;",
      "mo": "const o = db.adminCommand({ getCmdLineOpts: 1 }).parsed;\nprint((o.storage && o.storage.dbPath) || '/data/db (the default)')"
     },
     "look": "Run df twice, ten minutes apart, and divide.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Less than an hour left, or already full",
       "go": "grow"
      },
      {
       "if": "More time than that",
       "go": "what"
      }
     ]
    },
    {
     "key": "grow",
     "phase": "mitigate",
     "t": "Grow the volume first",
     "why": "On cloud volumes this is online and takes minutes. It buys the time to find the cause calmly.",
     "cmd": {
      "all": "# grow the volume: on AWS, modify the EBS volume, then\nsudo growpart /dev/nvme1n1 1   # if it has a partition\nsudo xfs_growfs /data          # or: sudo resize2fs /dev/nvme1n1p1"
     },
     "look": "Free space jumps. On RDS: modify the allocated storage; you cannot change it again for six hours, so add enough.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Volumes cannot shrink. That is fine.",
     "timebox": "15 minutes"
    },
    {
     "key": "what",
     "phase": "cause",
     "t": "Find what is growing: log, data, temp or server logs",
     "why": "Each has a different fix. WAL, binlogs and server logs grow fastest.",
     "cmd": {
      "pg": "SELECT slot_name, slot_type, active,\n       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS wal_kept\nFROM pg_replication_slots ORDER BY restart_lsn;\n-- WAL archiving failing also keeps WAL\nSELECT archived_count, failed_count, last_failed_wal, last_failed_time\nFROM pg_stat_archiver;",
      "my": "SHOW BINARY LOGS;\nSELECT @@binlog_expire_logs_seconds / 86400 AS days_kept;",
      "mo": "rs.printReplicationInfo()   // the oplog has a fixed size, so it is rarely the cause\ndb.adminCommand({ getCmdLineOpts: 1 }).parsed.systemLog   // where the mongod log lives; unrotated logs grow"
     },
     "look": "Read the result against the directory sizes from step 1.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "An inactive replication slot holds many GB",
       "go": "slot"
      },
      {
       "if": "WAL archiving is failing",
       "go": "Fix archive_command or its destination. WAL is then removed by itself."
      },
      {
       "if": "Binlogs kept for weeks",
       "go": "purge"
      },
      {
       "if": "Temporary files from one query",
       "go": "temp"
      },
      {
       "if": "Server log files",
       "go": "logs"
      },
      {
       "if": "Table files",
       "go": "See Tables grow but rows do not, or real growth: plan capacity."
      }
     ]
    },
    {
     "key": "logs",
     "phase": "cause",
     "t": "Check whether someone left verbose logging on",
     "why": "Statement logging left on after a debug session can write gigabytes an hour.",
     "cmd": {
      "pg": "SELECT name, setting FROM pg_settings\nWHERE name IN ('log_min_duration_statement', 'log_statement', 'log_connections', 'log_disconnections');",
      "my": "SHOW VARIABLES WHERE Variable_name IN ('general_log', 'slow_query_log', 'long_query_time', 'log_output');",
      "mo": "db.getProfilingStatus()\ndb.adminCommand({ getParameter: 1, logLevel: 1 })"
     },
     "look": "log_min_duration_statement = 0, log_statement = all, or the MySQL general log ON: turn it off and delete old log files. Safe.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "slot",
     "phase": "mitigate",
     "t": "Drop the replication slot nobody reads",
     "why": "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.",
     "cmd": {
      "pg": "-- only after you confirm nothing will use this slot again:\nSELECT pg_drop_replication_slot('old_slot');   -- its reader needs a full resync\n-- fix archive_command if step 2 showed failures; WAL is then removed by itself"
     },
     "look": "pg_wal shrinks at the next checkpoint.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "None. The consumer has to be rebuilt from a fresh snapshot."
    },
    {
     "key": "purge",
     "phase": "mitigate",
     "t": "Purge binlogs every replica has already read",
     "why": "Check every replica first: purging a binlog a replica still needs breaks that replica.",
     "cmd": {
      "my": "-- check every replica has read past this point first (SHOW REPLICA STATUS)\nPURGE BINARY LOGS BEFORE NOW() - INTERVAL 3 DAY;\nSET PERSIST binlog_expire_logs_seconds = 604800;   -- 7 days"
     },
     "look": "Free space rises at once.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "None. Keep a few days of binlogs for point-in-time recovery."
    },
    {
     "key": "temp",
     "phase": "mitigate",
     "t": "Cancel the query writing huge temporary files",
     "why": "A sort or hash spilling tens of GB is usually a bad query, not a real need.",
     "cmd": {
      "pg": "SELECT datname, temp_files, pg_size_pretty(temp_bytes) AS temp\nFROM pg_stat_database ORDER BY temp_bytes DESC;\nSELECT pid, now() - query_start AS running, left(query, 80)\nFROM pg_stat_activity WHERE state = 'active' ORDER BY query_start LIMIT 5;",
      "my": "-- the session temporary tablespace and ibtmp1 (ibtmp1 only shrinks at restart)\nSELECT * FROM information_schema.innodb_session_temp_tablespaces;",
      "mo": "// aggregations with allowDiskUse spill under the dbPath, in _tmp\ndb.currentOp({ active: true, secs_running: { $gte: 60 } })"
     },
     "look": "Cancel it (see CPU at 100%, step 6), then look at its plan.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm free space is stable",
     "why": "Flat or rising for 30 minutes, with the cause gone, not just pushed back.",
     "cmd": {
      "all": "df -h                                   # run it twice, 10 minutes apart\ndu -sh /path/to/data/dir/* | sort -h | tail -15"
     },
     "look": "Estimate when it will fill again at normal growth, and put that date in the ticket.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Less than 30 minutes to full and you cannot grow the volume.",
    "The server has already stopped (PostgreSQL PANIC on WAL): this is now a recovery, bring a second DBA.",
    "Dropping a slot or purging logs would break a replica or a CDC pipeline someone else owns."
   ],
   "call": {
    "when": [
     "A CDC connector, replica or data pipeline owned by another team holds a slot or old binlogs.",
     "An app or job is writing much more data than planned."
    ],
    "ask": [
     "Is your connector or replica still running? When did it last read? Can it be rebuilt from a snapshot if we drop its slot?",
     "What is writing this data, how much per day, and how long must it be kept?",
     "Can old rows be deleted or moved out, and on what schedule?"
    ],
    "suggest": [
     [
      "Monitor the consumer",
      "A CDC connector that stops should page its owners, before the database disk fills."
     ],
     [
      "Partition by time",
      "Data with a retention period: drop old partitions instead of running big deletes."
     ],
     [
      "Move cold data out",
      "Archive old rows to object storage or a warehouse."
     ],
     [
      "Set a slot size limit",
      "PostgreSQL max_slot_wal_keep_size caps how much WAL a dead slot can keep."
     ]
    ]
   },
   "comms": "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>.",
   "postmortem": {
    "prevent": [
     "max_slot_wal_keep_size on PostgreSQL, so a dead slot cannot fill the disk.",
     "binlog_expire_logs_seconds set to what point-in-time recovery needs, not 30 days by default.",
     "Log rotation with a size cap, and verbose logging turned off with a reminder after debugging."
    ],
    "detect": [
     "Alert on time to full (growth rate), not only on percent used.",
     "Alert when a replication slot is inactive or holds more than a few GB.",
     "Alert on WAL archiving failures."
    ],
    "automate": [
     "An agent can compute time to full every few minutes and grow a cloud volume by a fixed step when it drops under a threshold, with a human notified.",
     "A weekly report of the largest tables and their growth, with a projected full date."
    ]
   },
   "done": "Free space is stable, the cause is fixed, and the projected full date is months away.",
   "dont": [
    "rm files in pg_wal, binlogs, redo logs or MongoDB data files. The database will not start, or a replica is lost.",
    "Drop a replication slot before you know who reads it."
   ],
   "platform": {
    "rds": [
     {
      "t": "Watch FreeStorageSpace. At zero the instance goes to storage-full and stops writes. Turn on storage autoscaling with a maximum; after any storage change you must wait six hours for the next one."
     },
     {
      "t": "PostgreSQL: TransactionLogsDiskUsage and OldestReplicationSlotLag show WAL kept by slots. MySQL: binlog retention is a procedure, not a variable.",
      "cmd": "CALL mysql.rds_show_configuration;\nCALL mysql.rds_set_configuration('binlog retention hours', 24);"
     },
     {
      "t": "Aurora data storage grows by itself, but local storage for temp files does not: watch FreeLocalStorage. A big sort can fill it and fail queries."
     }
    ],
    "k8s": [
     {
      "t": "The volume is a PersistentVolumeClaim. Grow it through the operator's resource, or patch the PVC if the storage class allows expansion.",
      "cmd": "kubectl get pvc -n <ns>\nkubectl get storageclass <class> -o jsonpath='{.allowVolumeExpansion}'\nkubectl patch pvc <pvc> -n <ns> -p '{\"spec\":{\"resources\":{\"requests\":{\"storage\":\"200Gi\"}}}}'"
     },
     {
      "t": "Never delete a PVC to free space. With most storage classes the reclaim policy deletes the data with it."
     }
    ]
   }
  },
  "lag": {
   "signals": [
    "Replica lag alert, in seconds or bytes",
    "Users see old data after saving: reads go to a replica",
    "A failover would lose more than you accept"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "far",
     "phase": "confirm",
     "t": "How far behind, and which replicas",
     "why": "Seconds tell you how stale reads are. Bytes tell you what a failover now would lose or have to replay.",
     "cmd": {
      "pg": "-- on the primary\nSELECT application_name, client_addr, state,\n       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS behind,\n       write_lag, flush_lag, replay_lag\nFROM pg_stat_replication;",
      "my": "SHOW REPLICA STATUS\\G\n-- Seconds_Behind_Source, Replica_IO_Running, Replica_SQL_Running,\n-- Last_IO_Error, Last_SQL_Error",
      "mo": "rs.printSecondaryReplicationInfo()"
     },
     "look": "One replica behind: a problem on that replica. All of them: something on the primary, usually one huge write.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Replication stopped with an error",
       "go": "error"
      },
      {
       "if": "Users read from the lagging replica",
       "go": "rotate"
      }
     ]
    },
    {
     "key": "rotate",
     "phase": "mitigate",
     "t": "Take the lagging replica out of the read pool",
     "why": "This fixes what users see in a minute, without touching replication.",
     "cmd": {
      "my": "KILL QUERY <thread id>;   -- the long query on the replica\n-- remove it from the ProxySQL reader hostgroup",
      "mo": "// readPreference for that app: primaryPreferred, until the secondary catches up"
     },
     "look": "Stale-read complaints stop. Make sure the others can carry the reads.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Put it back once lag is under your threshold.",
     "timebox": "5 minutes"
    },
    {
     "key": "recv",
     "phase": "cause",
     "t": "Receiving or applying?",
     "why": "The fix is in a different place for each.",
     "cmd": {
      "pg": "-- on the replica\nSELECT pg_last_wal_receive_lsn() AS received,\n       pg_last_wal_replay_lsn()  AS applied,\n       pg_is_wal_replay_paused()  AS paused,\n       now() - pg_last_xact_replay_timestamp() AS behind;\nSELECT status, sender_host, last_msg_receipt_time FROM pg_stat_wal_receiver;",
      "my": "SHOW REPLICA STATUS\\G\n-- Retrieved_Gtid_Set (received) against Executed_Gtid_Set (applied)\nSELECT * FROM performance_schema.replication_applier_status_by_worker\\G",
      "mo": "rs.status().members.map(m => [m.name, m.stateStr, m.optimeDate, m.syncSourceHost])"
     },
     "look": "Compare received with applied.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Received is far ahead of applied",
       "go": "apply"
      },
      {
       "if": "Received itself is far behind the primary",
       "go": "Network, or the primary is saturated: check the primary's disk and CPU."
      }
     ]
    },
    {
     "key": "apply",
     "phase": "cause",
     "t": "What is slowing the apply",
     "why": "One giant transaction on the primary, or a long query on the replica, explains most of it.",
     "cmd": {
      "pg": "-- on the replica: queries that delay or conflict with replay\nSELECT pid, now() - query_start AS running, left(query, 80)\nFROM pg_stat_activity WHERE state = 'active' ORDER BY query_start LIMIT 10;\nSELECT * FROM pg_stat_database_conflicts WHERE datname = current_database();\nSHOW max_standby_streaming_delay;",
      "my": "SHOW VARIABLES LIKE 'replica_parallel%';\nSHOW PROCESSLIST;   -- the applier threads and their state",
      "mo": "db.serverStatus().metrics.repl.buffer\n// and CPU and disk on the secondary: an overloaded secondary falls behind"
     },
     "look": "A long report on a PostgreSQL replica can hold replay back. A big DELETE on the primary replays as one unit.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "A big batch job on the primary",
       "go": "job"
      },
      {
       "if": "A long query on the replica",
       "go": "Cancel it: pg_cancel_backend(<pid>) or KILL QUERY <id>."
      }
     ]
    },
    {
     "key": "job",
     "phase": "mitigate",
     "t": "Pause the big write job on the primary",
     "why": "One DELETE of 50 million rows becomes hours of lag. Stopping it, and running it in chunks later, ends the lag growth at once.",
     "cmd": {
      "all": "# with the job's owner: stop the job. Then, for later:\n# delete in chunks of a few thousand rows, with a short pause between chunks"
     },
     "look": "Lag stops growing, then falls.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Restart the job in chunks.",
     "timebox": "10 minutes"
    },
    {
     "key": "error",
     "phase": "cause",
     "t": "If replication stopped: read the error",
     "why": "Do not skip transactions to get it going. The replica would then be wrong in a way nobody can see.",
     "cmd": {
      "pg": "-- in the replica's log: the error, often a missing WAL file\n-- (the primary removed it before the replica read it)",
      "my": "SHOW REPLICA STATUS\\G   -- Last_SQL_Error, Last_IO_Error\nSELECT * FROM performance_schema.replication_applier_status_by_worker\\G",
      "mo": "rs.status()   // look for a member in RECOVERING or with an error message"
     },
     "look": "A WAL or binlog the primary no longer has means the replica cannot catch up: rebuild it.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "The needed log is gone",
       "go": "rebuild"
      }
     ]
    },
    {
     "key": "rebuild",
     "phase": "mitigate",
     "t": "Rebuild the replica",
     "why": "Sometimes a fresh copy is faster than waiting. Out of the read pool while it builds.",
     "cmd": {
      "pg": "pg_basebackup -h <primary> -D /new/data/dir -X stream -P -R",
      "my": "CLONE INSTANCE FROM 'clone_user'@'primary':3306 IDENTIFIED BY '...';   -- the clone plugin",
      "mo": "// stop the secondary, empty its dbPath, start it: it runs an initial sync"
     },
     "look": "Time it. That number belongs in your recovery plan.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm it caught up",
     "why": "Lag under your threshold for 15 minutes, then back into the read pool.",
     "cmd": {
      "pg": "-- on the primary\nSELECT application_name, client_addr, state,\n       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS behind,\n       write_lag, flush_lag, replay_lag\nFROM pg_stat_replication;",
      "my": "SHOW REPLICA STATUS\\G\n-- Seconds_Behind_Source, Replica_IO_Running, Replica_SQL_Running,\n-- Last_IO_Error, Last_SQL_Error",
      "mo": "rs.printSecondaryReplicationInfo()"
     },
     "look": "Also confirm your failover target is current again.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "The primary is unhealthy at the same time: a failover decision now includes how much data you accept losing. That is the service owner's call, not yours alone.",
    "Replication broke with an error you do not recognise.",
    "Lag keeps growing after you paused the obvious writer."
   ],
   "call": {
    "when": [
     "A batch job, migration or backfill is the writer.",
     "An app reads its own writes from a replica and users see stale data."
    ],
    "ask": [
     "What is this job doing, how many rows, and does it need to finish now?",
     "Which reads go to replicas? Which of them must see a write the user just made?",
     "How stale can each read be: a second, a minute?"
    ],
    "suggest": [
     [
      "Chunk big writes",
      "Batches of a few thousand rows with a pause, so replicas keep up."
     ],
     [
      "Read your own writes from the primary",
      "For a few seconds after a user writes, send that user's reads to the primary."
     ],
     [
      "Lag-aware routing",
      "The proxy or driver stops sending reads to a replica that is more than N seconds behind."
     ],
     [
      "Run heavy jobs off-peak",
      "Backfills and purges at night, with a throttle."
     ]
    ]
   },
   "comms": "Database <name>: replica <r> is <n> behind, so <reads may be stale / failover protection is reduced>. Cause: <what>. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Big writes in chunks, enforced in code review for backfills and purges.",
     "Parallel apply on MySQL replicas (replica_parallel_workers).",
     "Reports run on a replica that is not the failover target."
    ],
    "detect": [
     "Alert on lag in seconds and bytes, per replica.",
     "Alert on replication stopped, separately from lag.",
     "Show lag next to the write rate of the primary on one dashboard."
    ],
    "automate": [
     "An agent can take a replica out of the read pool when lag passes a threshold and put it back when it recovers.",
     "A guard that pauses a batch job when replica lag passes a threshold."
    ]
   },
   "done": "Every replica is under the lag threshold, back in the read pool, and the failover target is current.",
   "dont": [
    "Fail over to a lagging replica without the owner agreeing to lose what it has not received.",
    "Skip a failed transaction on MySQL (sql_replica_skip_counter) to make the error go away."
   ],
   "platform": {
    "rds": [
     {
      "t": "ReplicaLag in CloudWatch for RDS read replicas, AuroraReplicaLag for Aurora. Aurora replicas share storage, so their lag is usually milliseconds: seconds of lag on Aurora means the replica is overloaded or restarting."
     },
     {
      "t": "MySQL on RDS: replication errors are skipped with a procedure. Do not use it to make an error go away; rebuild the replica instead.",
      "cmd": "CALL mysql.rds_skip_repl_error;   -- the same risk as sql_replica_skip_counter"
     }
    ],
    "k8s": [
     {
      "t": "With an operator, check its view of the replicas, then the database's.",
      "cmd": "kubectl cnpg status <cluster> -n <ns>          # CloudNativePG\nkubectl exec <pod> -n <ns> -- patronictl list   # Zalando and Crunchy run Patroni"
     },
     {
      "t": "A replica on a node with a slow or shared disk lags. Check which node and which storage class it landed on.",
      "cmd": "kubectl get pod -o wide -n <ns>"
     }
    ]
   }
  },
  "locks": {
   "signals": [
    "Requests hang, then fail with lock wait timeout or deadlock errors",
    "Low CPU but high latency: things are waiting, not working",
    "Often right after a migration starts"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "waits",
     "phase": "confirm",
     "t": "Confirm sessions are waiting on locks",
     "why": "Lock waits look like a slow database with low CPU.",
     "cmd": {
      "pg": "SELECT wait_event_type, wait_event, count(*)\nFROM pg_stat_activity WHERE state = 'active'\nGROUP BY 1, 2 ORDER BY 3 DESC;",
      "my": "SELECT count(*) AS waiting FROM information_schema.innodb_trx\nWHERE trx_state = 'LOCK WAIT';\nSELECT state, count(*) FROM information_schema.processlist GROUP BY 1 ORDER BY 2 DESC;",
      "mo": "db.currentOp({ waitingForLock: true }).inprog.length"
     },
     "look": "Most active sessions waiting on Lock, or in LOCK WAIT or \"Waiting for table metadata lock\".",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "head",
     "phase": "cause",
     "t": "Find the blocker at the front",
     "why": "A session that blocks others but is not blocked itself.",
     "cmd": {
      "pg": "SELECT pid, usename, application_name, state,\n       now() - xact_start AS transaction_age, left(query, 80) AS query\nFROM pg_stat_activity\nWHERE pid IN (SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity)\n  AND cardinality(pg_blocking_pids(pid)) = 0;",
      "my": "SELECT * FROM sys.innodb_lock_waits\\G         -- row locks: blocking_pid, blocking_query\nSELECT * FROM sys.schema_table_lock_waits\\G   -- metadata locks, such as an ALTER",
      "mo": "db.getSiblingDB('admin').aggregate([\n  { $currentOp: { allUsers: true, idleSessions: true } },\n  { $match: { transaction: { $exists: true } } },\n  { $sort: { 'transaction.timeOpenMicros': -1 } }, { $limit: 5 }])"
     },
     "look": "Note what it is and what it is doing.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "An ALTER, CREATE INDEX or other DDL is waiting",
       "go": "ddl"
      },
      {
       "if": "The blocker is idle in a transaction",
       "go": "kill"
      },
      {
       "if": "The blocker is an active long job",
       "go": "job"
      }
     ]
    },
    {
     "key": "ddl",
     "phase": "mitigate",
     "t": "Cancel the migration first",
     "why": "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.",
     "cmd": {
      "pg": "SELECT pid, pg_cancel_backend(pid) FROM pg_stat_activity\nWHERE query ~* '^\\s*(alter|create index|drop|truncate)' AND wait_event_type = 'Lock';",
      "my": "-- find the ALTER waiting for its metadata lock, then\nKILL QUERY <thread id of the ALTER>;",
      "mo": "db.killOp(<opid of the index build or collMod>)"
     },
     "look": "The queue drains within seconds.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Rerun the migration with a lock timeout (step 6).",
     "timebox": "2 minutes"
    },
    {
     "key": "kill",
     "phase": "mitigate",
     "t": "End the blocker that is idle in a transaction",
     "why": "It holds locks and does nothing. Ending it rolls its transaction back.",
     "cmd": {
      "pg": "SELECT pg_cancel_backend(<pid>);      -- stops the running query\nSELECT pg_terminate_backend(<pid>);   -- ends the session and rolls back",
      "my": "KILL QUERY <blocking_pid>;   -- or KILL <blocking_pid>; to end the connection\n-- sys.innodb_lock_waits also prints the statements: sql_kill_blocking_connection",
      "mo": "db.killOp(<opid>)"
     },
     "look": "The queue drains. A big transaction takes time to roll back: do not end it twice.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "None. The app retries the work.",
     "timebox": "5 minutes"
    },
    {
     "key": "job",
     "phase": "mitigate",
     "t": "Stop the long job, with its owner",
     "why": "An active batch job might be halfway through something important. Ask before you kill it, but do not wait long.",
     "cmd": {
      "pg": "SELECT pg_cancel_backend(<pid>);      -- stops the running query\nSELECT pg_terminate_backend(<pid>);   -- ends the session and rolls back",
      "my": "KILL QUERY <blocking_pid>;   -- or KILL <blocking_pid>; to end the connection\n-- sys.innodb_lock_waits also prints the statements: sql_kill_blocking_connection",
      "mo": "db.killOp(<opid>)"
     },
     "look": "Cancel it, then plan to rerun it in smaller transactions.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "The job reruns from its start or its last checkpoint.",
     "timebox": "10 minutes"
    },
    {
     "key": "retry",
     "phase": "mitigate",
     "t": "Rerun the migration safely",
     "why": "A short lock timeout means it gives up quickly instead of blocking everyone. Retry it in a loop until it gets the lock.",
     "cmd": {
      "pg": "SET lock_timeout = '3s';\nALTER TABLE orders ADD COLUMN note text;   -- retry until it gets the lock",
      "my": "SET SESSION lock_wait_timeout = 5;\nALTER TABLE orders ADD COLUMN note TEXT, ALGORITHM = INSTANT;",
      "mo": "// MongoDB schema changes are index builds and collMod; check db.currentOp() for them"
     },
     "look": "It finishes in a moment or fails fast, and traffic is never stuck behind it.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "hot",
     "phase": "cause",
     "t": "If waits keep coming back: find the hot row",
     "why": "One counter or one stock row updated by everyone queues by design.",
     "cmd": {
      "pg": "SELECT relation::regclass, mode, granted, count(*)\nFROM pg_locks WHERE relation IS NOT NULL\nGROUP BY 1, 2, 3 ORDER BY 4 DESC LIMIT 10;",
      "my": "SELECT object_schema, object_name, lock_type, lock_mode, count(*)\nFROM performance_schema.data_locks GROUP BY 1, 2, 3, 4 ORDER BY 5 DESC LIMIT 10;",
      "mo": "db.serverStatus().locks"
     },
     "look": "That is a design problem, not an on-call one: get the app team on the call.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm the queue is gone",
     "why": "No session waiting on a lock for more than a few seconds, for 15 minutes.",
     "cmd": {
      "pg": "SELECT wait_event_type, wait_event, count(*)\nFROM pg_stat_activity WHERE state = 'active'\nGROUP BY 1, 2 ORDER BY 3 DESC;",
      "my": "SELECT count(*) AS waiting FROM information_schema.innodb_trx\nWHERE trx_state = 'LOCK WAIT';\nSELECT state, count(*) FROM information_schema.processlist GROUP BY 1 ORDER BY 2 DESC;",
      "mo": "db.currentOp({ waitingForLock: true }).inprog.length"
     },
     "look": "Check the app's error rate too.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "The blocker is a job you do not own and cannot reach its owner.",
    "Deadlocks every minute: a code path needs changing.",
    "Waits return within minutes of every fix."
   ],
   "call": {
    "when": [
     "A migration caused it.",
     "The same hot rows keep blocking.",
     "An app leaves transactions open."
    ],
    "ask": [
     "How do you run migrations: with a lock timeout and retries, at what time of day?",
     "Which rows does everyone update at once: a counter, a balance, a stock level?",
     "Do you call other services or wait on anything while a transaction is open?",
     "Do two code paths update the same tables in a different order?"
    ],
    "suggest": [
     [
      "Lock timeout in every migration",
      "lock_timeout (PostgreSQL) or lock_wait_timeout (MySQL) of a few seconds, with a retry loop, and an online schema change tool for big tables."
     ],
     [
      "Split the hot row",
      "Spread a counter over N rows and sum them, or append events and aggregate."
     ],
     [
      "Shorter transactions",
      "Do the slow work first, then open the transaction, write, commit."
     ],
     [
      "Same lock order everywhere",
      "Update rows in the same order (by primary key) in every code path to end deadlocks."
     ]
    ]
   },
   "comms": "Database <name>: queries are waiting on locks, so <feature> is timing out. Cause: <migration / transaction> from <app>. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Every migration runs with a lock timeout and retries, reviewed like code.",
     "idle_in_transaction_session_timeout for app users.",
     "statement_timeout for app users, below the app's own request timeout."
    ],
    "detect": [
     "Alert on the number of sessions waiting on locks, and on the age of the oldest transaction.",
     "Log lock waits longer than a second (log_lock_waits in PostgreSQL)."
    ],
    "automate": [
     "An agent can find the head blocker within seconds of the alert and post who it is, what it holds and how long it has run.",
     "Auto-cancel a DDL that has waited for a lock longer than a few seconds while others queue behind it."
    ]
   },
   "done": "No lock waits for 15 minutes, and the migration or transaction that caused it has a safer plan.",
   "dont": [
    "Raise lock timeouts to make the errors go away. The waits only get longer.",
    "Kill the waiting sessions one by one. End the blocker."
   ],
   "platform": {
    "rds": [
     {
      "t": "Performance Insights shows lock waits as Lock:transactionid, Lock:tuple (PostgreSQL) or synch/... and innodb lock waits (MySQL), with the SQL behind them."
     },
     {
      "t": "MySQL on RDS: end the blocker with the procedures, not KILL.",
      "cmd": "CALL mysql.rds_kill(<blocking thread id>);"
     }
    ],
    "k8s": [
     {
      "t": "Migrations often run as a Job or an init container at deploy time. Find it and stop it before it retries.",
      "cmd": "kubectl get jobs -n <ns>\nkubectl delete job <migration-job> -n <ns>"
     }
    ]
   }
  },
  "plan": {
   "signals": [
    "One endpoint or job got slow while everything else is fine",
    "One query's average time jumped, with no code change",
    "Often after a big data load, a delete, a restore or a major upgrade"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "one",
     "phase": "confirm",
     "t": "Confirm it is one query, and when it changed",
     "why": "You want the fingerprint and the time its average jumped.",
     "cmd": {
      "pg": "-- needs the pg_stat_statements extension\nSELECT calls, round(total_exec_time) AS total_ms,\n       round(mean_exec_time::numeric, 2) AS mean_ms,\n       rows, left(query, 80) AS query\nFROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;",
      "my": "SELECT query, exec_count, total_latency, avg_latency,\n       rows_examined_avg, rows_sent_avg\nFROM sys.statement_analysis LIMIT 10;   -- sorted by total latency"
     },
     "look": "Compare its mean time with yesterday in your monitoring.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "plan",
     "phase": "cause",
     "t": "Get the real plan with real values",
     "why": "Real timings and real row counts, not only the estimate.",
     "cmd": {
      "pg": "BEGIN;\nEXPLAIN (ANALYZE, BUFFERS) <the slow query, with real values>;\nROLLBACK;",
      "my": "EXPLAIN ANALYZE <the slow query>;",
      "mo": "db.orders.find({ customer_id: 42 }).sort({ created_at: -1 }).explain('executionStats')"
     },
     "look": "Compare the estimated rows with the actual rows at each step.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Estimates off by ten times or more",
       "go": "stats"
      },
      {
       "if": "Estimates fine, but it scans",
       "go": "index"
      },
      {
       "if": "It is fast with some values and slow with others",
       "go": "param"
      }
     ]
    },
    {
     "key": "stats",
     "phase": "mitigate",
     "t": "Refresh the statistics",
     "why": "A big load or delete changed the table under the planner. This is cheap and takes seconds to minutes.",
     "cmd": {
      "pg": "ANALYZE orders;",
      "my": "ANALYZE TABLE orders;\n-- for skewed columns, a histogram:\nANALYZE TABLE orders UPDATE HISTOGRAM ON customer_id WITH 64 BUCKETS;",
      "mo": "db.orders.getPlanCache().clear()   // forgets cached plans; the next run plans again"
     },
     "look": "Run the plan again. Back to the old plan: done.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Nothing to undo.",
     "timebox": "5 minutes"
    },
    {
     "key": "index",
     "phase": "cause",
     "t": "Check the index exists and is valid",
     "why": "A failed concurrent build leaves an index that exists but is never used.",
     "cmd": {
      "pg": "SELECT indexrelid::regclass AS index, indisvalid, indisready\nFROM pg_index WHERE indrelid = 'orders'::regclass;",
      "my": "SHOW INDEX FROM orders;\nSELECT * FROM sys.schema_unused_indexes WHERE object_name = 'orders';",
      "mo": "db.orders.getIndexes()"
     },
     "look": "Invalid: drop and rebuild it concurrently. Missing: see CPU at 100%, step 7.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "param",
     "phase": "mitigate",
     "t": "Handle the value that breaks the plan",
     "why": "One customer with a million rows, or a prepared statement that switched to a generic plan.",
     "cmd": {
      "pg": "-- see the generic plan a prepared statement may switch to (PostgreSQL 16 and later)\nEXPLAIN (GENERIC_PLAN) SELECT * FROM orders WHERE customer_id = $1;\n-- for one role, always plan with the real value:\nALTER ROLE app_user SET plan_cache_mode = force_custom_plan;",
      "my": "-- a hint, in the query, for the big case\nSELECT /*+ INDEX(orders orders_customer_created_idx) */ * FROM orders WHERE customer_id = 42;",
      "mo": "db.orders.find({ customer_id: 42 }).hint({ customer_id: 1, created_at: -1 })"
     },
     "look": "Pin the plan only as a bandage, and write down why.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "PostgreSQL: ALTER ROLE app_user RESET plan_cache_mode;"
    },
    {
     "key": "deploy",
     "phase": "mitigate",
     "t": "If the query text changed in a deploy: roll back",
     "why": "A new filter or a new ORDER BY is a new plan.",
     "cmd": {
      "all": "kubectl rollout undo deployment/<app> -n <namespace>"
     },
     "look": "The old query and its old plan come back.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm the plan stayed fixed",
     "why": "The query's average time back to normal for an hour, through some traffic.",
     "cmd": {
      "pg": "-- needs the pg_stat_statements extension\nSELECT calls, round(total_exec_time) AS total_ms,\n       round(mean_exec_time::numeric, 2) AS mean_ms,\n       rows, left(query, 80) AS query\nFROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;",
      "my": "SELECT query, exec_count, total_latency, avg_latency,\n       rows_examined_avg, rows_sent_avg\nFROM sys.statement_analysis LIMIT 10;   -- sorted by total latency"
     },
     "look": "Plans can flip back: check again tomorrow.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "ANALYZE did not fix it and the query serves a critical path.",
    "The fix needs a new index on a large table, or a hint in application code."
   ],
   "call": {
    "when": [
     "The slow query is new or changed in a deploy.",
     "It is slow only for some values: big customers, old accounts."
    ],
    "ask": [
     "What does this query do for the user? Which values are slow?",
     "Did the query, its filters or its sort change?",
     "How many rows do the biggest customers have compared with a typical one?",
     "Does it need every column it selects, and every row it fetches?"
    ],
    "suggest": [
     [
      "A composite index that matches the query",
      "Equality columns first, then the range or sort column."
     ],
     [
      "Rewrite for the big case",
      "Keyset paging instead of OFFSET, a narrower SELECT, or a separate path for very large tenants."
     ],
     [
      "Cache it",
      "An expensive result that is read often and changes rarely."
     ],
     [
      "Precompute it",
      "A summary table or materialized view refreshed on a schedule, for dashboards and counts."
     ]
    ]
   },
   "comms": "<feature> is slow because one query changed its plan. We are <action>. Other features are not affected. Next update <time>.",
   "postmortem": {
    "prevent": [
     "ANALYZE after every big load, delete, restore or major upgrade, as a step in the runbook for those jobs.",
     "Lower autovacuum_analyze_scale_factor on large, fast-changing tables.",
     "Test queries with the data shape of the biggest customer, not the average one."
    ],
    "detect": [
     "Alert when one fingerprint's mean time rises several times over its baseline.",
     "Log slow queries with their plans (auto_explain in PostgreSQL)."
    ],
    "automate": [
     "An agent can compare today's plan for the top queries with yesterday's and flag any that changed shape.",
     "Run ANALYZE automatically at the end of every bulk job."
    ]
   },
   "done": "The query is back to its normal time for an hour, and you know why the plan changed.",
   "dont": [
    "Restart the database to fix a plan. It may come back the same, and the cache goes cold.",
    "Add an index without reading the plan. It may not be the one the query needs."
   ],
   "platform": {
    "rds": [
     {
      "t": "Performance Insights keeps SQL history: compare the query's load per call today with last week. After a major version upgrade on RDS, run ANALYZE on PostgreSQL: statistics may be missing."
     },
     {
      "t": "pg_hint_plan and auto_explain are available as extensions on RDS PostgreSQL, through the parameter group."
     }
    ],
    "k8s": [
     {
      "t": "Nothing different. If the operator restarted the pod during the incident, the plan cache is cold: compare after a few minutes of traffic."
     }
    ]
   }
  },
  "io": {
   "signals": [
    "Read latency up across many queries",
    "Disk queue depth high, or IOPS flat at the volume's limit",
    "CPU waits on I/O"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "disk",
     "phase": "confirm",
     "t": "Confirm the disk is the limit",
     "why": "A line flat at the provisioned IOPS or throughput is the tell. So is gp2 burst balance at zero.",
     "cmd": {
      "all": "iostat -x 1 5        # r_await, w_await and %util on the data volume\n# on AWS also look at the volume's queue length, and BurstBalance for gp2\n# AWS: CloudWatch ReadIOPS, WriteIOPS, DiskQueueDepth, BurstBalance for the volume"
     },
     "look": "Await in tens of ms and utilization near 100 percent, or IOPS flat at the cap.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "hit",
     "phase": "cause",
     "t": "Has the share served from memory fallen?",
     "why": "If it fell, the working set grew or something is scanning.",
     "cmd": {
      "pg": "SELECT blks_hit, blks_read,\n       round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct\nFROM pg_stat_database WHERE datname = current_database();",
      "my": "SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%';\n-- Innodb_buffer_pool_reads (from disk) against Innodb_buffer_pool_read_requests",
      "mo": "const c = db.serverStatus().wiredTiger.cache;\n[c['bytes currently in the cache'], c['maximum bytes configured'], c['pages read into cache']]"
     },
     "look": "Two readings a minute apart, compared with yesterday.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "who",
     "phase": "cause",
     "t": "Find who reads the most",
     "why": "One report or job usually explains it.",
     "cmd": {
      "pg": "SELECT calls, shared_blks_read, round(total_exec_time) AS total_ms, left(query, 80)\nFROM pg_stat_statements ORDER BY shared_blks_read DESC LIMIT 10;",
      "my": "SELECT * FROM sys.statements_with_full_table_scans LIMIT 10;\nSELECT * FROM sys.io_global_by_file_by_latency LIMIT 10;",
      "mo": "db.system.profile.find({}, { ns: 1, docsExamined: 1, millis: 1, planSummary: 1 })\n  .sort({ docsExamined: -1 }).limit(10)"
     },
     "look": "A new report or a scan without an index.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "One report or job",
       "go": "stop"
      },
      {
       "if": "Backups, vacuum or checkpoints",
       "go": "bg"
      }
     ]
    },
    {
     "key": "bg",
     "phase": "cause",
     "t": "Check background work",
     "why": "Backups, vacuum, checkpoints and compaction all use the disk.",
     "cmd": {
      "pg": "SELECT pid, relid::regclass, phase, heap_blks_scanned, heap_blks_total\nFROM pg_stat_progress_vacuum;\nSELECT * FROM pg_stat_checkpointer;   -- PostgreSQL 17 and later; pg_stat_bgwriter before",
      "my": "SHOW ENGINE INNODB STATUS\\G   -- BUFFER POOL AND MEMORY, and pending flushes",
      "mo": "db.serverStatus().wiredTiger.cache['tracked dirty bytes in the cache']",
      "all": "ps aux | grep -E 'pg_basebackup|xtrabackup|mysqldump|mongodump' | grep -v grep"
     },
     "look": "A backup at peak: move it. Checkpoints every few minutes: max_wal_size is too small.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "stop",
     "phase": "mitigate",
     "t": "Stop or move the heavy reader",
     "why": "Keep the live traffic; move the report.",
     "cmd": {
      "pg": "SELECT pg_cancel_backend(<pid>);   -- the report found in step 3",
      "my": "KILL QUERY <thread id>;",
      "mo": "db.killOp(<opid>)"
     },
     "look": "Disk wait falls within a minute.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Rerun it on a replica or off-peak.",
     "timebox": "5 minutes"
    },
    {
     "key": "iops",
     "phase": "mitigate",
     "t": "Raise the volume's IOPS or throughput",
     "why": "gp3 and io2 can be changed online. It costs money, so use it when the load is real.",
     "cmd": {
      "all": "aws ec2 modify-volume --volume-id <vol> --iops <n> --throughput <MBps>\n# RDS: modify-db-instance --iops <n> (and --storage-type gp3)"
     },
     "look": "Latency falls as the change applies.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm latency is back",
     "why": "Disk wait and the hit ratio back to normal for 15 minutes.",
     "cmd": {
      "pg": "SELECT blks_hit, blks_read,\n       round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct\nFROM pg_stat_database WHERE datname = current_database();",
      "my": "SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%';\n-- Innodb_buffer_pool_reads (from disk) against Innodb_buffer_pool_read_requests",
      "mo": "const c = db.serverStatus().wiredTiger.cache;\n[c['bytes currently in the cache'], c['maximum bytes configured'], c['pages read into cache']]"
     },
     "look": "Watch the next peak.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "The volume is at its maximum and the load is real: you need more memory or a different volume type.",
    "Vacuum or compaction is the reader and cannot be paused safely."
   ],
   "call": {
    "when": [
     "A new report, export or job is the heavy reader.",
     "The working set outgrew memory because the data grew."
    ],
    "ask": [
     "What does this job need, how often, and how fresh?",
     "Which data do users read most: the last day, the last month, everything?",
     "Can the export run from a replica or a snapshot?"
    ],
    "suggest": [
     [
      "Move it to a replica or warehouse",
      "Reports and exports read big ranges; keep them off the primary."
     ],
     [
      "Index the scan",
      "If it scans for a small result, it needs an index."
     ],
     [
      "Cache the hot reads",
      "If the same data is read again and again."
     ],
     [
      "Archive cold data",
      "Keep the hot set small enough to fit in memory."
     ]
    ]
   },
   "comms": "Database <name>: storage is saturated, so reads are slow. Cause: <what>. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Reports and exports on replicas by default.",
     "Memory sized for the working set, reviewed every quarter as data grows.",
     "Backups and heavy maintenance outside peak hours."
    ],
    "detect": [
     "Alert on disk queue depth and on IOPS near the provisioned limit.",
     "Alert on BurstBalance below 20 percent on gp2.",
     "Track the buffer cache hit ratio against its own baseline."
    ],
    "automate": [
     "An agent can name the top reader by blocks read within a minute of the alert.",
     "Schedule heavy jobs with a check that pauses them when disk latency rises."
    ]
   },
   "done": "Disk latency and hit ratio are back to normal, and the heavy reader has a new home or an index.",
   "dont": [
    "Cancel autovacuum again and again. It comes back, and the dead rows keep growing.",
    "Buy IOPS before you know what is reading."
   ],
   "platform": {
    "rds": [
     {
      "t": "ReadIOPS, WriteIOPS, ReadLatency, DiskQueueDepth and, on gp2, BurstBalance. gp3 IOPS and throughput can be raised online, but on RDS this is a storage change: the six hour rule applies."
     },
     {
      "t": "Enhanced Monitoring shows the OS view (per process I/O) that CloudWatch does not."
     }
    ],
    "k8s": [
     {
      "t": "Disk limits come from the storage class: cloud volume type and size. A database on network storage with a small volume gets small IOPS.",
      "cmd": "kubectl get pvc <pvc> -n <ns> -o jsonpath='{.spec.storageClassName}'"
     }
    ]
   }
  },
  "memory": {
   "signals": [
    "The database restarted on its own",
    "Connection errors for a minute, then recovery",
    "OOM killer lines in the kernel log",
    "A failover you did not start"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "up",
     "phase": "confirm",
     "t": "Is it up, and in the right role?",
     "why": "After a crash the database replays its log first. On a cluster, a failover may have happened.",
     "cmd": {
      "pg": "SELECT pg_is_in_recovery(), now() - pg_postmaster_start_time() AS up_for;",
      "my": "SHOW GLOBAL STATUS LIKE 'Uptime';\nSELECT @@read_only, @@super_read_only;",
      "mo": "rs.status().members.map(m => [m.name, m.stateStr])"
     },
     "look": "Up and with the expected role: step 3.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "It keeps restarting",
       "go": "loop"
      },
      {
       "if": "A failover happened",
       "go": "Check the old primary rejoined as a replica, and that apps point at the new one. Two primaries is a bigger outage than a restart."
      }
     ]
    },
    {
     "key": "loop",
     "phase": "mitigate",
     "t": "Stop a crash loop",
     "why": "If it is killed again as soon as traffic returns, take load off before it comes back: fewer connections, the heavy job stopped.",
     "cmd": {
      "all": "# stop the job or app that triggered it, or lower its pool, then start the database\nsystemctl status postgresql mysql mongod 2>/dev/null | head -20"
     },
     "look": "It stays up for 15 minutes with traffic.",
     "risk": "high",
     "approval": true,
     "branches": []
    },
    {
     "key": "oom",
     "phase": "cause",
     "t": "Confirm the OOM killer and the time",
     "why": "The kernel log names the process and the minute.",
     "cmd": {
      "all": "dmesg -T | grep -i -E 'killed process|out of memory'\njournalctl -k --since '2 hours ago' | grep -i -E 'oom|killed process'",
      "pg": "-- in the PostgreSQL log:\n-- server process (PID ...) was terminated by signal 9: Killed",
      "my": "-- in the MySQL error log: mysqld restarted, then InnoDB crash recovery",
      "mo": "// in the mongod log: no shutdown message before the next startup"
     },
     "look": "Line it up with your graphs: what spiked at that minute?",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "math",
     "phase": "cause",
     "t": "Add up what the configuration allows",
     "why": "Cache plus per-connection memory times connections must fit with room to spare.",
     "cmd": {
      "pg": "SELECT name, setting, unit FROM pg_settings\nWHERE name IN ('shared_buffers', 'work_mem', 'maintenance_work_mem',\n               'hash_mem_multiplier', 'max_connections', 'autovacuum_max_workers');\n-- work_mem is per sort or hash, so one query can use it several times",
      "my": "SELECT @@innodb_buffer_pool_size / 1024 / 1024 / 1024 AS buffer_pool_gb,\n       @@max_connections, @@sort_buffer_size, @@join_buffer_size, @@tmp_table_size;\nSELECT * FROM sys.memory_global_by_current_bytes LIMIT 10;",
      "mo": "db.serverStatus().wiredTiger.cache['maximum bytes configured']\n// default: 50 percent of (RAM - 1 GB)",
      "all": "free -g"
     },
     "look": "A cache near total RAM, or many connections each allowed big sorts.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "query",
     "phase": "cause",
     "t": "Find what ran when it died",
     "why": "One query with a huge sort or hash is a common trigger.",
     "cmd": {
      "pg": "-- the log lines just before the kill; to log big sorts from now on:\nALTER SYSTEM SET log_temp_files = '100MB';\nSELECT pg_reload_conf();",
      "my": "SELECT * FROM performance_schema.memory_summary_by_thread_by_event_name\nORDER BY current_number_of_bytes_used DESC LIMIT 10;",
      "mo": "// the slow operations in the mongod log just before the restart"
     },
     "look": "Write it down: it is the one to fix.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "room",
     "phase": "mitigate",
     "t": "Leave headroom",
     "why": "Lower the memory for the role that runs big queries; leave room for the OS.",
     "cmd": {
      "pg": "-- lower work_mem for the role that runs big reports, not for everyone\nALTER ROLE report_user SET work_mem = '64MB';\n-- PostgreSQL's docs recommend vm.overcommit_memory = 2 on dedicated servers",
      "my": "-- leave room: a buffer pool around 70 to 75 percent of RAM on a dedicated server\nSET PERSIST innodb_buffer_pool_size = <bytes>;   -- resizes online",
      "mo": "# mongod.conf\nstorage:\n  wiredTiger:\n    engineConfig:\n      cacheSizeGB: <smaller value>"
     },
     "look": "No OOM through the next peak.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Set the old values back."
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm it is stable",
     "why": "Up, the right role, memory below 85 percent through a peak.",
     "cmd": {
      "pg": "SELECT pg_is_in_recovery(), now() - pg_postmaster_start_time() AS up_for;",
      "my": "SHOW GLOBAL STATUS LIKE 'Uptime';\nSELECT @@read_only, @@super_read_only;",
      "mo": "rs.status().members.map(m => [m.name, m.stateStr])"
     },
     "look": "Watch the next day's peak too.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "A crash loop.",
    "Two nodes claim to be primary.",
    "The database does not finish crash recovery."
   ],
   "call": {
    "when": [
     "One query or job caused it.",
     "A new service added many connections."
    ],
    "ask": [
     "What ran at <time>? Any new report, export or batch job?",
     "How many connections do your services open now?",
     "Does any query sort or group millions of rows?"
    ],
    "suggest": [
     [
      "Paginate or stream",
      "Do not pull millions of rows into one result."
     ],
     [
      "Move it to a warehouse",
      "Big aggregations belong in an analytics store."
     ],
     [
      "Use a pooler",
      "Fewer real connections means less memory."
     ]
    ]
   },
   "comms": "Database <name> restarted at <time> because it ran out of memory. It is <up / recovering>. Cause: <what>. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Size the cache and per-connection memory with a written formula, reviewed when connections grow.",
     "work_mem raised only for the roles that need it.",
     "vm.overcommit_memory = 2 on dedicated PostgreSQL servers, as its docs recommend."
    ],
    "detect": [
     "Alert on memory above 85 percent.",
     "Alert on any unplanned restart or failover."
    ],
    "automate": [
     "An agent can collect the kernel log, the database log and the active queries from the minute before, and post them as one summary."
    ]
   },
   "done": "The database has been stable through a peak, and the memory budget adds up with room to spare.",
   "dont": [
    "Give the cache 90 percent of RAM on a server that also runs other things.",
    "Add swap and call it fixed. A database in swap is slower than one that restarts."
   ],
   "platform": {
    "rds": [
     {
      "t": "There is no kernel log. Look for FreeableMemory falling and SwapUsage rising, and for \"restarted\" or \"failover\" in RDS events.",
      "cmd": "aws rds describe-events --source-type db-instance --source-identifier <id> --duration 1440"
     },
     {
      "t": "Parameter groups use formulas such as {DBInstanceClassMemory*3/4} for the buffer pool. A custom value copied from a bigger instance is a common cause."
     }
    ],
    "k8s": [
     {
      "t": "An OOM kill shows as Last State: Terminated, Reason: OOMKilled, exit code 137 on the container.",
      "cmd": "kubectl describe pod <db-pod> -n <ns> | grep -A5 'Last State'\nkubectl logs <db-pod> -n <ns> --previous | tail -50"
     },
     {
      "t": "The database's memory settings must fit the container limit, not the node. shared_buffers or the buffer pool sized for the node gets the pod killed."
     }
    ]
   }
  },
  "commits": {
   "signals": [
    "Inserts and updates slow while reads are fine",
    "Commit latency up with low CPU",
    "All writes hang at once: classic sign of a synchronous standby that went away"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "wait",
     "phase": "confirm",
     "t": "What are commits waiting on",
     "why": "This decides the rest.",
     "cmd": {
      "pg": "SELECT wait_event_type, wait_event, count(*)\nFROM pg_stat_activity WHERE state = 'active'\nGROUP BY 1, 2 ORDER BY 3 DESC;\n-- WALSync or WALWrite: the disk.  SyncRep: a synchronous standby.",
      "my": "SELECT event_name, count_star, sum_timer_wait / 1e12 AS total_s\nFROM performance_schema.file_summary_by_event_name\nWHERE event_name LIKE '%innodb_log_file%';\nSHOW GLOBAL STATUS LIKE 'Rpl_semi_sync_source%';",
      "mo": "db.serverStatus().opLatencies.writes\n// with writeConcern majority, writes also wait for secondaries"
     },
     "look": "Read the wait events.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "SyncRep (PostgreSQL), semi-sync waits (MySQL), w: majority (MongoDB)",
       "go": "sync"
      },
      {
       "if": "WALSync or WALWrite, or log file waits",
       "go": "disk"
      },
      {
       "if": "Lock waits",
       "go": "See Queries waiting on locks."
      }
     ]
    },
    {
     "key": "sync",
     "phase": "cause",
     "t": "Which standby is slow or gone",
     "why": "With synchronous replication every commit waits for it. If it is gone, every commit waits forever.",
     "cmd": {
      "pg": "SHOW synchronous_standby_names;\nSELECT application_name, sync_state, state, flush_lag\nFROM pg_stat_replication;",
      "my": "SHOW GLOBAL STATUS LIKE 'Rpl_semi_sync_source_status';\nSHOW VARIABLES LIKE 'rpl_semi_sync_source_timeout';",
      "mo": "rs.printSecondaryReplicationInfo()"
     },
     "look": "A missing or far-behind sync standby.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "The standby is down",
       "go": "async"
      }
     ]
    },
    {
     "key": "async",
     "phase": "mitigate",
     "t": "Decide: keep waiting, or drop to asynchronous for now",
     "why": "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.",
     "cmd": {
      "pg": "-- a dead synchronous standby: commits stop waiting for it\nALTER SYSTEM SET synchronous_standby_names = '';\nSELECT pg_reload_conf();\n-- for a non-critical role only: commits return before the flush\nALTER ROLE events_user SET synchronous_commit = off;",
      "my": "-- semi-sync falls back to async after this many ms without an ack\nSET PERSIST rpl_semi_sync_source_timeout = 1000;",
      "mo": "// for non-critical writes only, in the app:\n// { writeConcern: { w: 1 } } instead of majority"
     },
     "look": "Writes flow again.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "Set synchronous_standby_names back once the standby is healthy.",
     "timebox": "Decide within 10 minutes"
    },
    {
     "key": "disk",
     "phase": "cause",
     "t": "Measure the log disk",
     "why": "Every durable commit waits for one flush.",
     "cmd": {
      "all": "iostat -x 1 5                  # w_await on the log volume\npg_test_fsync -f /data/test    # PostgreSQL's tool: flushes per second on this disk"
     },
     "look": "A flush in milliseconds: the volume is slow, shared or throttled.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "idx",
     "phase": "cause",
     "t": "Check for too many indexes",
     "why": "Every insert updates every index.",
     "cmd": {
      "pg": "SELECT indexrelid::regclass AS index, idx_scan,\n       pg_size_pretty(pg_relation_size(indexrelid)) AS size\nFROM pg_stat_user_indexes WHERE idx_scan = 0\nORDER BY pg_relation_size(indexrelid) DESC LIMIT 10;",
      "my": "SELECT * FROM sys.schema_unused_indexes;",
      "mo": "db.orders.aggregate([{ $indexStats: {} }])   // accesses.ops near 0 means unused"
     },
     "look": "Not a mid-incident fix: put it in the postmortem.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm writes are normal",
     "why": "Commit latency back to baseline.",
     "cmd": {
      "pg": "SELECT wait_event_type, wait_event, count(*)\nFROM pg_stat_activity WHERE state = 'active'\nGROUP BY 1, 2 ORDER BY 3 DESC;\n-- WALSync or WALWrite: the disk.  SyncRep: a synchronous standby.",
      "my": "SELECT event_name, count_star, sum_timer_wait / 1e12 AS total_s\nFROM performance_schema.file_summary_by_event_name\nWHERE event_name LIKE '%innodb_log_file%';\nSHOW GLOBAL STATUS LIKE 'Rpl_semi_sync_source%';",
      "mo": "db.serverStatus().opLatencies.writes\n// with writeConcern majority, writes also wait for secondaries"
     },
     "look": "If you dropped to async: a ticket to restore it, with an owner.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Dropping to async is on the table: that is a data loss decision.",
    "The log volume is the problem and cannot be changed quickly."
   ],
   "call": {
    "when": [
     "Write volume or write pattern changed.",
     "The durability decision (sync or async) affects their data."
    ],
    "ask": [
     "Did write volume change? Are rows written one per transaction?",
     "For this data, what is worse: a few seconds of writes failing, or losing the last second of writes in a failover?"
    ],
    "suggest": [
     [
      "Batch commits",
      "Many rows per transaction instead of one."
     ],
     [
      "Durability per data type",
      "Events or metrics can use asynchronous commit; payments cannot."
     ],
     [
      "Two sync standbys",
      "ANY 1 of 2 standbys, so one failing does not stop writes."
     ]
    ]
   },
   "comms": "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>.",
   "postmortem": {
    "prevent": [
     "Synchronous replication with a quorum of standbys (ANY 1 of 2), never a single required one.",
     "The WAL or redo log on a fast volume of its own."
    ],
    "detect": [
     "Alert on commit latency, and on a synchronous standby disconnecting.",
     "Alert on WAL sync time."
    ],
    "automate": [
     "An agent can detect a dead sync standby in seconds and prepare the async switch for a human to approve, with the data-loss window stated."
    ]
   },
   "done": "Commit latency is normal, and any durability change has a ticket and an owner to restore it.",
   "dont": [
    "Turn off fsync, or set innodb_flush_log_at_trx_commit away from 1 for the whole server. A crash can corrupt data or lose commits.",
    "Switch to async without the owner agreeing to the data-loss window."
   ],
   "platform": {
    "rds": [
     {
      "t": "Multi-AZ instances replicate every write synchronously to the standby, so commit latency includes that. Multi-AZ DB clusters (two readable standbys) wait for one of two. Aurora writes six copies across three zones and needs four."
     },
     {
      "t": "WriteLatency and CommitLatency (Aurora) in CloudWatch."
     }
    ],
    "k8s": [
     {
      "t": "Check the storage class: network-attached volumes add latency to every flush. Operators can also run synchronous replicas: check the cluster resource.",
      "cmd": "kubectl get cluster <name> -n <ns> -o yaml | grep -i -A3 sync"
     }
    ]
   }
  },
  "bloat": {
   "signals": [
    "PostgreSQL warns \"database must be vacuumed within N transactions\"",
    "PostgreSQL refuses writes \"to avoid wraparound data loss\": a full outage",
    "Tables grow while row counts do not; MySQL history list length in the millions"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "wrap",
     "phase": "confirm",
     "t": "How close is wraparound?",
     "why": "Writes stop near 2 billion. This number decides how urgent the next hour is.",
     "cmd": {
      "pg": "SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY 2 DESC;\nSELECT relname, age(relfrozenxid) AS xid_age\nFROM pg_class WHERE relkind = 'r' ORDER BY 2 DESC LIMIT 10;",
      "my": "-- not applicable to MySQL",
      "mo": "// not applicable to MongoDB"
     },
     "look": "Over a billion and climbing: treat it as an outage.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "block",
     "phase": "cause",
     "t": "Find what stops cleanup",
     "why": "An old transaction, an abandoned replication slot, a forgotten prepared transaction, or a replica with hot_standby_feedback.",
     "cmd": {
      "pg": "-- the oldest snapshots\nSELECT pid, usename, state, now() - xact_start AS age, backend_xmin\nFROM pg_stat_activity WHERE backend_xmin IS NOT NULL\nORDER BY age(backend_xmin) DESC LIMIT 5;\nSELECT slot_name, active, xmin, catalog_xmin FROM pg_replication_slots;\nSELECT gid, prepared FROM pg_prepared_xacts;",
      "my": "SELECT trx_mysql_thread_id, trx_started, trx_state\nFROM information_schema.innodb_trx ORDER BY trx_started LIMIT 5;",
      "mo": "db.getSiblingDB('admin').aggregate([\n  { $currentOp: { allUsers: true, idleSessions: true } },\n  { $match: { transaction: { $exists: true } } }])"
     },
     "look": "The oldest of these is the blocker.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Found one",
       "go": "remove"
      }
     ]
    },
    {
     "key": "remove",
     "phase": "mitigate",
     "t": "Remove the blocker",
     "why": "Nothing else helps until the oldest snapshot is gone.",
     "cmd": {
      "pg": "SELECT pg_terminate_backend(<pid>);           -- the old transaction\nSELECT pg_drop_replication_slot('old_slot');  -- only if nobody will read it again\nROLLBACK PREPARED '<gid>';                     -- a forgotten prepared transaction",
      "my": "KILL <thread id>;   -- the old transaction; its rollback can take a while",
      "mo": "db.killOp(<opid>)"
     },
     "look": "The oldest xmin moves forward.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "None. A dropped slot's consumer needs a rebuild."
    },
    {
     "key": "freeze",
     "phase": "mitigate",
     "t": "Vacuum the oldest tables first",
     "why": "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.",
     "cmd": {
      "pg": "VACUUM (FREEZE, VERBOSE) <the oldest table>;\n-- watch it from another session\nSELECT * FROM pg_stat_progress_vacuum;"
     },
     "look": "age(datfrozenxid) falls after each table.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "timebox": "As long as it takes; report progress every 15 minutes"
    },
    {
     "key": "dead",
     "phase": "cause",
     "t": "For plain bloat: measure the dead rows",
     "why": "Not urgent unless the disk is filling.",
     "cmd": {
      "pg": "SELECT relname, n_live_tup, n_dead_tup, last_autovacuum,\n       pg_size_pretty(pg_total_relation_size(relid)) AS size\nFROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;",
      "my": "SELECT table_name, ROUND(data_free / 1024 / 1024) AS free_mb,\n       ROUND((data_length + index_length) / 1024 / 1024) AS used_mb\nFROM information_schema.tables WHERE table_schema = DATABASE()\nORDER BY data_free DESC LIMIT 10;\nSELECT count FROM information_schema.innodb_metrics WHERE name = 'trx_rseg_history_len';",
      "mo": "db.orders.stats().wiredTiger['block-manager']['file bytes available for reuse']"
     },
     "look": "Plan the fix; do not rebuild tables in the middle of the day.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm the age is falling",
     "why": "age(datfrozenxid) well under autovacuum_freeze_max_age, and autovacuum keeping up.",
     "cmd": {
      "pg": "SELECT datname, age(datfrozenxid) AS xid_age FROM pg_database ORDER BY 2 DESC;\nSELECT relname, age(relfrozenxid) AS xid_age\nFROM pg_class WHERE relkind = 'r' ORDER BY 2 DESC LIMIT 10;",
      "my": "-- not applicable to MySQL",
      "mo": "// not applicable to MongoDB"
     },
     "look": "",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "PostgreSQL has stopped accepting writes.",
    "The age is over a billion and the blocker is a slot or replica someone else owns."
   ],
   "call": {
    "when": [
     "An app keeps long transactions or long-running reports open.",
     "A CDC connector or replica owns the slot that blocks cleanup."
    ],
    "ask": [
     "What keeps a transaction open for hours? A report, a cursor, a forgotten session?",
     "Is your connector still reading this slot?",
     "Do you run hours-long queries on a replica with hot_standby_feedback on?"
    ],
    "suggest": [
     [
      "Short transactions",
      "Long reports belong on a replica without hot_standby_feedback, or in a warehouse."
     ],
     [
      "Timeouts",
      "idle_in_transaction_session_timeout and statement_timeout for app users."
     ],
     [
      "Partition big tables",
      "Smaller tables vacuum and freeze faster, and old partitions can be dropped."
     ]
    ]
   },
   "comms": "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>.",
   "postmortem": {
    "prevent": [
     "Timeouts for idle transactions and statements.",
     "max_slot_wal_keep_size, and monitoring of slot consumers.",
     "Autovacuum tuned for the biggest tables: more workers, a higher cost limit."
    ],
    "detect": [
     "Alert on age(datfrozenxid) above 500 million, long before PostgreSQL warns.",
     "Alert on the oldest transaction age and on inactive slots."
    ],
    "automate": [
     "An agent can track wraparound age daily and open a ticket with the oldest tables and the current blocker long before it is urgent."
    ]
   },
   "done": "The age is falling and well below the alert line, the blocker is gone, and autovacuum keeps up on its own.",
   "dont": [
    "Run VACUUM FULL on a busy table. It locks the table until it finishes.",
    "Disable autovacuum on a table because it is busy. That is how wraparound happens."
   ],
   "platform": {
    "rds": [
     {
      "t": "MaximumUsedTransactionIDs in CloudWatch is the wraparound age. Alert on it. RDS has no single-user mode, so remove blockers early."
     },
     {
      "t": "pg_repack is available as an extension on RDS PostgreSQL."
     }
    ],
    "k8s": [
     {
      "t": "Nothing different, except the PVC: a rebuild needs free space for a full copy of the table."
     }
    ]
   }
  },
  "redis": {
   "title": "Redis: latency spikes, memory full, writes refused",
   "see": "Commands that took a millisecond take tens or hundreds. Or writes fail with \"OOM command not allowed when used memory > maxmemory\".",
   "causes": [
    "Memory reached maxmemory, and the eviction policy is noeviction.",
    "One big key: a list, set or hash with millions of members, read or deleted in one command.",
    "A fork for a snapshot or rewrite on a large dataset pauses the server.",
    "A slow command such as KEYS, or a Lua script that runs long."
   ],
   "more": "How Redis works and where it breaks: <a href=\"../redis/index.html#breaks\">Redis, the cache in front</a>.",
   "signals": [
    "Latency alert on Redis or on the app endpoints that use it",
    "\"OOM command not allowed\" errors",
    "Many client timeouts at once"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "mem",
     "phase": "confirm",
     "t": "Check memory against the limit",
     "why": "Writes are refused when memory hits maxmemory with noeviction.",
     "cmd": {
      "all": "redis-cli INFO memory | grep -E 'used_memory_human|maxmemory_human|maxmemory_policy|mem_fragmentation_ratio'\nredis-cli INFO stats | grep -E 'evicted_keys|rejected_connections'"
     },
     "look": "Near the limit: step 5.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "slow",
     "phase": "cause",
     "t": "Find the slow commands",
     "why": "One slow command delays every client.",
     "cmd": {
      "all": "redis-cli SLOWLOG GET 10\nredis-cli --latency            # live latency from this client\nredis-cli LATENCY DOCTOR       # needs latency-monitor-threshold set"
     },
     "look": "KEYS, big SMEMBERS or HGETALL, or a long script.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "A client is running it",
       "go": "client"
      }
     ]
    },
    {
     "key": "client",
     "phase": "cause",
     "t": "Find the client sending it",
     "why": "CLIENT LIST shows each connection's last command and its address.",
     "cmd": {
      "all": "redis-cli CLIENT LIST | grep -E 'cmd=(keys|smembers|hgetall|eval)'\n# each line has id=, addr= and name=: the address tells you which app"
     },
     "look": "Note the address and name. That is the team to call.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "big",
     "phase": "cause",
     "t": "Find big keys",
     "why": "One key with millions of members makes every command on it slow.",
     "cmd": {
      "all": "redis-cli --bigkeys     # scans with SCAN; run it on a replica if you can\nredis-cli --memkeys\nredis-cli MEMORY USAGE <key>"
     },
     "look": "Split it in the app; delete with UNLINK.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "fix",
     "phase": "mitigate",
     "t": "Stop the bleeding",
     "why": "For a cache, let Redis evict. Remove the big key without blocking, and disconnect the client running KEYS.",
     "cmd": {
      "all": "redis-cli CONFIG SET maxmemory-policy allkeys-lru   # only if every key can be rebuilt\nredis-cli UNLINK <big key>\nredis-cli CONFIG REWRITE                            # keep the change after a restart\nredis-cli CLIENT KILL ID <id>"
     },
     "look": "Writes succeed and latency falls.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "CONFIG SET maxmemory-policy <old policy>"
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm latency is back",
     "why": "p99 back to normal, memory below the limit.",
     "cmd": {
      "all": "redis-cli SLOWLOG GET 10\nredis-cli --latency            # live latency from this client\nredis-cli LATENCY DOCTOR       # needs latency-monitor-threshold set"
     },
     "look": "",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Redis holds data that cannot be rebuilt (sessions, queues) and memory is full.",
    "A failover happened and clients did not follow."
   ],
   "call": {
    "when": [
     "One client sends slow commands or builds big keys.",
     "Memory grew because of a new use."
    ],
    "ask": [
     "What do you store, how big does a key get, and does it need a TTL?",
     "Can this data be rebuilt from the database if Redis loses it?"
    ],
    "suggest": [
     [
      "TTL on every cache key",
      "So memory cannot fill with keys nobody reads."
     ],
     [
      "Split big keys",
      "Many small hashes instead of one huge one."
     ],
     [
      "SCAN instead of KEYS",
      "Never KEYS in production code."
     ],
     [
      "A separate Redis for data you cannot lose",
      "Do not mix cache and queues in one instance."
     ]
    ]
   },
   "comms": "Redis <name>: <slow / refusing writes>. Cause: <what>. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "TTL on cache keys, and the right eviction policy for each instance.",
     "Rename or disable KEYS and FLUSHALL in production."
    ],
    "detect": [
     "Alert on memory at 80 percent of maxmemory, and on evicted keys when they should not happen.",
     "Alert on slowlog entries."
    ],
    "automate": [
     "An agent can sample big keys weekly on a replica and report the owners."
    ]
   },
   "done": "Latency is normal, memory is below the limit, and the key or client that caused it has an owner and a fix.",
   "dont": [
    "Run KEYS * in production. It blocks Redis until it has walked every key.",
    "Set an evicting policy on a Redis that holds data nobody can rebuild."
   ],
   "platform": {
    "rds": [
     {
      "t": "ElastiCache: DatabaseMemoryUsagePercentage, EngineCPUUtilization (the one thread), Evictions and CurrConnections in CloudWatch. KEYS and CONFIG may be renamed or blocked; change settings in the parameter group."
     }
    ],
    "k8s": [
     {
      "t": "A Redis pod with persistence on a slow volume pauses on every fork for a snapshot. A cache usually needs no persistence at all."
     }
    ]
   }
  },
  "cassandra": {
   "title": "Cassandra: slow reads on some nodes, deleted data returning",
   "see": "Reads are slow or time out on some nodes but not others. Or rows that were deleted show up again.",
   "causes": [
    "A partition grew far too large.",
    "Reads scan many tombstones before finding live data.",
    "Compaction is behind, so each read touches many SSTables.",
    "Repair did not run within gc_grace_seconds."
   ],
   "more": "How Cassandra spreads data and where it breaks: <a href=\"../cassandra/index.html#breaks\">Cassandra, built to spread</a>. A real case: <a href=\"../stories/index.html#discord-tombstones\">Discord's 20 second channel</a>.",
   "signals": [
    "Read latency p99 up on some nodes",
    "Read timeouts in the app",
    "Tombstone warnings in system.log"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "nodes",
     "phase": "confirm",
     "t": "Find the sick nodes",
     "why": "Pending reads and dropped messages show which nodes are struggling.",
     "cmd": {
      "all": "nodetool status          # every node should be UN (up, normal)\nnodetool tpstats         # Pending and Blocked tasks, and dropped messages"
     },
     "look": "One or two nodes stand out: step 2.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "drain",
     "phase": "mitigate",
     "t": "Take client traffic off the sick node",
     "why": "The other replicas serve the reads. The node keeps receiving writes and catches up.",
     "cmd": {
      "all": "nodetool disablebinary    # stop serving CQL clients on this node\n# later: nodetool enablebinary"
     },
     "look": "Read latency falls for clients.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "nodetool enablebinary"
    },
    {
     "key": "table",
     "phase": "cause",
     "t": "Look at the table the slow reads hit",
     "why": "Partition size and SSTables per read.",
     "cmd": {
      "all": "nodetool tablehistograms <keyspace> <table>   # partition size and SSTables per read\nnodetool tablestats <keyspace>.<table>          # max partition bytes, tombstones per slice"
     },
     "look": "Huge partitions or many SSTables per read.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "tomb",
     "phase": "cause",
     "t": "Check tombstones",
     "why": "Deletes and TTLs pile up.",
     "cmd": {
      "all": "grep -i tombstone /var/log/cassandra/system.log | tail -20"
     },
     "look": "A data model problem: get the app team on the call.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "comp",
     "phase": "cause",
     "t": "Check compaction and GC",
     "why": "Behind on compaction, or long GC pauses.",
     "cmd": {
      "all": "nodetool compactionstats    # pending tasks\nnodetool gcstats\ngrep GCInspector /var/log/cassandra/system.log | tail -10"
     },
     "look": "",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "repair",
     "phase": "mitigate",
     "t": "Deleted data returning: repair",
     "why": "A replica missed a delete.",
     "cmd": {
      "all": "nodetool repair -pr <keyspace>    # on every node in turn, primary ranges only"
     },
     "look": "Schedule repair within gc_grace_seconds.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm latency is even across nodes",
     "why": "Then put the node back.",
     "cmd": {
      "all": "nodetool enablebinary\nnodetool tpstats"
     },
     "look": "",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "More than one replica of the same range is sick.",
    "Deleted data reappeared in a table that matters (payments, permissions)."
   ],
   "call": {
    "when": [
     "A partition is too large or full of tombstones: that is the data model."
    ],
    "ask": [
     "What is the partition key, and how big can one partition grow?",
     "Do you delete or overwrite with nulls a lot? Use TTLs?",
     "Which query is slow, and does it read a whole partition?"
    ],
    "suggest": [
     [
      "Bucket the partition key",
      "Add a time bucket so no partition grows past ~100 MB."
     ],
     [
      "Avoid nulls and mass deletes",
      "They write tombstones."
     ],
     [
      "Use TTLs with time-window compaction",
      "For time series."
     ]
    ]
   },
   "comms": "Cassandra <cluster>: reads are slow on <nodes>. We have taken them out of client traffic. Cause: <what>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Partition size limits in design review.",
     "Repair on a schedule with a tool such as Cassandra Reaper."
    ],
    "detect": [
     "Alert on max partition size, tombstones per read and pending compactions."
    ],
    "automate": [
     "An agent can check repair history against gc_grace_seconds for every table and open tickets."
    ]
   },
   "done": "Latency is even across nodes, every node is serving again, and the table has a fix planned.",
   "dont": [
    "Lower gc_grace_seconds below how often repair runs.",
    "Restart the slow node and hope. It comes back with the same partitions."
   ],
   "platform": {
    "k8s": [
     {
      "t": "With K8ssandra or another operator, run nodetool inside the pod, and let the operator do restarts and repairs (Reaper).",
      "cmd": "kubectl exec -it <cassandra-pod> -n <ns> -c cassandra -- nodetool status"
     }
    ]
   }
  },
  "vector": {
   "title": "Vector search: results missing, or search got slow",
   "see": "Similar items that should be found are not, or a filtered search returns fewer results than asked for. Or search latency grew with the data.",
   "causes": [
    "A filter applied after the approximate index.",
    "Search settings too low for the data size.",
    "The index no longer fits in memory.",
    "An IVFFlat index built on early data."
   ],
   "more": "How vector indexes work: <a href=\"../vector-databases/index.html#breaks\">Vector databases</a>. Measured: <a href=\"../notebooks/index.html#agent-memory\">a tenant filter after HNSW returned 1.3 rows instead of 10</a>.",
   "signals": [
    "Users report missing results, or an AI feature gives worse answers",
    "Search latency up after data growth",
    "Filtered searches return fewer rows than LIMIT"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "recall",
     "phase": "confirm",
     "t": "Compare the index with an exact search",
     "why": "Recall is how many true nearest neighbours the index found.",
     "cmd": {
      "all": "-- approximate, using the index\nSELECT id FROM items ORDER BY embedding <=> :q LIMIT 10;\n-- exact, without the index\nBEGIN;\nSET LOCAL enable_indexscan = off;\nSELECT id FROM items ORDER BY embedding <=> :q LIMIT 10;\nCOMMIT;"
     },
     "look": "9 or 10 of 10 is good.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "filter",
     "phase": "cause",
     "t": "Does a filter run after the index?",
     "why": "The index returns its candidates, then the filter throws most away.",
     "cmd": {
      "all": "EXPLAIN ANALYZE\nSELECT id FROM items WHERE tenant_id = 7\nORDER BY embedding <=> :q LIMIT 10;\n-- an index scan, then Filter with many Rows Removed"
     },
     "look": "Many rows removed by the filter.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Yes",
       "go": "iter"
      }
     ]
    },
    {
     "key": "iter",
     "phase": "mitigate",
     "t": "Fix the filter",
     "why": "Let the index keep scanning, or give the big tenant its own index.",
     "cmd": {
      "all": "-- pgvector 0.8 and later: keep scanning until LIMIT rows pass the filter\nSET hnsw.iterative_scan = relaxed_order;\n-- or a partial index for a big tenant\nCREATE INDEX CONCURRENTLY items_t7_emb ON items\n  USING hnsw (embedding vector_cosine_ops) WHERE tenant_id = 7;"
     },
     "look": "The filtered query returns the full LIMIT.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ef",
     "phase": "mitigate",
     "t": "Raise the search settings",
     "why": "More of the graph searched, more true neighbours found.",
     "cmd": {
      "all": "SET hnsw.ef_search = 100;       -- default 40; must be at least LIMIT\nSET ivfflat.probes = 10;        -- default 1"
     },
     "look": "Recall up and latency acceptable.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "RESET hnsw.ef_search;"
    },
    {
     "key": "mem",
     "phase": "cause",
     "t": "Does the index fit in memory?",
     "why": "From disk, every hop in the graph is a read.",
     "cmd": {
      "all": "SELECT pg_size_pretty(pg_relation_size('items_embedding_idx'));\nSHOW shared_buffers;"
     },
     "look": "Much bigger than memory: more RAM, halfvec, or partitions.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm recall on several real queries",
     "why": "One query is not a test.",
     "cmd": {
      "all": "-- approximate, using the index\nSELECT id FROM items ORDER BY embedding <=> :q LIMIT 10;\n-- exact, without the index\nBEGIN;\nSET LOCAL enable_indexscan = off;\nSELECT id FROM items ORDER BY embedding <=> :q LIMIT 10;\nCOMMIT;"
     },
     "look": "",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "The index must be rebuilt on a large table.",
    "The fix needs more memory."
   ],
   "call": {
    "when": [
     "Results got worse for one tenant or one filter.",
     "The data grew much faster than planned."
    ],
    "ask": [
     "Which queries got worse? Can you give five real examples?",
     "Do you filter by tenant, date or category before or after the vector search?",
     "How many vectors per tenant, and how fast is it growing?"
    ],
    "suggest": [
     [
      "A partial index per large tenant",
      "Or partitions by tenant."
     ],
     [
      "Iterative scans",
      "pgvector 0.8 and later."
     ],
     [
      "A recall test in CI",
      "A fixed set of queries with known answers, run on every change."
     ]
    ]
   },
   "comms": "<feature> search is <missing results / slow>. Cause: <what>. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "A recall test on a fixed query set, run weekly and on every index change.",
     "Index memory sized with the data growth."
    ],
    "detect": [
     "Track recall and p95 latency for a fixed query set."
    ],
    "automate": [
     "An agent can run the recall test nightly and flag drops."
    ]
   },
   "done": "Recall on real queries is back where you want it, and filtered searches return the full number of results.",
   "dont": [
    "Trust a vector search that has never been compared with an exact search on your data.",
    "Raise ef_search for everyone to fix one tenant's filter."
   ],
   "platform": {
    "rds": [
     {
      "t": "pgvector is available on RDS and Aurora PostgreSQL. HNSW indexes need memory: check FreeableMemory and BufferCacheHitRatio when latency rises."
     }
    ],
    "k8s": [
     {
      "t": "Index builds need maintenance_work_mem inside the container limit. A big HNSW build can get the pod OOMKilled."
     }
    ]
   }
  },
  "patroni-readonly": {
   "group": "patroni",
   "eng": "pg",
   "label": "Patroni and etcd",
   "title": "Patroni: no leader, or the primary went read-only",
   "see": "Writes fail with \"cannot execute ... in a read-only transaction\". patronictl shows no Leader, or every member as a Replica.",
   "causes": [
    "etcd lost quorum or is unreachable, so the leader cannot renew its key and demotes itself. This is Patroni protecting you from split brain.",
    "etcd is out of space (the NOSPACE alarm) or its disk is so slow that requests time out.",
    "A network split put the primary on the minority side.",
    "The cluster is paused (maintenance mode) and someone stopped the primary."
   ],
   "more": "Why Patroni demotes instead of guessing: <a href=\"../lessons/consensus/index.html\">Consensus and leaders</a>.",
   "signals": [
    "App errors: read-only transaction",
    "patronictl list shows no Leader",
    "Patroni logs: \"failed to update leader lock\" or \"demoting self\""
   ],
   "start": "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.",
   "steps": [
    {
     "key": "list",
     "phase": "confirm",
     "t": "See what Patroni thinks",
     "why": "Roles, states, lag and timeline for every member.",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml list\npatronictl -c /etc/patroni/patroni.yml history | tail -5"
     },
     "look": "No Leader, or a Leader whose state is not running.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "etcd",
     "phase": "cause",
     "t": "Check etcd health and quorum",
     "why": "Patroni needs a majority of etcd members to keep the leader key.",
     "cmd": {
      "all": "etcdctl endpoint health --cluster\netcdctl endpoint status --cluster -w table   # leader, DB size, raft term\netcdctl alarm list"
     },
     "look": "Read the result.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Fewer than a majority healthy",
       "go": "quorum"
      },
      {
       "if": "alarm:NOSPACE",
       "go": "nospace"
      },
      {
       "if": "All healthy",
       "go": "logs"
      }
     ]
    },
    {
     "key": "logs",
     "phase": "cause",
     "t": "Read the Patroni logs on the old primary",
     "why": "They say why it stepped down.",
     "cmd": {
      "all": "journalctl -u patroni --since '30 min ago' | grep -i -E 'demot|lock|dcs|timeout' | tail -30"
     },
     "look": "\"failed to update leader lock\" means it could not reach etcd in time; look at the network and etcd disk latency.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "quorum",
     "phase": "mitigate",
     "t": "Bring etcd back to a majority",
     "why": "Start the stopped members or fix the network between them. Patroni elects a leader by itself once etcd answers.",
     "cmd": {
      "all": "systemctl status etcd\nsystemctl start etcd     # on the members that are down\netcdctl member list -w table"
     },
     "look": "A leader appears in patronictl list within a loop or two (10 to 30 seconds).",
     "risk": "low",
     "approval": false,
     "branches": [],
     "timebox": "15 minutes"
    },
    {
     "key": "nospace",
     "phase": "mitigate",
     "t": "Clear the etcd space alarm",
     "why": "etcd keeps old revisions until compacted. At the quota (2 GB by default) it refuses writes, so Patroni cannot write its key.",
     "cmd": {
      "all": "rev=$(etcdctl endpoint status --write-out=json | grep -o '\"revision\":[0-9]*' | head -1 | cut -d: -f2)\netcdctl compact $rev\netcdctl defrag --cluster\netcdctl alarm disarm"
     },
     "look": "alarm list is empty and Patroni elects a leader.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "Nothing to undo."
    },
    {
     "key": "manual",
     "phase": "mitigate",
     "t": "If etcd cannot come back soon: run without it, on purpose",
     "why": "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.",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml pause\n# on the node you choose, after checking it has the most WAL:\nsudo -u postgres pg_ctl promote -D <data dir>"
     },
     "look": "One writable primary, and every app pointed at it.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "patronictl -c /etc/patroni/patroni.yml resume, once etcd is healthy and the others follow this primary."
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm one leader and healthy replicas",
     "why": "",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml list",
      "q": "SELECT pg_is_in_recovery();"
     },
     "look": "One Leader, replicas streaming, lag near zero.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "etcd lost quorum and members will not start.",
    "Anyone suggests promoting by hand: get a second DBA."
   ],
   "call": {
    "when": [
     "Writes are failing and the app owners need to know whether to retry or wait."
    ],
    "ask": [
     "Can your app run read-only for a while, or should it fail fast?",
     "Does it retry writes, and are those writes idempotent?"
    ],
    "suggest": [
     [
      "Fail fast on read-only errors",
      "Retry with backoff instead of hammering a demoted primary."
     ],
     [
      "Connect through a service that follows the leader",
      "A Patroni REST check behind HAProxy, or a Kubernetes service the operator updates."
     ]
    ]
   },
   "comms": "PostgreSQL cluster <name> has no writable primary because <etcd / network>. Reads work, writes fail. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Run etcd on its own fast disks, with three or five members across zones.",
     "Schedule etcd compaction and defragmentation (auto-compaction-retention).",
     "Consider Patroni failsafe_mode (Patroni 3.0 and later): the leader keeps running when etcd is down but every member can still see it."
    ],
    "detect": [
     "Alert on etcd health, leader changes, DB size against quota, and fsync latency.",
     "Alert on Patroni reporting no leader."
    ],
    "automate": [
     "An agent can check etcd health and the alarm list the moment Patroni reports no leader, and post which of the two problems it is."
    ]
   },
   "done": "One leader, every replica streaming, etcd healthy with room under its quota.",
   "dont": [
    "Wipe etcd data or the Patroni key to \"reset\" the cluster.",
    "Promote a replica with pg_ctl while Patroni is running and not paused. You can end up with two primaries."
   ]
  },
  "patroni-failover": {
   "group": "patroni",
   "eng": "pg",
   "label": "Patroni",
   "title": "Patroni: an unexpected failover, or failovers that keep happening",
   "see": "The primary moved without anyone asking. Apps saw a burst of errors. Maybe it happened several times.",
   "causes": [
    "The primary or its network paused longer than ttl (30 seconds by default): a VM pause, a long I/O stall, a network blip.",
    "etcd itself was slow, so the leader could not renew its key in time.",
    "The primary really died: OOM, disk full, hardware.",
    "Someone ran a failover or a node was drained for maintenance."
   ],
   "more": "",
   "signals": [
    "patronictl history shows a new entry",
    "Burst of connection errors",
    "The timeline went up by one"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "hist",
     "phase": "confirm",
     "t": "When and to whom",
     "why": "The history shows each failover with its time and the new leader.",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml history\npatronictl -c /etc/patroni/patroni.yml list"
     },
     "look": "A new leader, and whether the old one is back.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "why",
     "phase": "cause",
     "t": "Why the old leader lost its lease",
     "why": "Its Patroni log just before the failover.",
     "cmd": {
      "all": "journalctl -u patroni --since '<time - 5 min>' --until '<time + 2 min>' | grep -v -i 'no action'\njournalctl -k --since '<time - 5 min>' | tail -20    # OOM or I/O errors"
     },
     "look": "\"failed to update leader lock\", a missing heartbeat, or a crash.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "It keeps failing over",
       "go": "pause"
      }
     ]
    },
    {
     "key": "apps",
     "phase": "cause",
     "t": "Did the apps follow?",
     "why": "Apps that cached the old address, or pools that never reconnect, keep failing after the database is fine.",
     "cmd": {
      "q": "SELECT client_addr, application_name, count(*) FROM pg_stat_activity GROUP BY 1, 2 ORDER BY 3 DESC;",
      "all": "curl -s http://<node>:8008/primary -o /dev/null -w '%{http_code}\\n'   # 200 only on the leader"
     },
     "look": "Apps missing from the new primary: their pools hold dead connections. Restart those pods or services.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "pause",
     "phase": "mitigate",
     "t": "Stop the flapping: pause Patroni",
     "why": "Pausing stops automatic failover while you fix the cause. The current primary stays primary.",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml pause --wait"
     },
     "look": "No new failovers. Remember to resume.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "undo": "patronictl -c /etc/patroni/patroni.yml resume",
     "timebox": "Until the cause is fixed, ideally under an hour"
    },
    {
     "key": "tune",
     "phase": "mitigate",
     "t": "Fix the cause, then tune the timings",
     "why": "If short pauses trigger failovers, the timings are tighter than your infrastructure.",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml edit-config   # ttl, loop_wait, retry_timeout: keep loop_wait + 2*retry_timeout <= ttl"
     },
     "look": "Longer ttl means slower failover but fewer false ones. Pick on purpose.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm a stable cluster",
     "why": "",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml list"
     },
     "look": "One leader, replicas streaming, no new history entries for an hour.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "More than one failover in an hour.",
    "The old primary does not rejoin (see the next playbook)."
   ],
   "call": {
    "when": [
     "Apps did not reconnect after the failover."
    ],
    "ask": [
     "How does your app find the primary: DNS, a VIP, HAProxy, a Kubernetes service?",
     "Do your pools test connections and reconnect on errors?"
    ],
    "suggest": [
     [
      "Test connections before use",
      "Pool settings like testOnBorrow, or a short max lifetime."
     ],
     [
      "Connect with target_session_attrs=read-write",
      "A libpq connection string with all hosts finds the primary itself."
     ]
    ]
   },
   "comms": "PostgreSQL cluster <name> failed over at <time> from <old> to <new>. Writes failed for <n> seconds. Cause: <what>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Timings that match your infrastructure, tested with a planned switchover each quarter.",
     "Maintenance with patronictl pause or switchover, never by stopping the primary."
    ],
    "detect": [
     "Alert on every leader change, with the reason from the logs."
    ],
    "automate": [
     "An agent can collect the Patroni and kernel logs of the old leader and post the reason within a minute of the failover."
    ]
   },
   "done": "One leader for an hour, the old primary back as a replica, and the reason written down.",
   "dont": [
    "Leave the cluster paused after the incident.",
    "Lower ttl to make failovers faster without knowing your longest normal pause."
   ]
  },
  "patroni-rejoin": {
   "group": "patroni",
   "eng": "pg",
   "label": "Patroni",
   "title": "Patroni: the old primary will not rejoin as a replica",
   "see": "After a failover, the old primary shows as stopped or start failed, with errors about timelines or missing WAL.",
   "causes": [
    "It wrote WAL the new primary never received, so its history diverged. It needs pg_rewind.",
    "use_pg_rewind is off, or pg_rewind cannot run (no wal_log_hints or data checksums).",
    "The WAL it needs to catch up is gone from the new primary."
   ],
   "more": "",
   "signals": [
    "patronictl list shows the member stopped or start failed",
    "\"requested timeline is not a child of this server's history\" in the log"
   ],
   "start": "Do not force it. Let Patroni rewind it, and if that cannot work, rebuild it from the new primary.",
   "steps": [
    {
     "key": "st",
     "phase": "confirm",
     "t": "See the member and its error",
     "why": "",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml list\njournalctl -u patroni -n 50 | grep -i -E 'timeline|rewind|wal'"
     },
     "look": "A timeline or rewind error.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "rewind",
     "phase": "mitigate",
     "t": "Let Patroni rewind it",
     "why": "pg_rewind copies back only the blocks that changed. It needs use_pg_rewind and wal_log_hints or checksums.",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml edit-config   # postgresql.use_pg_rewind: true\npatronictl -c /etc/patroni/patroni.yml restart <cluster> <member>"
     },
     "look": "It starts as a replica on the new timeline.",
     "risk": "low",
     "approval": false,
     "branches": [
      {
       "if": "It still fails",
       "go": "reinit"
      }
     ]
    },
    {
     "key": "reinit",
     "phase": "mitigate",
     "t": "Rebuild it from the leader",
     "why": "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.",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml reinit <cluster> <member>"
     },
     "look": "It streams again. Time it.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "None. The old data is replaced."
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm it streams",
     "why": "",
     "cmd": {
      "all": "patronictl -c /etc/patroni/patroni.yml list"
     },
     "look": "Running, the new timeline, lag near zero.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Someone needs the writes the old primary had that never replicated."
   ],
   "call": {
    "when": [
     "Writes were lost in the failover."
    ],
    "ask": [
     "Which writes in the last seconds before <time> matter? Can they be replayed from the app or a queue?"
    ],
    "suggest": [
     [
      "Synchronous mode for data that must not be lost",
      "Patroni synchronous_mode, accepting slower commits."
     ]
    ]
   },
   "comms": "The old primary <node> is being rebuilt as a replica. No user impact; failover protection is reduced until it finishes at about <time>.",
   "postmortem": {
    "prevent": [
     "use_pg_rewind on, and data checksums or wal_log_hints on, in every cluster."
    ],
    "detect": [
     "Alert when a member is not streaming for more than 10 minutes."
    ],
    "automate": [
     "Patroni can reinit by itself with remove_data_directory_on_rewind_failure; decide on purpose whether you want that."
    ]
   },
   "done": "Every member streams on the current timeline.",
   "dont": [
    "Start the old primary by hand outside Patroni."
   ]
  },
  "innodb-quorum": {
   "group": "innodb",
   "eng": "my",
   "label": "MySQL Shell",
   "title": "InnoDB Cluster: lost quorum, or every member is down",
   "see": "Writes hang or fail across the cluster. MySQL Shell reports the cluster has no quorum, or every member is OFFLINE after a power or network event.",
   "causes": [
    "A majority of Group Replication members are unreachable, so the rest cannot decide anything and block writes.",
    "All members restarted (power, maintenance, a bad deploy) and Group Replication does not start itself into a new group.",
    "A network split left no side with a majority."
   ],
   "more": "How Group Replication decides: <a href=\"../lessons/consensus/index.html\">Consensus and leaders</a>.",
   "signals": [
    "cluster.status() says NO_QUORUM or OFFLINE",
    "Writes hang through MySQL Router",
    "replication_group_members shows UNREACHABLE members"
   ],
   "start": "Find out which members are truly down and which are only unreachable. Forcing quorum on the wrong side creates two clusters accepting writes.",
   "steps": [
    {
     "key": "st",
     "phase": "confirm",
     "t": "Cluster and member status",
     "why": "The Shell view and the server view.",
     "cmd": {
      "all": "mysqlsh --js clusteradmin@<node>:3306 -e \"print(dba.getCluster().status({extended: 1}))\"",
      "q": "SELECT MEMBER_HOST, MEMBER_STATE, MEMBER_ROLE FROM performance_schema.replication_group_members;"
     },
     "look": "Read the states.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Some members ONLINE, the rest UNREACHABLE",
       "go": "confirm"
      },
      {
       "if": "Every member OFFLINE or stopped",
       "go": "reboot"
      }
     ]
    },
    {
     "key": "confirm",
     "phase": "cause",
     "t": "Make sure the unreachable members are really down",
     "why": "If they are alive on the other side of a network split, forcing quorum here gives you two primaries.",
     "cmd": {
      "all": "# on each unreachable host, or through your cloud console:\nsystemctl status mysqld\nping <host>"
     },
     "look": "Down for certain: step 3. Alive but cut off: fix the network instead.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "force",
     "phase": "mitigate",
     "t": "Restore quorum from the surviving members",
     "why": "Tells the group to continue with only the members you name.",
     "cmd": {
      "all": "mysqlsh --js clusteradmin@<node>:3306 -e \"dba.getCluster().forceQuorumUsingPartitionOf('<surviving node>:3306')\""
     },
     "look": "Writes resume on the surviving primary.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "Rejoin the other members once they are back (rejoinInstance)."
    },
    {
     "key": "reboot",
     "phase": "mitigate",
     "t": "Start the cluster after a complete outage",
     "why": "Run it on the member with the most transactions (the most complete GTID set). Shell checks and tells you if another member is ahead.",
     "cmd": {
      "all": "mysqlsh --js clusteradmin@<node>:3306 -e \"dba.rebootClusterFromCompleteOutage()\""
     },
     "look": "The cluster is ONLINE with that member as primary; the others rejoin.",
     "risk": "high",
     "approval": true,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm all members are ONLINE",
     "why": "",
     "cmd": {
      "all": "mysqlsh --js clusteradmin@<node>:3306 -e \"print(dba.getCluster().status())\"",
      "q": "SELECT MEMBER_HOST, MEMBER_STATE, MEMBER_ROLE FROM performance_schema.replication_group_members;"
     },
     "look": "Status OK, every member ONLINE.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "You cannot prove the unreachable members are down.",
    "Before forceQuorumUsingPartitionOf or rebootClusterFromCompleteOutage: get a second DBA."
   ],
   "call": {
    "when": [
     "Writes are failing and app owners need a decision on waiting or degrading."
    ],
    "ask": [
     "Can you run read-only? Do you retry writes?"
    ],
    "suggest": [
     [
      "Connect only through MySQL Router",
      "Its read-write port follows the primary."
     ]
    ]
   },
   "comms": "MySQL cluster <name> lost quorum at <time>; writes are failing. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Three or five members across failure zones, never two.",
     "group_replication_unreachable_majority_timeout set, so a minority side gives up instead of hanging.",
     "group_replication_autorejoin_tries so members come back after short splits."
    ],
    "detect": [
     "Alert on any member not ONLINE, and on the cluster status not OK."
    ],
    "automate": [
     "An agent can run cluster.status() on alert and post which members are where, and whether the missing ones answer ping."
    ]
   },
   "done": "Every member ONLINE, status OK, Router routing writes to the primary.",
   "dont": [
    "Force quorum without proving the other side is down.",
    "Run rebootClusterFromCompleteOutage on a member that is behind."
   ]
  },
  "innodb-member": {
   "group": "innodb",
   "eng": "my",
   "label": "MySQL Shell",
   "title": "InnoDB Cluster: a member is in ERROR, expelled, or slowing everyone",
   "see": "One member shows ERROR, RECOVERING for a long time, or was expelled. Or writes on the primary slowed down because one member falls behind (flow control).",
   "causes": [
    "A transaction larger than group_replication_transaction_size_limit, or a long apply, got the member expelled.",
    "Errant transactions: something was written directly on a secondary, so its GTIDs no longer match.",
    "One member has a slower disk or CPU, and flow control throttles the whole group to its speed.",
    "The member was down longer than the others kept binlogs for."
   ],
   "more": "",
   "signals": [
    "A member not ONLINE in cluster.status()",
    "Primary write latency up with low load",
    "Errors mentioning errant GTIDs or flow control"
   ],
   "start": "Find out whether the member is slowing the group (remove it fast) or just missing (rejoin it). Then rejoin, or rebuild it with clone.",
   "steps": [
    {
     "key": "st",
     "phase": "confirm",
     "t": "Member states and queues",
     "why": "Large queues on one member mean it cannot keep up.",
     "cmd": {
      "q": "SELECT m.MEMBER_HOST, m.MEMBER_STATE, s.COUNT_TRANSACTIONS_IN_QUEUE AS certify_queue,\n       s.COUNT_TRANSACTIONS_REMOTE_IN_APPLIER_QUEUE AS apply_queue\nFROM performance_schema.replication_group_members m\nJOIN performance_schema.replication_group_member_stats s USING (MEMBER_ID);",
      "all": "mysqlsh --js clusteradmin@<node>:3306 -e \"print(dba.getCluster().status({extended: 1}))\""
     },
     "look": "Read the states and queues.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "One member's queues keep growing, and writes are slow",
       "go": "remove"
      },
      {
       "if": "A member in ERROR or OFFLINE",
       "go": "why"
      }
     ]
    },
    {
     "key": "why",
     "phase": "cause",
     "t": "Read why it left",
     "why": "The member's error log says expelled, errant GTIDs or a failed recovery.",
     "cmd": {
      "all": "grep -i -E 'group_replication|expel|errant|gtid' /var/log/mysqld.log | tail -30"
     },
     "look": "Errant GTIDs or missing binlogs: rebuild it (step 4).",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "remove",
     "phase": "mitigate",
     "t": "Take the slow member out of the group",
     "why": "Flow control slows every write to the speed of the slowest member. Removing it restores the primary at once.",
     "cmd": {
      "all": "mysqlsh --js clusteradmin@<node>:3306 -e \"dba.getCluster().removeInstance('<slow node>:3306', {force: true})\""
     },
     "look": "Primary write latency recovers.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "addInstance it back once its disk or load is fixed."
    },
    {
     "key": "rejoin",
     "phase": "mitigate",
     "t": "Rejoin it, or rebuild it with clone",
     "why": "rejoinInstance for a member that only fell out. Clone replaces its data with a fresh copy when GTIDs do not match.",
     "cmd": {
      "all": "mysqlsh --js clusteradmin@<node>:3306 -e \"dba.getCluster().rejoinInstance('<node>:3306')\"\n# if that fails:\nmysqlsh --js clusteradmin@<node>:3306 -e \"var c = dba.getCluster(); c.removeInstance('<node>:3306', {force: true}); c.addInstance('<node>:3306', {recoveryMethod: 'clone'})\""
     },
     "look": "The member goes RECOVERING, then ONLINE.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm the group is healthy",
     "why": "",
     "cmd": {
      "q": "SELECT MEMBER_HOST, MEMBER_STATE FROM performance_schema.replication_group_members;"
     },
     "look": "Every member ONLINE, queues near zero.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Errant transactions exist on more than one member.",
    "Removing a member would leave fewer than three."
   ],
   "call": {
    "when": [
     "A big transaction got a member expelled.",
     "Someone wrote directly to a secondary."
    ],
    "ask": [
     "Do you run large batch updates or deletes in one transaction?",
     "Does anything connect to the members directly instead of through Router?"
    ],
    "suggest": [
     [
      "Chunk big writes",
      "Stay well under the transaction size limit (150 MB by default)."
     ],
     [
      "Only connect through Router",
      "And keep super_read_only on secondaries (InnoDB Cluster sets it)."
     ]
    ]
   },
   "comms": "One member of MySQL cluster <name> is <out / slow>. <Writes are affected / not affected.> We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Members with the same instance and disk types.",
     "Big writes in chunks."
    ],
    "detect": [
     "Alert on applier queue size per member and on any member not ONLINE."
    ],
    "automate": [
     "An agent can spot a growing applier queue on one member and propose removing it before flow control hurts the primary."
    ]
   },
   "done": "Every member ONLINE with empty queues.",
   "dont": [
    "Write to a secondary to \"fix\" data.",
    "Reset GTIDs by hand to make a member rejoin."
   ]
  },
  "innodb-router": {
   "group": "innodb",
   "eng": "my",
   "label": "MySQL Router",
   "title": "InnoDB Cluster: the database failed over, but the apps did not",
   "see": "cluster.status() is OK with a new primary, but apps still fail writes or cannot connect.",
   "causes": [
    "Apps connect to a member directly instead of through MySQL Router.",
    "Router cannot read the cluster metadata (its user, network or a stale metadata cache).",
    "Apps use the read-only port for writes, or connection pools keep connections to the old primary."
   ],
   "more": "",
   "signals": [
    "Writes fail with read-only errors after a failover",
    "Router log errors about metadata"
   ],
   "start": "Check what the apps connect to, then what Router thinks the primary is.",
   "steps": [
    {
     "key": "routers",
     "phase": "confirm",
     "t": "List the routers and their view",
     "why": "",
     "cmd": {
      "all": "mysqlsh --js clusteradmin@<node>:3306 -e \"print(dba.getCluster().listRouters())\"\ntail -50 /var/log/mysqlrouter/mysqlrouter.log"
     },
     "look": "Errors fetching metadata, or a router that has not checked in recently.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "ports",
     "phase": "cause",
     "t": "Check which port the app uses",
     "why": "Router listens on 6446 for read-write and 6447 for read-only by default (classic protocol).",
     "cmd": {
      "q": "SELECT user, SUBSTRING_INDEX(host, ':', 1) AS client, count(*)\nFROM information_schema.processlist GROUP BY 1, 2 ORDER BY 3 DESC;"
     },
     "look": "Apps connected straight to the old primary's address bypass Router.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "restart",
     "phase": "mitigate",
     "t": "Restart Router, or the app pools",
     "why": "A restart makes Router reload metadata. Restarting app pods clears pools holding old connections.",
     "cmd": {
      "all": "systemctl restart mysqlrouter\n# or restart the app instances whose pools hold old connections"
     },
     "look": "Writes succeed through 6446.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm writes go to the new primary",
     "why": "",
     "cmd": {
      "q": "SELECT @@hostname, @@read_only, @@super_read_only;"
     },
     "look": "Through port 6446 this returns the primary with read_only = 0.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Apps hardcode member addresses."
   ],
   "call": {
    "when": [
     "Any app connects to a member directly."
    ],
    "ask": [
     "What host and port does your connection string use?",
     "Do pools validate connections?"
    ],
    "suggest": [
     [
      "Router on each app host, or as a sidecar",
      "Apps connect to localhost:6446."
     ],
     [
      "Short connection lifetimes",
      "So pools pick up the new primary."
     ]
    ]
   },
   "comms": "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.",
   "postmortem": {
    "prevent": [
     "All app connections through Router, checked in config review."
    ],
    "detect": [
     "Alert on write errors with \"read-only\" after a primary change."
    ],
    "automate": [
     "A post-failover check that lists clients still connected to the old primary."
    ]
   },
   "done": "All apps write through Router to the new primary.",
   "dont": [
    "Make the old primary writable again to \"help\" the apps."
   ]
  },
  "mongo-noprimary": {
   "group": "mongo",
   "eng": "mo",
   "label": "mongosh",
   "title": "MongoDB replica set: no primary, or elections keep happening",
   "see": "Writes fail with \"not primary\" or NotWritablePrimary errors. rs.status() shows no PRIMARY, or the primary changes every few minutes.",
   "causes": [
    "A majority of voting members are down or unreachable.",
    "Network flaps between members, so heartbeats miss and elections start.",
    "An overloaded primary misses heartbeats.",
    "A PSA set (primary, secondary, arbiter) lost its secondary and is struggling."
   ],
   "more": "Elections and majorities: <a href=\"../lessons/cap/index.html\">CAP as settings you choose</a>.",
   "signals": [
    "NotWritablePrimary errors in apps",
    "rs.status() without a PRIMARY",
    "Log lines \"Starting an election\" repeating"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "st",
     "phase": "confirm",
     "t": "Who is up, and who votes",
     "why": "",
     "cmd": {
      "mo": "rs.status().members.map(m => [m.name, m.stateStr, m.health, m.lastHeartbeatMessage])\nrs.conf().members.map(m => [m.host, m.votes, m.priority, m.arbiterOnly])"
     },
     "look": "Count healthy voters against the total.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "A majority of voters is healthy, but elections repeat",
       "go": "flap"
      },
      {
       "if": "Fewer than a majority healthy",
       "go": "back"
      }
     ]
    },
    {
     "key": "flap",
     "phase": "cause",
     "t": "Why elections keep happening",
     "why": "The logs say which member called the election and why.",
     "cmd": {
      "all": "grep -E 'Starting an election|stepping down|heartbeat' /var/log/mongodb/mongod.log | tail -30"
     },
     "look": "Heartbeat timeouts point at the network or an overloaded primary (see CPU at 100%).",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "back",
     "phase": "mitigate",
     "t": "Bring members back",
     "why": "The safe fix: start them, fix the network. The set elects a primary by itself once a majority sees each other.",
     "cmd": {
      "all": "systemctl status mongod\nsystemctl start mongod"
     },
     "look": "A PRIMARY appears within seconds of a majority.",
     "risk": "low",
     "approval": false,
     "branches": [],
     "timebox": "15 minutes"
    },
    {
     "key": "force",
     "phase": "mitigate",
     "t": "Last resort: force a reconfig with the members you have",
     "why": "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.",
     "cmd": {
      "mo": "cfg = rs.conf()\ncfg.members = cfg.members.filter(m => ['<host1>:27017', '<host2>:27017'].includes(m.host))\nrs.reconfig(cfg, { force: true })"
     },
     "look": "One PRIMARY. Add the others back when they return.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "Reconfig again to add the members back once they are healthy."
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm one stable primary",
     "why": "",
     "cmd": {
      "mo": "rs.status().members.map(m => [m.name, m.stateStr])"
     },
     "look": "One PRIMARY, no new elections for an hour.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Forcing a reconfig.",
    "More than one member thinks it is primary."
   ],
   "call": {
    "when": [
     "Writes are failing and apps need to know whether to retry."
    ],
    "ask": [
     "Which write concern do you use: w: 1 or majority?",
     "Do your drivers have retryable writes on?"
    ],
    "suggest": [
     [
      "w: majority for data that matters",
      "Writes acknowledged by a majority are not rolled back in a failover."
     ],
     [
      "retryWrites=true",
      "Drivers retry once across a failover."
     ]
    ]
   },
   "comms": "MongoDB replica set <name> has no primary since <time>; writes fail. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Three data-bearing members across zones (PSS), not an arbiter.",
     "Members on the same instance type; priorities set on purpose."
    ],
    "detect": [
     "Alert on no primary, and on more than one election an hour."
    ],
    "automate": [
     "An agent can count voters and healthy members on alert and say whether the set can elect by itself."
    ]
   },
   "done": "One primary for an hour, every member healthy.",
   "dont": [
    "Force a reconfig while the old primary might still be taking writes.",
    "Add an arbiter to \"fix\" an even member count when you could add a data-bearing member."
   ]
  },
  "mongo-member": {
   "group": "mongo",
   "eng": "mo",
   "label": "mongosh",
   "title": "MongoDB replica set: a member is stale, or majority writes hang",
   "see": "A secondary is stuck in RECOVERING, or \"too stale to catch up\". Or writes with w: majority hang while w: 1 writes work.",
   "causes": [
    "The secondary was down longer than the oplog window, so the entries it needs are gone.",
    "In a PSA set with the secondary down, the majority commit point cannot move, majority writes wait and cache pressure grows on the primary.",
    "A secondary is too slow to apply, on a slower disk or busy with reads."
   ],
   "more": "",
   "signals": [
    "A member in RECOVERING for a long time",
    "\"too stale to catch up\" in the log",
    "Majority writes time out"
   ],
   "start": "Check the oplog window against how long the member was gone, and whether a majority of data-bearing members is up for majority writes.",
   "steps": [
    {
     "key": "st",
     "phase": "confirm",
     "t": "Member states and oplog window",
     "why": "",
     "cmd": {
      "mo": "rs.printReplicationInfo()            // the oplog window on this member\nrs.printSecondaryReplicationInfo()\nrs.status().members.map(m => [m.name, m.stateStr, m.optimeDate])"
     },
     "look": "Read the states.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "A member is too stale",
       "go": "resync"
      },
      {
       "if": "Majority writes hang with a data-bearing member down",
       "go": "votes"
      }
     ]
    },
    {
     "key": "votes",
     "phase": "mitigate",
     "t": "Stop counting the down member",
     "why": "In a PSA set, set the unavailable secondary to votes 0 and priority 0. The majority then forms without it and majority writes flow.",
     "cmd": {
      "mo": "cfg = rs.conf()\nm = cfg.members.find(x => x.host === '<down host>:27017')\nm.votes = 0; m.priority = 0\nrs.reconfig(cfg)"
     },
     "look": "Majority writes succeed again.",
     "risk": "high",
     "approval": true,
     "branches": [],
     "undo": "Set votes and priority back once the member has caught up."
    },
    {
     "key": "resync",
     "phase": "mitigate",
     "t": "Resync the stale member",
     "why": "Stop it, empty its data directory, start it: it runs an initial sync from another member.",
     "cmd": {
      "all": "systemctl stop mongod\nmv /var/lib/mongodb /var/lib/mongodb.old && mkdir /var/lib/mongodb && chown mongodb: /var/lib/mongodb\nsystemctl start mongod"
     },
     "look": "It goes STARTUP2, then SECONDARY. Initial sync on a big set takes hours.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "oplog",
     "phase": "mitigate",
     "t": "Give the oplog a longer window",
     "why": "So a member can be down longer next time.",
     "cmd": {
      "mo": "db.adminCommand({ replSetResizeOplog: 1, size: <megabytes> })   // on each member"
     },
     "look": "rs.printReplicationInfo() shows a longer window.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm every member is SECONDARY or PRIMARY",
     "why": "",
     "cmd": {
      "mo": "rs.status().members.map(m => [m.name, m.stateStr])"
     },
     "look": "",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "Reconfiguring votes.",
    "Initial sync will take longer than the remaining members can be trusted alone."
   ],
   "call": {
    "when": [
     "Majority writes hang."
    ],
    "ask": [
     "Which collections need w: majority, and which could accept w: 1 for an hour?"
    ],
    "suggest": [
     [
      "Three data-bearing members",
      "So one down member never blocks majority writes."
     ]
    ]
   },
   "comms": "MongoDB replica set <name>: member <host> is <stale / down>. <Majority writes are affected / not affected.> We are <action>.",
   "postmortem": {
    "prevent": [
     "An oplog window of days, not hours.",
     "PSS instead of PSA."
    ],
    "detect": [
     "Alert when the oplog window drops below a threshold, and on members not SECONDARY."
    ],
    "automate": [
     "An agent can compare each member's lag with the oplog window and warn before a member goes stale."
    ]
   },
   "done": "Every member healthy and a comfortable oplog window.",
   "dont": [
    "Delete a member's data while it is the only healthy secondary."
   ]
  },
  "rds-failover": {
   "group": "cloud",
   "eng": null,
   "label": "AWS CLI",
   "title": "RDS or Aurora: a failover happened, or the instance is unavailable",
   "see": "A burst of connection errors, then the database is back with the same endpoint. Or the instance status is not \"available\".",
   "causes": [
    "A Multi-AZ failover: host failure, maintenance, an instance class change, or a reboot with failover.",
    "Aurora promoted a reader after the writer failed.",
    "The instance is in storage-full, incompatible-parameters or rebooting.",
    "Apps cached the old IP from DNS and keep failing after the failover finished."
   ],
   "more": "",
   "signals": [
    "RDS event: \"Multi-AZ instance failover started/completed\"",
    "Connection errors for one or two minutes",
    "Instance status other than available"
   ],
   "start": "Read the RDS events first: they tell you what AWS did and when. Then make sure the apps followed the endpoint.",
   "steps": [
    {
     "key": "ev",
     "phase": "confirm",
     "t": "What AWS did",
     "why": "",
     "cmd": {
      "all": "aws rds describe-events --source-type db-instance --source-identifier <id> --duration 180\naws rds describe-db-instances --db-instance-identifier <id> --query 'DBInstances[0].[DBInstanceStatus,AvailabilityZone,SecondaryAvailabilityZone]'"
     },
     "look": "A failover with its reason, or a status such as storage-full.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Status is storage-full",
       "go": "See The disk is filling up: modify the allocated storage."
      }
     ]
    },
    {
     "key": "aurora",
     "phase": "confirm",
     "t": "Aurora: who is the writer now",
     "why": "",
     "cmd": {
      "all": "aws rds describe-db-clusters --db-cluster-identifier <cluster> --query 'DBClusters[0].DBClusterMembers'"
     },
     "look": "The member with IsClusterWriter true.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "apps",
     "phase": "cause",
     "t": "Did the apps follow the endpoint?",
     "why": "The endpoint name moved; apps that cached the IP, or pools with old connections, keep failing.",
     "cmd": {
      "all": "dig +short <endpoint>   # should resolve to the new writer"
     },
     "look": "Errors continue after the event says completed: restart the app pools.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "pools",
     "phase": "mitigate",
     "t": "Restart the stuck app pools",
     "why": "",
     "cmd": {
      "all": "kubectl rollout restart deployment/<app> -n <ns>"
     },
     "look": "Errors stop.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm available and writable",
     "why": "",
     "cmd": {
      "all": "aws rds describe-db-instances --db-instance-identifier <id> --query 'DBInstances[0].DBInstanceStatus'"
     },
     "look": "available, and the apps' error rates are back to normal.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "The instance is not available after 15 minutes: open an AWS support case at the right severity."
   ],
   "call": {
    "when": [
     "Apps kept failing after the failover completed."
    ],
    "ask": [
     "Does your runtime cache DNS (the JVM does by default)?",
     "Do pools validate connections?"
    ],
    "suggest": [
     [
      "RDS Proxy",
      "It keeps app connections open through a failover."
     ],
     [
      "A short DNS TTL in the runtime",
      "For the JVM, networkaddress.cache.ttl of a few seconds."
     ],
     [
      "The AWS Advanced JDBC Wrapper",
      "It knows the Aurora topology and fails over faster than DNS."
     ]
    ]
   },
   "comms": "Database <name> on RDS failed over at <time> (<reason from the event>). It is available again. <Apps> are <reconnected / being restarted>.",
   "postmortem": {
    "prevent": [
     "RDS Proxy or a topology-aware driver for critical apps.",
     "Maintenance windows set to quiet hours, and reviewed pending maintenance."
    ],
    "detect": [
     "Subscribe to RDS event notifications for failover, low storage and maintenance."
    ],
    "automate": [
     "An agent can read the events on any connection-error alert and post what AWS did."
    ]
   },
   "done": "Available, the apps reconnected, and the reason from the event written down.",
   "dont": [
    "Reboot with failover again to \"fix\" apps that did not reconnect. Fix the apps."
   ]
  },
  "k8s-pod": {
   "group": "cloud",
   "eng": null,
   "label": "kubectl",
   "title": "Kubernetes: the database pod keeps restarting, or will not start",
   "see": "The database pod is in CrashLoopBackOff, keeps restarting, is Pending, or its status shows OOMKilled.",
   "causes": [
    "A liveness probe that times out while the database is busy, so Kubernetes kills a healthy database again and again.",
    "The container memory limit is smaller than what the database is configured to use.",
    "The volume is full.",
    "The pod cannot be scheduled: its volume is in another zone, or no node has room."
   ],
   "more": "",
   "signals": [
    "Restarts count going up",
    "CrashLoopBackOff or OOMKilled",
    "Pod Pending"
   ],
   "start": "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.",
   "steps": [
    {
     "key": "desc",
     "phase": "confirm",
     "t": "Why did it stop?",
     "why": "",
     "cmd": {
      "all": "kubectl get pod <db-pod> -n <ns> -o wide\nkubectl describe pod <db-pod> -n <ns> | grep -A8 -E 'Last State|Events'\nkubectl logs <db-pod> -n <ns> --previous | tail -40"
     },
     "look": "Read the reason.",
     "risk": "read",
     "approval": false,
     "branches": [
      {
       "if": "Liveness probe failed",
       "go": "probe"
      },
      {
       "if": "OOMKilled, exit code 137",
       "go": "mem"
      },
      {
       "if": "Pending",
       "go": "pending"
      },
      {
       "if": "No space left on device",
       "go": "See The disk is filling up, Kubernetes notes."
      }
     ]
    },
    {
     "key": "probe",
     "phase": "mitigate",
     "t": "Stop the probe from killing a busy database",
     "why": "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.",
     "cmd": {
      "all": "kubectl edit <operator resource or statefulset> -n <ns>\n# livenessProbe: timeoutSeconds 10+, failureThreshold 6+; add a startupProbe for recovery"
     },
     "look": "Restarts stop climbing.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "mem",
     "phase": "mitigate",
     "t": "Fit memory to the container",
     "why": "Either raise the limit, or lower the database's memory settings so they fit inside it.",
     "cmd": {
      "all": "kubectl get pod <db-pod> -n <ns> -o jsonpath='{.spec.containers[*].resources.limits.memory}'\n# then change the limit or the database settings in the operator's resource"
     },
     "look": "No more OOMKilled through a peak.",
     "risk": "low",
     "approval": false,
     "branches": []
    },
    {
     "key": "pending",
     "phase": "cause",
     "t": "Why it will not schedule",
     "why": "",
     "cmd": {
      "all": "kubectl describe pod <db-pod> -n <ns> | grep -A10 Events\nkubectl get pvc -n <ns>\nkubectl get pv <pv> -o jsonpath='{.spec.nodeAffinity}'"
     },
     "look": "A volume pinned to a zone with no free node: add capacity in that zone. Do not delete the PVC.",
     "risk": "read",
     "approval": false,
     "branches": []
    },
    {
     "key": "ok",
     "phase": "verify",
     "t": "Confirm the pod is Ready and the cluster healthy",
     "why": "",
     "cmd": {
      "all": "kubectl get pods -n <ns>\nkubectl cnpg status <cluster> -n <ns>    # or the operator's equivalent"
     },
     "look": "Ready, no new restarts for an hour, replicas healthy.",
     "risk": "read",
     "approval": false,
     "branches": []
    }
   ],
   "escalate": [
    "The operator itself is failing to reconcile.",
    "Anyone suggests deleting the PVC or the StatefulSet."
   ],
   "call": {
    "when": [
     "The platform team owns the probes, limits or nodes."
    ],
    "ask": [
     "Who owns this operator and its resource? Which change went out last?",
     "Is there a PodDisruptionBudget, and did a node drain move the pod?"
    ],
    "suggest": [
     [
      "Database-aware probes",
      "Readiness checks the role; liveness is lenient; startupProbe covers recovery."
     ],
     [
      "A PodDisruptionBudget",
      "So node drains never take two members at once."
     ],
     [
      "Guaranteed QoS for databases",
      "Requests equal to limits for memory."
     ]
    ]
   },
   "comms": "Database <name> on Kubernetes is restarting because <reason>. <Impact>. We are <action>. Next update <time>.",
   "postmortem": {
    "prevent": [
     "Probe settings reviewed for every database, with recovery time in mind.",
     "Memory settings derived from the container limit, not the node.",
     "PodDisruptionBudgets for every database cluster."
    ],
    "detect": [
     "Alert on database pod restarts, OOMKilled and Pending."
    ],
    "automate": [
     "An agent can run describe and logs --previous on any database pod restart and post the reason."
    ]
   },
   "done": "The pod is Ready with no new restarts for an hour.",
   "dont": [
    "Delete the PVC or the StatefulSet to \"start fresh\".",
    "Edit config inside the pod: the operator replaces it."
   ]
  }
 }
}