Skip to content
Plausible Analytics · Chapter 10 of 14 Day 8: Backup and Restore

Day 8: Backup and Restore

Goal: You back up all three parts of Plausible, restore them into a fresh stack, prove that the numbers match and see what happens without the old keys. · Duration: approx. 75 min · Prerequisite: Day 7

Briefing

Plausible spreads its state across three places. A backup is only complete if it contains all three:

Part Where Content Without it
PostgreSQL volume db-data accounts, sites, goals, shields, keys no login
ClickHouse volume event-data all events and sessions empty statistics
.env folder ce SECRET_KEY_BASE, TOTP_VAULT_KEY keys, 2FA useless
  • You do not need the volumes plausible-data (exports, Day 6) and event-logs (ClickHouse logs) for a restore.
  • Copying volumes while the stack is running is not a backup: both databases write constantly. That is why each database gets its own tool: pg_dump for PostgreSQL, BACKUP … TO File(…) for ClickHouse.
  • A backup only counts as a backup once a restore has worked. That is why the day ends on a second stack, not with copying.
 Stack ce (keeps running)                    Stack neu (freshly cloned)
 plausible_db ──pg_dump──► plausible_db.dump ──pg_restore──► plausible_db
 events_db ──BACKUP──► clickhouse/events.zip ──RESTORE──► events_db
 .env ──────────cp──────► env ──────────────────cp──────► .env
                         ~/plausible/tag08

Drill 1: Inventory

Before every backup: what lives where, and which numbers must match again afterwards?

# on argo
docker volume ls --format '{{.Name}}' | grep '^ce_'
sudo sh -c 'du -sh /var/lib/docker/volumes/ce_*/_data'
mkdir -p ~/plausible/tag08
K=$(cat ~/plausible/api-key)
Q='{"site_id":"itdrills.com","date_range":"all",
    "metrics":["visitors","pageviews","events"]}'
curl -s -H "Authorization: Bearer $K" -H 'Content-Type: application/json' \
  https://plausible.lab/api/v2/query -d "$Q" | jq -c '.results[0].metrics' \
  | tee ~/plausible/tag08/vorher.txt

Expected (numbers will differ):

ce_db-data
ce_event-data
ce_event-logs
ce_plausible-data
67M /var/lib/docker/volumes/ce_db-data/_data
6.0M    /var/lib/docker/volumes/ce_event-data/_data
36K /var/lib/docker/volumes/ce_event-logs/_data
3.3M    /var/lib/docker/volumes/ce_plausible-data/_data
[16,47,53]

vorher.txt (“before”) records visitors, pageviews and events over the whole time range. The same query against the new stack must return the same line at the end.

Save your progress? Sign up for free

Drill 2: Backing up PostgreSQL

# on argo
cd ~/plausible/ce
docker compose exec -T plausible_db pg_dump -U postgres -Fc plausible_db \
  > ~/plausible/tag08/plausible_db.dump
ls -lh ~/plausible/tag08/plausible_db.dump | awk '{print $5}'
docker compose exec -T plausible_db pg_restore --list \
  < ~/plausible/tag08/plausible_db.dump | grep -c 'TABLE DATA'

Expected (the size will differ):

195K
50

-Fc produces the compressed custom format. Only with it can pg_restore later pick individual tables and create the database itself (Drill 5). --list reads the dump without restoring anything: a quick test of whether the file is complete.

Save your progress? Sign up for free

Drill 3: Backing up ClickHouse

Break it: The obvious command, directly on the running stack.

# on argo
cd ~/plausible/ce
docker compose exec -T plausible_events_db clickhouse-client --query \
  "BACKUP DATABASE plausible_events_db TO File('/backups/events.zip')" 2>&1 \
  | grep -o "Path '[^']*' is not allowed for backups"

Symptom:

Path '/backups/events.zip' is not allowed for backups

Cause: ClickHouse writes backups only to directories that are allowed in the configuration under backups/allowed_path. Out of the box, none is allowed.

