Skip to content

Restic multi-host backup orchestration with a shared repository on AlmaLinux 9

Stand up a fleet that all backs up to one restic repository — locking strategy, prune cadence, host-tagging, and the rules for when to split the repo before it bites you.

You have fifteen production hosts and a fresh restic repository. The first six hosts back up cleanly. On host seven, the nightly job fails with repository is already locked exclusively. You SSH in, run restic unlock, the next night it happens again. The repo has become a coordination problem you didn’t plan for, and you’re about to discover that “fifteen hosts sharing one repo” is a default that scales badly without two specific changes: enforcing client tags, and centralizing prune away from the writer hosts.

What’s happening

A restic repository is content-addressed and deduplicated globally — that’s the whole point. When fifteen hosts back up to the same repo, blocks that exist on multiple hosts are stored exactly once. Disk savings are real, often 60-80% versus per-host repos for similar workloads.

The cost is that the repository has shared state. Specifically:

  • Locks. A restic backup operation takes a non-exclusive lock; prune, forget --prune, and check take an exclusive lock. If two operators or two systemd timers run prune at the same time, one of them fails immediately. Worse: if a writer host loses network mid-backup, it leaves a stale lock that has to be cleared before any other host can run an exclusive operation.

  • Index files. Every backup adds a pack to the index. Reading the index to check what’s already in the repo gets slower as the repo grows. Past about 500 GB of unique data with hundreds of thousands of snapshots, the restic backup step that walks the index can take longer than the actual data transfer.

  • Prune cost. restic prune rewrites packs to reclaim space from deleted snapshots. It reads every pack referenced by a surviving snapshot. On a 2 TB repo, a full prune can take 4+ hours and a lot of egress if you’re pruning from a different host than the storage.

  • Host-to-host blast radius. A misconfigured host that runs forget --keep-last 1 --prune on its own snapshots can take down the lock for hours. A compromised host with the repo password can forget ALL snapshots from ALL hosts. The repo password is a single secret with global authority.

The three rules that make this work at fleet scale:

  1. Every backup is tagged with the host. restic backup --tag host=web01 --tag env=prod /etc /var/lib/.... Forget/prune policies operate on tag filters, not on snapshot IDs, so a host can only target its own snapshots.

  2. No writer host ever runs prune or forget --prune. They only run backup. A dedicated “maintenance” host or container runs forget+prune on a fixed schedule, against tag filters per host.

  3. The repo split criterion is not size, it’s locking contention. When prune duration starts exceeding the gap between scheduled writes, or when stale-lock recovery starts requiring manual intervention more than once a quarter, split the repo. The natural seams are by environment (prod / staging) and by data class (DB / filesystem). Don’t split until you have evidence; per-host repos give away the dedupe benefit for nothing.

How to verify

Check whether host tags are present on every snapshot — a missing tag will hide a host from policy-based forget runs:

restic -r $RESTIC_REPOSITORY snapshots --json \
  | jq -r '.[] | "\(.hostname)\t\(.tags // [] | join(","))\t\(.time)"' \
  | sort | uniq -c | sort -rn | head -30

Every line should include a host=... tag. If you see snapshots from hostnames with no tag, those snapshots are invisible to per-host forget rules and will accumulate indefinitely.

Check current lock state and find stale locks:

restic -r $RESTIC_REPOSITORY list locks
restic -r $RESTIC_REPOSITORY unlock --remove-all  # only when no live operation is running

Time how long an integrity check takes — this is your prune-time floor:

time restic -r $RESTIC_REPOSITORY check --read-data-subset=2%

If this is taking longer than the spacing between your backup runs, you have a coordination problem coming.

The fix

The installer below assumes:

  • A central restic REST server already running at restic.internal:8000 (see restic REST server deploy for that piece).
  • Each writer host runs AlmaLinux 9 and uses systemd timers for the backup job.
  • A separate maintenance host runs the forget+prune job under a different identity.

Save the script as /root/restic-host-setup.sh on each writer host:

#!/usr/bin/env bash
set -euo pipefail

### Restic writer setup for AlmaLinux 9 hosts
### Backs up /etc, /var, /home, /srv to a shared restic REST repository
### Tags every snapshot with host + env so policy-based forget can find it

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER HOST ===
HOST_NAME="$(hostname -s)"
ENV_TAG="prod"                       # prod / staging / dev
REST_SERVER="restic.internal:8000"
REPO_NAME="fleet"                    # path inside REST server
REPO_USER="${HOST_NAME}-writer"
REPO_PASSWORD="CHANGE_ME_REPO_PW"    # password to the restic repo itself
HTTP_BASIC_PW="CHANGE_ME_HTTP_PW"    # HTTP-basic password for this REST user
BACKUP_PATHS=(/etc /var/log /var/lib /home /srv)
EXCLUDES=(
  /var/lib/restic-cache
  /var/lib/docker/overlay2
  /var/log/journal
  /var/cache
  /tmp
  /proc /sys /dev /run
)
# =====================

echo "==> Installing restic"
dnf -y install epel-release
dnf -y install restic ca-certificates curl jq

