PlexichatGuides

Disaster Recovery

Guides, route-group overviews, and live schema entry points for the Plexichat backend.

Disaster recovery guide

This guide describes how to plan and execute disaster recovery for Plexichat. It covers backups, failover, data recovery testing, incident response, and encryption key management.

Overview

A disaster recovery plan keeps Plexichat available after system failures, data corruption, security incidents, or natural disasters. This guide explains how to:

  • Back up and restore data
  • Fail over to secondary systems
  • Test data recovery
  • Respond to incidents
  • Manage key encryption keys (KEKs) and keyrings

Recovery objectives

Recovery time objective (RTO)

Target time to restore services after a disaster:

  • Critical services (API and gateway): 4 hours
  • Non-critical services (admin panel and analytics): 24 hours
  • Full system recovery: 8 hours

Recovery point objective (RPO)

Maximum acceptable data loss:

  • Database: 15 minutes
  • Media files: 1 hour
  • Configuration: 5 minutes

Backup strategy

The Docker Compose stack includes a restic-based backup container (backup service) that runs on a schedule. Restic provides block-level deduplication, encryption, and multiple storage backends.

What Plexichat backs up

Each run creates one encrypted restic snapshot that contains:

Path in snapshot Source Contents
tmp/backup/db/plexichat.sql.gz PostgreSQL via pg_dump All database tables
plexichat-home/ ~/.plexichat volume config.yaml, keyrings, .machine_key
rustfs-data/ RustFS data volume Uploaded media, avatars, attachments

The default schedule is daily at 2 AM. You can change the schedule with BACKUP_SCHEDULE.

Configuration

Set these variables in .env (generated by the deploy script):

BACKUP_RESTIC_PASSWORD=<auto-generated>
BACKUP_SCHEDULE=0 2 * * *
BACKUP_KEEP_DAILY=7
BACKUP_KEEP_WEEKLY=4
BACKUP_KEEP_MONTHLY=6
BACKUP_KEEP_YEARLY=0
BACKUP_INCLUDE_DB=true
BACKUP_INCLUDE_HOME=true
BACKUP_INCLUDE_MEDIA=true
BACKUP_SECONDARY_REPO=
BACKUP_SECONDARY_PASSWORD=

Restore procedures

List available snapshots

docker exec plexichat-backup-1 /scripts/backup.sh list

Restore the database

docker exec plexichat-backup-1 /scripts/backup.sh restore-db latest

To restore a specific snapshot:

docker exec plexichat-backup-1 /scripts/backup.sh restore-db <snapshot-id>

Restore files (config, keyrings, and media)

docker exec plexichat-backup-1 /scripts/backup.sh restore latest /tmp/restore

This restores the entire snapshot to /tmp/restore inside the container. Use docker cp to copy files out or mount a host path into the container.

To restore only specific paths:

docker exec plexichat-backup-1 /scripts/backup.sh restore latest /tmp/restore --include /plexichat-home

Run an ad-hoc backup

docker exec plexichat-backup-1 /scripts/backup.sh run

Secondary and off-site storage

The backup container can replicate to a secondary restic repository. Set BACKUP_SECONDARY_REPO to any restic-compatible target:

Backend Example URI
S3 s3:s3.us-east-1.amazonaws.com/bucket-name
SFTP sftp:user@host:/path
Local /mnt/backup-drive/repo
B2 b2:bucket-name
Rclone rclone:remote:path

Set the corresponding environment variables for the backend (for example, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY for S3). The secondary backup runs independently with its own retention policy.

Retention and pruning

Restic prunes old snapshots after each backup according to BACKUP_KEEP_*. Because restic uses block-level deduplication, keeping daily, weekly, and monthly snapshots for long periods uses only slightly more storage than a single full backup.

Monitoring

Set BACKUP_SUCCESS_HOOK and BACKUP_FAILURE_HOOK to shell commands or webhook URLs for alerting:

BACKUP_FAILURE_HOOK="curl -sf https://hooks.slack.com/... -d'{\"text\":\"Backup failed\"}'"

KEK and keyring considerations

The backup container includes ~/.plexichat/ in every snapshot, which contains .machine_key and keyring files. However:

  • KEKs that you store as environment variables (PLEXICHAT_SYSTEM_KEY, PLEXICHAT_MESSAGE_KEY, PLEXICHAT_MEDIA_KEY) are not inside the restic snapshot. Store them separately in a password manager or secrets manager.
  • For production, use PLEXICHAT_SYSTEM_KEY instead of .machine_key. See the security guide.

Restore on a fresh host