Fix: A configuration snippet for the path /backups/ and a host directory that is mounted there. Inside the container, ClickHouse runs as user 101; the directory must belong to that user.

# on argo
cd ~/plausible/ce
cat > clickhouse-backups.xml <<'EOF'
<clickhouse>
    <backups>
        <allowed_path>/backups/</allowed_path>
    </backups>
</clickhouse>
EOF
sudo install -d -o 101 -g 101 -m 750 ~/plausible/tag08/clickhouse
cat > compose.override.yml <<'EOF'
services:
  plausible:
    ports:
      - 127.0.0.1:8000:8000
  plausible_events_db:
    volumes:
      - ./clickhouse-backups.xml:/etc/clickhouse-server/config.d/backups.xml:ro
      - ~/plausible/tag08/clickhouse:/backups
EOF
docker compose up -d 2>&1 | tail -1
until curl -sf http://127.0.0.1:8000/api/health >/dev/null; do sleep 2; done

Verify:

# on argo
cd ~/plausible/ce
docker compose exec -T plausible_events_db clickhouse-client --query \
  "BACKUP DATABASE plausible_events_db TO File('/backups/events.zip')"
sudo ls -lh ~/plausible/tag08/clickhouse | tail -1 | awk '{print $3, $5, $9}'

Expected (ID and size will differ):

5092d3c4-b451-400b-b5ba-f2b13753cc2a    BACKUP_CREATED
messagebus 2.1M events.zip

A ZIP file with all tables of the database. ClickHouse freezes a consistent state for this while Plausible keeps writing. On the host the file belongs to user 101 – on Ubuntu that user happens to be called messagebus.

Save your progress? Sign up for free

Drill 4: Backing up the keys

# on argo
install -m 600 ~/plausible/ce/.env ~/plausible/tag08/env
cut -d= -f1 ~/plausible/tag08/env
ls -l ~/plausible/tag08/env | awk '{print $1}'

Expected:

BASE_URL
SECRET_KEY_BASE
TOTP_VAULT_KEY
HTTP_PORT
DISABLE_REGISTRATION
-rw-------

The file is small and easily forgotten – yet it is the only part that cannot be regenerated without breaking something (Drill 7). It contains secrets: permissions 600, and wherever the backup goes, it must be stored encrypted.

Save your progress? Sign up for free

Drill 5: Restore onto a fresh stack

A second stack on the same VM plays the new server: its own folder, its own volumes, port 8001. The folder name neu (“new”) becomes the Compose project name – so the two stacks do not get in each other’s way.

# on argo
git clone -q -b v3.2.1 --single-branch \
  https://github.com/plausible/community-edition ~/plausible/neu 2>&1 | grep -v detached
cd ~/plausible/neu
install -m 600 ~/plausible/tag08/env .env
cp ~/plausible/ce/clickhouse-backups.xml .
cat > compose.override.yml <<'EOF'
services:
  plausible:
    ports:
      - 127.0.0.1:8001:8000
  plausible_events_db:
    volumes:
      - ./clickhouse-backups.xml:/etc/clickhouse-server/config.d/backups.xml:ro
      - ~/plausible/tag08/clickhouse:/backups
EOF
docker compose up -d --wait plausible_db plausible_events_db 2>&1 | tail -1

Only the two databases are running – Plausible itself is not yet. Otherwise it would create empty databases at startup, and the restore would hit tables that already exist.

# on argo
cd ~/plausible/neu
docker compose exec -T plausible_db pg_restore -U postgres --create -d postgres \
  < ~/plausible/tag08/plausible_db.dump
docker compose exec -T plausible_events_db clickhouse-client --query \
  "RESTORE DATABASE plausible_events_db FROM File('/backups/events.zip')"
docker compose up -d 2>&1 | tail -1
until curl -sf http://127.0.0.1:8001/api/health >/dev/null; do sleep 2; done
curl -s http://127.0.0.1:8001/api/health; echo