echo "==> Creating restic identity"
useradd -r -s /sbin/nologin -d /var/lib/restic resticuser 2>/dev/null || true
mkdir -p /var/lib/restic-cache
chown resticuser:resticuser /var/lib/restic-cache
chmod 700 /var/lib/restic-cache

echo "==> Writing environment file"
mkdir -p /etc/restic
cat > /etc/restic/env <<EOF
RESTIC_REPOSITORY=rest:https://${REPO_USER}:${HTTP_BASIC_PW}@${REST_SERVER}/${REPO_NAME}/
RESTIC_PASSWORD=${REPO_PASSWORD}
RESTIC_CACHE_DIR=/var/lib/restic-cache
RESTIC_PACK_SIZE=32
GOMAXPROCS=2
EOF
chown root:resticuser /etc/restic/env
chmod 640 /etc/restic/env

echo "==> Writing excludes file"
cat > /etc/restic/excludes <<EOF
$(printf '%s\n' "${EXCLUDES[@]}")
EOF

echo "==> Writing backup script"
cat > /usr/local/sbin/restic-backup <<BACKUP
#!/usr/bin/env bash
set -euo pipefail
source /etc/restic/env

LOG_TAG="restic-backup[${HOST_NAME}]"
logger -t "\${LOG_TAG}" "starting"

# Tag every snapshot so policy-based forget can target only this host
restic backup \\
  --tag host=${HOST_NAME} \\
  --tag env=${ENV_TAG} \\
  --tag class=filesystem \\
  --exclude-file=/etc/restic/excludes \\
  --one-file-system \\
  --no-scan \\
  --json \\
  ${BACKUP_PATHS[@]} \\
  | tee /var/log/restic-backup.json.log \\
  | jq -rc 'select(.message_type=="summary")
            | "files_new=\\(.files_new) files_changed=\\(.files_changed) data_added=\\(.data_added) total_duration=\\(.total_duration)"' \\
  | logger -t "\${LOG_TAG}"

logger -t "\${LOG_TAG}" "completed"
BACKUP
chmod 750 /usr/local/sbin/restic-backup

echo "==> Writing pre-backup database hook (optional)"
cat > /usr/local/sbin/restic-pre-backup <<'PREHOOK'
#!/usr/bin/env bash
set -euo pipefail
# Place per-host hooks here. Examples:
#  - dump postgres to /var/lib/restic-dumps/
#  - quiesce mysql with a snapshot
#  - export config from a control-plane app
# A no-op default exits 0.
mkdir -p /var/lib/restic-dumps
exit 0
PREHOOK
chmod 750 /usr/local/sbin/restic-pre-backup

echo "==> systemd unit + timer"
cat > /etc/systemd/system/restic-backup.service <<'UNIT'
[Unit]
Description=Restic backup for this host
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
EnvironmentFile=/etc/restic/env
ExecStartPre=/usr/local/sbin/restic-pre-backup
ExecStart=/usr/local/sbin/restic-backup
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7
TimeoutStartSec=4h
# Hard cap: kill if a backup runs longer than this
RuntimeMaxSec=5h
UNIT

cat > /etc/systemd/system/restic-backup.timer <<'TIMER'
[Unit]
Description=Daily restic backup

[Timer]
# Randomized window so 15 hosts don't all hit the repo at 02:00
OnCalendar=*-*-* 02:00:00
RandomizedDelaySec=45m
Persistent=true
Unit=restic-backup.service

[Install]
WantedBy=timers.target
TIMER

systemctl daemon-reload

echo "==> Verifying repository connection (no init — central host inits the repo)"
set +e
runuser -u root -- bash -c 'source /etc/restic/env && restic snapshots --last --no-lock >/dev/null'
RC=$?
set -e
if [[ $RC -ne 0 ]]; then
  echo "WARNING: could not read the repository. Either:"
  echo "  - the REST server is unreachable from this host"
  echo "  - the HTTP-basic credentials are wrong"
  echo "  - the repo has not been initialized yet — run on the maintenance host:"
  echo "      restic -r \$RESTIC_REPOSITORY init"
fi

systemctl enable --now restic-backup.timer

echo
echo "========================================"
echo "DONE — writer host ${HOST_NAME} (${ENV_TAG})"
echo "========================================"
echo
systemctl list-timers restic-backup.timer --no-pager
echo
echo "Manual run for a smoke test:"
echo "  systemctl start restic-backup.service"
echo "  journalctl -u restic-backup.service -f"

Now the maintenance host — a separate VM that owns prune and forget. Save as /root/restic-maint-setup.sh:

#!/usr/bin/env bash
set -euo pipefail

### Restic maintenance host
### Runs forget + prune + check on a fixed cadence
### Operates per-host via tag filters so a bad rule cannot purge another host
### Does NOT take backups itself

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT ===
REST_SERVER="restic.internal:8000"
REPO_NAME="fleet"
MAINT_USER="maintenance"
HTTP_BASIC_PW="CHANGE_ME_HTTP_PW"
REPO_PASSWORD="CHANGE_ME_REPO_PW"
# All known hosts — these MUST match the host=... tag on the writer side
KNOWN_HOSTS=("web01" "web02" "web03" "app01" "app02" "db01" "db02")
RETENTION_POLICY="--keep-daily 14 --keep-weekly 8 --keep-monthly 12"
# ============