If you lose the primary host, use this procedure:

  1. Deploy a new stack with the deploy script.

  2. Stop services: docker compose down

  3. Restore the restic repository from your secondary or off-site backup.

  4. Restore the snapshot:

    docker compose run --rm backup /scripts/backup.sh restore latest /restore
    
  5. Copy restored files into their volumes.

  6. Restore the database:

    docker compose run --rm backup /scripts/backup.sh restore-db latest
    
  7. Start the stack: docker compose up -d

Disaster scenarios

Scenario 1: Server failure

Symptoms

  • Server is unresponsive
  • You cannot SSH to the host
  • Services are not running

Recovery procedure

  1. Assess impact. Check the monitoring dashboard, identify affected services, and determine user impact.
  2. Attempt recovery. Try a remote reboot, check host status, and review system logs.
  3. Fail over if recovery fails. Promote the standby server, update DNS, and verify services.
  4. Restore the failed server. Reinstall the OS, restore from backup, reconfigure services, and return traffic to the primary when ready.

Scenario 2: Database corruption

Symptoms

  • Database errors in logs
  • Queries fail
  • Data inconsistencies

Recovery procedure

  1. Stop Plexichat:

    sudo systemctl stop plexichat
    
  2. Identify corruption:

    # PostgreSQL
    psql -U plexichat -d plexichat -c "SELECT * FROM pg_stat_database WHERE datname = 'plexichat';"
    
    # SQLite (development)
    sqlite3 ~/.plexichat/data/plexichat.db "PRAGMA integrity_check;"
    
  3. Restore from the restic backup. Prefer the restic restore-db command:

    docker exec plexichat-backup-1 /scripts/backup.sh restore-db latest
    

    For manual restores from a legacy file backup:

    # PostgreSQL
    gunzip < /backups/plexichat-latest.sql.gz | psql -U plexichat plexichat
    
    # SQLite (development)
    cp /backups/plexichat-latest.db ~/.plexichat/data/plexichat.db
    
  4. Verify integrity:

    psql -U plexichat -d plexichat -c "SELECT * FROM pg_stat_database WHERE datname = 'plexichat';"
    
  5. Start Plexichat:

    sudo systemctl start plexichat
    

Scenario 3: Data loss

Symptoms

  • Accidental deletion, malicious activity, or an application bug

Recovery procedure

  1. Identify lost data. Review audit logs, affected tables, and the time of loss.

  2. Restore to a point before the loss:

    # List snapshots and pick one before the loss
    docker exec plexichat-backup-1 /scripts/backup.sh list
    
    # Restore that snapshot
    docker exec plexichat-backup-1 /scripts/backup.sh restore-db <snapshot-id>
    
  3. For PostgreSQL point-in-time recovery with WAL:

    pg_restore -U plexichat -d plexichat --recovery-target-time="2024-01-01 12:30:00" /backups/plexichat-backup
    
  4. Verify data and test application functionality.

Scenario 4: Security incident

Symptoms

  • Unauthorized access, data breach, or malware infection

Recovery procedure

  1. Contain the incident. Isolate affected systems, block malicious IPs, disable compromised accounts, and rotate credentials.
  2. Assess damage. Review access logs, identify compromised data, and document the scope.
  3. Eradicate the threat. Remove malware, patch vulnerabilities, and close gaps.
  4. Recover systems. Restore from a clean backup or rebuild compromised hosts, then harden configuration.
  5. Run a post-incident review. Document lessons learned, update the incident response plan, and train staff.

Failover procedures

Database failover

PostgreSQL streaming replication

Set up a standby:

# On the standby host
sudo -u postgres pg_basebackup -h primary-server -D /var/lib/postgresql/data -P -U replicator -R

Promote the standby:

# On the standby host
sudo -u postgres pg_ctl promote -D /var/lib/postgresql/data

Update Plexichat configuration:

# config/config.yaml
database:
  postgres:
    host: standby-server-ip
    port: 5432

Valkey failover

Valkey Sentinel (Redis-compatible)

Example sentinel.conf:

sentinel monitor mymaster primary-server 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 10000
sentinel parallel-syncs mymaster 1

Sentinel promotes a replica automatically. Plexichat reconnects to the new master.

Note: src/core/database/valkey_client/base.py does not expose Sentinel configuration. You must wire Sentinel integration manually if you use it.

Application failover

Example Nginx upstream with a backup:

upstream plexichat {
    server primary-server:8000 max_fails=3 fail_timeout=30s;
    server standby-server:8000 backup;
}

server {
    location / {
        proxy_pass http://plexichat;
    }
}

For manual failover, update DNS to point to the standby or update the load balancer configuration.

Restoration testing

Backup validation

Automated validation script

#!/bin/bash
# validate-backup.sh

