| name | fairdb-emergency-response |
| description | Emergency incident response procedures for critical FairDB issues |
| model | sonnet |
FairDB Emergency Incident Response
You are responding to a critical incident in the FairDB PostgreSQL infrastructure. Follow this structured approach to diagnose, contain, and resolve the issue.
Incident Classification
First, identify the incident type:
- P1 Critical: Complete service outage, data loss risk
- P2 High: Major degradation, affecting multiple customers
- P3 Medium: Single customer impact, performance issues
- P4 Low: Minor issues, cosmetic problems
Initial Assessment (First 5 Minutes)
#!/bin/bash
echo "================================================"
echo " FAIRDB EMERGENCY INCIDENT RESPONSE"
echo " Started: $(date '+%Y-%m-%d %H:%M:%S')"
echo "================================================"
INCIDENT_ID="INC-$(date +%Y%m%d-%H%M%S)"
INCIDENT_LOG="/opt/fairdb/incidents/${INCIDENT_ID}.log"
mkdir -p /opt/fairdb/incidents
{
echo "Incident ID: $INCIDENT_ID"
echo "Response started: $(date)"
echo "Responding user: $(whoami)"
echo "========================================"
} | tee $INCIDENT_LOG
Step 1: Service Status Check
echo -e "\n[STEP 1] SERVICE STATUS CHECK" | tee -a $INCIDENT_LOG
echo "------------------------------" | tee -a $INCIDENT_LOG
if systemctl is-active --quiet postgresql; then
echo "✅ PostgreSQL: RUNNING" | tee -a $INCIDENT_LOG
else
echo "❌ CRITICAL: PostgreSQL is DOWN" | tee -a $INCIDENT_LOG
echo "Attempting emergency restart..." | tee -a $INCIDENT_LOG
sudo systemctl start postgresql 2>&1 | tee -a $INCIDENT_LOG
sleep 5
if systemctl is-active --quiet postgresql; then
echo "✅ PostgreSQL restarted successfully" | tee -a $INCIDENT_LOG
else
echo "❌ FAILED to restart PostgreSQL" | tee -a $INCIDENT_LOG
echo "Checking for port conflicts..." | tee -a $INCIDENT_LOG
sudo netstat -tulpn | grep :5432 | tee -a $INCIDENT_LOG
| -a
-u postgres /usr/lib/postgresql/16/bin/postgres -D /var/lib/postgresql/16/main -C data_directory 2>&1 | -a
-e | -a
-h | grep -E | -a
FULL_DISKS=$( -h | grep -E | -l)
[ -gt 0 ];
| -a
| -a
find /var/log/postgresql -name -mtime +7 -delete 2>/dev/null
find /opt/fairdb/logs -name -mtime +7 -delete 2>/dev/null
| -a
-h | grep -E | -a
Step 2: Connection Diagnostics
echo -e "\n[STEP 2] CONNECTION DIAGNOSTICS" | tee -a $INCIDENT_LOG
echo "--------------------------------" | tee -a $INCIDENT_LOG
echo "Testing local connection..." | tee -a $INCIDENT_LOG
if sudo -u postgres psql -c "SELECT 1;" > /dev/null 2>&1; then
echo "✅ Local connections: OK" | tee -a $INCIDENT_LOG
sudo -u postgres psql -t -c "
SELECT 'Active connections: ' || count(*)
FROM pg_stat_activity
WHERE state != 'idle';" | tee -a $INCIDENT_LOG
MAX_CONN=$(sudo -u postgres psql -t -c "SHOW max_connections;")
CURRENT_CONN=$(sudo -u postgres psql -t -c "SELECT count(*) FROM pg_stat_activity;")
echo "Connections: $CURRENT_CONN / $MAX_CONN" | tee -a $INCIDENT_LOG
if [ $CURRENT_CONN -gt $(( MAX_CONN * 90 / 100 )) ]; then
echo "⚠️ WARNING: Connection pool nearly exhausted" | tee -a $INCIDENT_LOG
| -a
-u postgres psql << | -a
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state =
AND state_change < NOW() - INTERVAL
AND pid != pg_backend_pid();
EOF
| -a
| -a
-50 /var/log/postgresql/postgresql-*. | -a
-e | -a
ip addr show | grep | -a
Step 3: Performance Emergency Response
echo -e "\n[STEP 3] PERFORMANCE TRIAGE" | tee -a $INCIDENT_LOG
echo "----------------------------" | tee -a $INCIDENT_LOG
echo "Checking for blocked/long queries..." | tee -a $INCIDENT_LOG
sudo -u postgres psql << 'EOF' | tee -a $INCIDENT_LOG
-- Queries running longer than 5 minutes
SELECT
pid,
now() - query_start as duration,
state,
LEFT(query, 100) as query_preview
FROM pg_stat_activity
WHERE state != 'idle'
AND now() - query_start > interval '5 minutes'
ORDER BY duration DESC;
-- Kill queries running longer than 30 minutes
SELECT pg_cancel_backend(pid)
FROM pg_stat_activity
WHERE state != 'idle'
AND now() - query_start > interval '30 minutes'
AND pid != pg_backend_pid();
EOF
echo -e "\nChecking for lock conflicts..." | tee -a $INCIDENT_LOG
sudo -u postgres psql << 'EOF' | tee -a $INCIDENT_LOG
SELECT
blocked_locks.pid AS blocked_pid,
blocked_activity.usename AS blocked_user,
blocking_locks.pid AS blocking_pid,
blocking_activity.usename AS blocking_user,
blocked_activity.query AS blocked_statement,
blocking_activity.query AS blocking_statement
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks ON blocking_locks.locktype = blocked_locks.locktype
AND blocking_locks.DATABASE IS NOT DISTINCT FROM blocked_locks.DATABASE
AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.GRANTED;
EOF
Step 4: Data Integrity Check
echo -e "\n[STEP 4] DATA INTEGRITY CHECK" | tee -a $INCIDENT_LOG
echo "------------------------------" | tee -a $INCIDENT_LOG
echo "Checking for corruption indicators..." | tee -a $INCIDENT_LOG
DATA_DIR="/var/lib/postgresql/16/main"
if [ -d "$DATA_DIR" ]; then
echo "Data directory exists: $DATA_DIR" | tee -a $INCIDENT_LOG
if [ -f "$DATA_DIR/recovery.signal" ]; then
echo "⚠️ Recovery in progress!" | tee -a $INCIDENT_LOG
fi
WAL_COUNT=$(ls -1 $DATA_DIR/pg_wal/*.partial 2>/dev/null | wc -l)
if [ $WAL_COUNT -gt 0 ]; then
echo "⚠️ Partial WAL files detected: $WAL_COUNT" | tee -a $INCIDENT_LOG
fi
else
echo "❌ CRITICAL: Data directory not found!" | -a
-e | -a
DB $( -u postgres psql -t -c );
| -a
-u postgres psql -d -c > /dev/null 2>&1
[ $? -eq 0 ];
| -a
| -a
Step 5: Emergency Recovery Actions
echo -e "\n[STEP 5] RECOVERY ACTIONS" | tee -a $INCIDENT_LOG
echo "-------------------------" | tee -a $INCIDENT_LOG
read -p "Do you need to initiate emergency recovery? (yes/no): " NEED_RECOVERY
if [ "$NEED_RECOVERY" = "yes" ]; then
echo "Starting emergency recovery procedures..." | tee -a $INCIDENT_LOG
echo "Option 1: Single-user mode repair" | tee -a $INCIDENT_LOG
echo "Command: sudo -u postgres /usr/lib/postgresql/16/bin/postgres --single -D $DATA_DIR" | tee -a $INCIDENT_LOG
echo "Option 2: Restore from backup" | tee -a $INCIDENT_LOG
if command -v pgbackrest &> /dev/null; then
echo "Available backups:" | tee -a $INCIDENT_LOG
sudo -u postgres pgbackrest --stanza=fairdb info 2>&1 | tee -a $INCIDENT_LOG
fi
| -a
| -a
-p RECOVERY_OPTION
1)
| -a
systemctl stop postgresql
-u postgres /usr/lib/postgresql/16/bin/postgres --single -D
;;
2)
| -a
-p BACKUP_LABEL
systemctl stop postgresql
-u postgres pgbackrest --stanza=fairdb --= restore
systemctl start postgresql
;;
3)
| -a
-p TARGET_TIME
/opt/fairdb/scripts/restore-pitr.sh
;;
*)
| -a
;;
Step 6: Customer Communication
echo -e "\n[STEP 6] CUSTOMER IMPACT ASSESSMENT" | tee -a $INCIDENT_LOG
echo "------------------------------------" | tee -a $INCIDENT_LOG
echo "Affected customer databases:" | tee -a $INCIDENT_LOG
AFFECTED_DBS=$(sudo -u postgres psql -t -c "
SELECT datname FROM pg_database
WHERE datname NOT IN ('postgres', 'template0', 'template1')
ORDER BY datname;")
for DB in $AFFECTED_DBS; do
if sudo -u postgres psql -d $DB -c "SELECT 1;" > /dev/null 2>&1; then
echo " ✅ $DB - Operational" | tee -a $INCIDENT_LOG
else
echo " ❌ $DB - IMPACTED" | tee -a $INCIDENT_LOG
fi
done
cat << EOF | tee -a $INCIDENT_LOG
CUSTOMER NOTIFICATION TEMPLATE
===============================
Subject: FairDB Service Incident - $INCIDENT_ID
Dear Customer,
We are currently experiencing a service incident affecting FairDB PostgreSQL services.
Incident ID: $INCIDENT_ID
Start Time: $(date)
Severity: [P1/P2/P3/P4]
Status: Investigating / Identified / Monitoring / Resolved
Impact:
[Describe customer impact]
Current Actions:
[List recovery actions being taken]
Next Update:
We will provide an update within 30 minutes or sooner if the situation changes.
We apologize for any inconvenience and are working to resolve this as quickly as possible.
For urgent matters, please contact our emergency hotline: [PHONE]
Regards,
FairDB Operations Team
EOF
Step 7: Post-Incident Checklist
echo -e "\n[STEP 7] STABILIZATION CHECKLIST" | tee -a $INCIDENT_LOG
echo "---------------------------------" | tee -a $INCIDENT_LOG
cat << 'EOF' | tee -a $INCIDENT_LOG
Post-Recovery Verification:
[ ] PostgreSQL service running
[ ] All customer databases accessible
[ ] Backup system operational
[ ] Monitoring alerts cleared
[ ] Network connectivity verified
[ ] Disk space adequate (>20% free)
[ ] CPU usage normal (<80%)
[ ] Memory usage normal (<90%)
[ ] No blocking locks
[ ] No long-running queries
[ ] Recent backup available
[ ] Customer access verified
[ ] Incident documented
[ ] Root cause identified
[ ] Prevention plan created
EOF
echo -e "\n[FINAL STATUS]" | tee -a $INCIDENT_LOG
echo "==============" | tee -a $INCIDENT_LOG
/usr/local/bin/fairdb-health-check | head -20 | tee -a $INCIDENT_LOG
Step 8: Root Cause Analysis
echo -e "\n[STEP 8] ROOT CAUSE ANALYSIS" | tee -a $INCIDENT_LOG
echo "-----------------------------" | tee -a $INCIDENT_LOG
echo "Collecting evidence for RCA..." | tee -a $INCIDENT_LOG
echo -e "\nSystem logs (last hour):" | tee -a $INCIDENT_LOG
sudo journalctl --since "1 hour ago" -p err --no-pager | tail -20 | tee -a $INCIDENT_LOG
echo -e "\nPostgreSQL error logs:" | tee -a $INCIDENT_LOG
find /var/log/postgresql -name "*.log" -mmin -60 -exec grep -i "error\|fatal\|panic" {} \; | tail -20 | tee -a $INCIDENT_LOG
echo -e "\nResource usage history:" | tee -a $INCIDENT_LOG
sar -u -f /var/log/sysstat/sa$(date +%d) | tail -10 | tee -a $INCIDENT_LOG 2>/dev/null
cat << EOF | tee /opt/fairdb/incidents/${INCIDENT_ID}-rca.md
# Root Cause Analysis - $INCIDENT_ID
## Incident Summary
- **Date/Time**: $(date)
- **Duration**: [TO BE FILLED]
- **Severity**: [P1/P2/P3/P4]
- **Impact**: [Number of customers/databases affected]
## Timeline
[Document sequence of events]
## Root Cause
[Identify primary cause]
## Contributing Factors
[List any contributing factors]
## Resolution
[Describe how the incident was resolved]
## Lessons Learned
[What was learned from this incident]
## Action Items
[ ] [Prevention measure 1]
[ ] [Prevention measure 2]
[ ] [Monitoring improvement]
## Metrics
- Time to Detection: [minutes]
- Time to Resolution: [minutes]
- Customer Impact Duration: [minutes]
Generated: $(date)
EOF
-e | -a
| -a
| -a
| -a
| -a
| -a
Emergency Contacts
Keep these contacts readily available:
- PostgreSQL Expert: [Contact info]
- Infrastructure Team: [Contact info]
- Customer Success: [Contact info]
- Management Escalation: [Contact info]
Quick Reference Commands
sudo systemctl stop postgresql
sudo systemctl start postgresql
sudo systemctl restart postgresql
sudo -u postgres psql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid != pg_backend_pid();"
sudo -u postgres /usr/lib/postgresql/16/bin/postgres --single -D /var/lib/postgresql/16/main
sudo -u postgres psql -c "CHECKPOINT;"
sudo -u postgres vacuumdb --all --analyze-in-stages
sudo -u postgres /usr/lib/postgresql/16/bin/pg_checksums -D /var/lib/postgresql/16/main --check