dnf -y install epel-release
dnf -y install restic ca-certificates curl jq

mkdir -p /etc/restic /var/lib/restic-cache
cat > /etc/restic/env <<EOF
RESTIC_REPOSITORY=rest:https://${MAINT_USER}:${HTTP_BASIC_PW}@${REST_SERVER}/${REPO_NAME}/
RESTIC_PASSWORD=${REPO_PASSWORD}
RESTIC_CACHE_DIR=/var/lib/restic-cache
EOF
chmod 600 /etc/restic/env

cat > /usr/local/sbin/restic-forget-per-host <<FORGET
#!/usr/bin/env bash
set -euo pipefail
source /etc/restic/env
HOSTS=("\${@}")
if [[ \${#HOSTS[@]} -eq 0 ]]; then
  HOSTS=(${KNOWN_HOSTS[@]})
fi

for h in "\${HOSTS[@]}"; do
  echo "===> forget for host=\${h}"
  restic forget --tag "host=\${h}" \\
    ${RETENTION_POLICY} \\
    --group-by 'paths,tags' \\
    --json | jq -c '.' || true
done

echo "===> prune (single global pass)"
restic prune --max-unused 5% --max-repack-size 50G
FORGET
chmod 750 /usr/local/sbin/restic-forget-per-host

cat > /usr/local/sbin/restic-check <<'CHECK'
#!/usr/bin/env bash
set -euo pipefail
source /etc/restic/env
# Full structural check + sample 2% of data each week
restic check --read-data-subset=2%
CHECK
chmod 750 /usr/local/sbin/restic-check

cat > /etc/systemd/system/restic-forget.service <<'UNIT'
[Unit]
Description=Restic forget + prune (maintenance host only)
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
EnvironmentFile=/etc/restic/env
ExecStart=/usr/local/sbin/restic-forget-per-host
TimeoutStartSec=12h
RuntimeMaxSec=14h
UNIT

cat > /etc/systemd/system/restic-forget.timer <<'TIMER'
[Unit]
Description=Weekly restic forget + prune
[Timer]
OnCalendar=Sun *-*-* 05:00:00
Persistent=true
Unit=restic-forget.service
[Install]
WantedBy=timers.target
TIMER

cat > /etc/systemd/system/restic-check.service <<'UNIT'
[Unit]
Description=Restic integrity check
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
EnvironmentFile=/etc/restic/env
ExecStart=/usr/local/sbin/restic-check
TimeoutStartSec=8h
RuntimeMaxSec=10h
UNIT

cat > /etc/systemd/system/restic-check.timer <<'TIMER'
[Unit]
Description=Weekly restic integrity check
[Timer]
OnCalendar=Wed *-*-* 04:00:00
Persistent=true
Unit=restic-check.service
[Install]
WantedBy=timers.target
TIMER

systemctl daemon-reload
systemctl enable --now restic-forget.timer restic-check.timer

echo
echo "========================================"
echo "Maintenance host configured"
echo "========================================"
echo
echo "Forget runs Sunday 05:00. Check runs Wednesday 04:00."
echo
echo "Initial repo init (run once, by hand, if the repo does not yet exist):"
echo "  source /etc/restic/env && restic init"
echo
echo "Per-host listing:"
echo "  source /etc/restic/env && restic snapshots --tag host=web01"

Run the writer script on every fleet host (edit HOST_NAME/ENV_TAG/BACKUP_PATHS). Run the maintenance script on the dedicated maintenance VM. Initialize the repo from the maintenance host once: source /etc/restic/env && restic init.

A few operational notes that catch teams out the first time:

  • The repo password is fleet-wide. Anyone with it can decrypt every snapshot from every host. Store it in your secret manager (Vault, sealed secrets, 1Password), not in the systemd unit. The script above puts it in /etc/restic/env mode 640; on a real fleet, fetch it at boot from your secret store and write it to tmpfs.

  • Per-host HTTP-basic users in rest-server is what gives you the “host A cannot read host B’s data via the REST endpoint” guarantee at the transport layer. The repo-password authority is still fleet-wide; the HTTP credential limits the path scope.

  • When to split the repo. Track prune duration over 6-8 weeks. When it consistently exceeds 6 hours and the per-host forget step starts colliding with the writer window, split by environment first (fleet-prod / fleet-staging). Production data has compliance retention concerns that staging does not; staging churn pollutes the prune budget of production.

  • Backups of databases go through pre-hooks, not by restic backup-ing a live data directory. Dump first to /var/lib/restic-dumps/, then let restic pick up that directory. The script’s restic-pre-backup is the hook point.


If you’d rather we run the writer fleet + maintenance host + offsite vault as one connected system, our environment management team operates this pattern for managed customers — patching, lock-recovery on-call, and quarterly restore drills included. Start a scoping call and bring your current host count.