# Restore backup to a test database
createdb plexichat_test
gunzip < /backups/plexichat-latest.sql.gz | psql -U plexichat plexichat_test

# Run integrity checks
psql -U plexichat -d plexichat_test -c "SELECT COUNT(*) FROM users;"
psql -U plexichat -d plexichat_test -c "SELECT COUNT(*) FROM servers;"

# Clean up
dropdb plexichat_test

Schedule

  • Daily automated validation
  • Weekly full restoration test
  • Monthly disaster recovery drill

Disaster recovery drill

Run a drill every quarter:

  1. Plan the drill. Define the scenario, set objectives, assign roles, and schedule the time.
  2. Execute the drill. Simulate the disaster, run recovery procedures, document issues, and measure recovery time.
  3. Review results. Compare RTO and RPO to targets, identify gaps, update procedures, and train staff.

Incident response

Incident response team

  • Incident commander — Coordinates the response
  • Technical lead — Manages technical recovery
  • Communications lead — Manages stakeholder communication
  • Security lead — Handles security aspects

Incident response process

  1. Detection — Monitor alerts, identify the incident, and classify severity.
  2. Containment — Isolate affected systems, prevent spread, and preserve evidence.
  3. Eradication — Remove the threat, patch vulnerabilities, and secure systems.
  4. Recovery — Restore from backup, verify systems, and resume operations.
  5. Post-incident — Document the incident, analyze the root cause, and implement improvements.

Severity levels

Level Meaning Response time RTO
P1 — Critical Complete outage or data breach Immediate 4 hours
P2 — High Partial outage or significant degradation Within 1 hour 8 hours
P3 — Medium Minor degradation with limited impact Within 4 hours 24 hours
P4 — Low Minimal impact or routine issue Within 24 hours 48 hours

KEK migration

When to migrate KEKs

  • A KEK is compromised
  • Regular key rotation (recommended annually)
  • Security policy or compliance changes

Migration procedure

  1. Generate a new KEK:

    export PLEXICHAT_MESSAGE_KEY_NEW=$(openssl rand -base64 32)
    
  2. Run a dry-run migration:

    python -m src.utils.encryption.kek_migration \
      --keyring ~/.plexichat/data/message_keyring.json \
      --new-kek-env PLEXICHAT_MESSAGE_KEY_NEW \
      --dry-run
    
  3. Validate the migration:

    python -m src.utils.encryption.kek_migration \
      --keyring ~/.plexichat/data/message_keyring.json \
      --new-kek-env PLEXICHAT_MESSAGE_KEY_NEW \
      --validate
    
  4. Perform the migration:

    python -m src.utils.encryption.kek_migration \
      --keyring ~/.plexichat/data/message_keyring.json \
      --new-kek-env PLEXICHAT_MESSAGE_KEY_NEW
    
  5. Update the environment variable:

    export PLEXICHAT_MESSAGE_KEY=$PLEXICHAT_MESSAGE_KEY_NEW
    
  6. Roll back if needed:

    python -m src.utils.encryption.kek_migration \
      --rollback \
      --keyring ~/.plexichat/data/message_keyring.json
    

Monitoring and alerting

Health checks

curl https://api.plexichat.com/health

Expected response:

{
  "status": "healthy",
  "database": "connected",
  "valkey": "connected",
  "version": "1.0.0a239"
}

The version comes from src/config_defaults.py.

Monitoring metrics

  • API response time
  • Database connection pool
  • Valkey connection pool
  • WebSocket connections
  • Error rates
  • Disk usage
  • Memory usage

Alerting

Trigger alerts when:

  • API response time exceeds 1 second
  • Error rate exceeds 5%
  • Database or Valkey connections fail
  • Disk usage exceeds 80% or memory usage exceeds 90%

Send alerts to email, Slack, Teams, SMS for critical alerts, or PagerDuty for on-call.

Documentation

Runbook maintenance

Update the runbook when system architecture changes, you add services, or you apply lessons learned.

Review the runbook quarterly and publish a major update annually. Also review it after every incident.

Contact information

Maintain current contacts for:

  • System administrator
  • Database administrator
  • Security team
  • Management
  • Cloud provider support
  • Database support
  • Network provider

Best practices

  • Follow the 3-2-1 rule: keep 3 copies of data on 2 media types with 1 off-site.
  • Encrypt backups. Restic encrypts snapshots at rest.
  • Test restores regularly.
  • Document procedures so any on-call engineer can follow them.
  • Monitor backups and alert on failure.
  • Use least privilege and multi-factor authentication.
  • Enable comprehensive audit logging.
  • Keep systems patched and train staff.

Resources