Expected (the ID will differ):

977d3551-cfaf-4373-9e81-fd4909c533d4    RESTORED
 Container neu-plausible-1 Started
{"sessions":"ok","postgres":"ok","clickhouse":"ok","sites_cache":"ok"}

--create creates the database plausible_db from the dump; to do that, it connects to the default database postgres. At startup Plausible runs its migrations – they find everything already in place and do nothing.

Save your progress? Sign up for free

Drill 6: Do the numbers match?

The same query as in Drill 1, with the same API key – this time against the new stack.

# on argo
K=$(cat ~/plausible/api-key)
Q='{"site_id":"itdrills.com","date_range":"all",
    "metrics":["visitors","pageviews","events"]}'
curl -s -H "Authorization: Bearer $K" -H 'Content-Type: application/json' \
  http://127.0.0.1:8001/api/v2/query -d "$Q" | jq -c '.results[0].metrics' \
  > ~/plausible/tag08/nachher.txt
cat ~/plausible/tag08/vorher.txt ~/plausible/tag08/nachher.txt
cmp -s ~/plausible/tag08/vorher.txt ~/plausible/tag08/nachher.txt && echo gleich

Expected (gleich means “same”):

[16,47,53]
[16,47,53]
gleich

The same line twice. The fact that the API key is accepted at all is already half the proof: user, site and key came from PostgreSQL, the numbers from ClickHouse.

Save your progress? Sign up for free

Drill 7: Restore without the old keys

Break it: The .env was not backed up. The colleague simply generates new keys for the new server – the databases are there, after all.

# on argo
cd ~/plausible/neu
sed -i "s|^SECRET_KEY_BASE=.*|SECRET_KEY_BASE=$(openssl rand -base64 48)|" .env
docker compose up -d 2>&1 | tail -1
until curl -sf http://127.0.0.1:8001/api/health >/dev/null; do sleep 2; done

Symptom:

# on argo
K=$(cat ~/plausible/api-key)
Q='{"site_id":"itdrills.com","date_range":"all","metrics":["visitors"]}'
curl -s -H "Authorization: Bearer $K" -H 'Content-Type: application/json' \
  http://127.0.0.1:8001/api/v2/query -d "$Q"; echo

Expected:

{"error":"Invalid API key or site ID. Please make sure you're using a valid API key
with access to the site you've requested."}

Investigate: Is the key in the database at all?

# on argo
cd ~/plausible/neu
K=$(cat ~/plausible/api-key)
echo "Präfix des Keys: ${K:0:6}"
docker compose exec -T plausible_db psql -U postgres -d plausible_db \
  -tAc "select name, key_prefix, length(key_hash) from api_keys"

Expected (Präfix des Keys means “key prefix”):

Präfix des Keys: Ozv356
labor|Ozv356|64

Cause: The key is there, the prefix matches. But Plausible does not store the key itself; it stores a hash of SECRET_KEY_BASE and the key. With a new SECRET_KEY_BASE a different hash comes out, and no key matches any more. By the same principle, the 2FA secrets depend on TOTP_VAULT_KEY, which encrypts them.

Fix and verify: Put the backed-up .env back.

# on argo
cd ~/plausible/neu
install -m 600 ~/plausible/tag08/env .env
docker compose up -d 2>&1 | tail -1
until curl -sf http://127.0.0.1:8001/api/health >/dev/null; do sleep 2; done
K=$(cat ~/plausible/api-key)
Q='{"site_id":"itdrills.com","date_range":"all","metrics":["visitors"]}'
curl -s -H "Authorization: Bearer $K" -H 'Content-Type: application/json' \
  http://127.0.0.1:8001/api/v2/query -d "$Q" | jq -c '.results'

Expected:

[{"metrics":[16],"dimensions":[]}]

Tip: In an emergency you can generate new keys – then all API keys must be created again and 2FA set up again. Better: back up .env along with the rest and also store it in your password manager.

Save your progress? Sign up for free

Exercise: Speed Drills

  1. Show which backups ClickHouse knows about, with status and size. Target time: 45 s
  2. Show how many events the new stack has – directly in ClickHouse. Target time: 30 s

Solution

# on argo
cd ~/plausible/ce
docker compose exec -T plausible_events_db clickhouse-client --query \
  "select name, status, formatReadableSize(total_size) from system.backups
   format TSVRaw"
cd ~/plausible/neu
docker compose exec -T plausible_events_db clickhouse-client -d plausible_events_db \
  --query "select count() from events_v2"

Expected (values will differ):

File('/backups/events.zip') BACKUP_CREATED  2.96 MiB
55

system.backups lists every backup and every restore since the last restart of ClickHouse – with an error message if one fails.

Save your progress? Sign up for free

Checkpoint

# on argo
ls ~/plausible/tag08
sudo ls ~/plausible/tag08/clickhouse
cmp -s ~/plausible/tag08/vorher.txt ~/plausible/tag08/nachher.txt && echo gleich
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8001/api/health

Expected (gleich means “same”):

clickhouse
env
nachher.txt
plausible_db.dump
vorher.txt
events.zip
gleich
200

Challenge

Meanwhile something has gone wrong in the new stack – you want to restore the state from events.zip once more. Show that a second RESTORE fails, and then restore the state cleanly without counting events twice.

Hint: Stop Plausible first, otherwise it writes in the middle of the restore.

Solution

# on argo
cd ~/plausible/neu
docker compose exec -T plausible_events_db clickhouse-client --query \
  "RESTORE DATABASE plausible_events_db FROM File('/backups/events.zip')" 2>&1 \
  | grep -o 'Code: [0-9]*\|already contains some data' | sort -u
docker compose stop plausible 2>&1 | tail -1
docker compose exec -T plausible_events_db clickhouse-client --query \
  "DROP DATABASE plausible_events_db SYNC"
docker compose exec -T plausible_events_db clickhouse-client --query \
  "RESTORE DATABASE plausible_events_db FROM File('/backups/events.zip')" \
  | awk '{print $2}'
docker compose start plausible 2>&1 | tail -1
docker compose exec -T plausible_events_db clickhouse-client -d plausible_events_db \
  --query "select count() from events_v2"

Expected:

Code: 608
already contains some data
 Container neu-plausible-1 Stopped
RESTORED
 Container neu-plausible-1 Started
55

ClickHouse does not restore into tables that already contain data – otherwise every event would be there twice. Drop the database first, then restore: the same number as in the speed drill again.

Save your progress? Sign up for free

Cleanup

The second stack has done its job. You will need the backup in ~/plausible/tag08 and the backup path in the ce stack again on Day 9.

# on argo
cd ~/plausible/neu
docker compose down -v 2>&1 | tail -1
cd ~ && rm -rf ~/plausible/neu
docker volume ls --format '{{.Name}}' | grep -c '^neu_'

Expected:

0

Interview Note

  • What belongs in a complete Plausible backup? PostgreSQL, ClickHouse and the .env with SECRET_KEY_BASE and TOTP_VAULT_KEY.
  • Why not just copy the volumes? Running databases write constantly; a file copy can catch a half-written state. pg_dump and ClickHouse BACKUP deliver a consistent state.
  • What happens without the old SECRET_KEY_BASE? The data is there, but no API key matches any more – keys are stored as a hash with this secret.

Enterprise Note

  • Automate backups: a systemd timer runs pg_dump and BACKUP at night and pushes the files, including .env, encrypted to another location, for example with restic to a storage server or into an S3 bucket.
  • Every run reports to a monitoring system (push monitor, heartbeat). Alerts fire on errors and when the report does not arrive.
  • Rehearse restores regularly, as in Drills 5 and 6 – on a throwaway stack, comparing numbers. A backup that has never been tested is a hope.
  • Location matters: if the backup sits in the same data center as the server, it helps when the server breaks, not when the data center fails.

Contents

More