Skip to content

ZFS replication pipeline: zfs send | zfs receive with bookmarks and retention rotation

Build a hardened incremental ZFS replication pipeline between two hosts — snapshot policy, bookmarks for safe pruning, retention rotation, and the failure modes that bite operators in production.

You inherit a pair of file servers that “replicate to a DR host every night.” When you ask to see the last successful run, the operator points at a cron job that pipes zfs send over SSH to a remote zfs receive. The job runs at 02:00, fails silently when a snapshot is missing on the target, and has been quietly out of sync for eleven days because somebody pruned the wrong snapshot on the source two weeks ago. The first hint of trouble is a DR drill that can’t roll back past last week.

What’s happening

zfs send -i @prev @cur produces an incremental stream that depends on the receiving side still having @prev available. If @prev is destroyed on either side — by manual cleanup, a buggy retention script, or a forced zfs rollback — the next incremental fails with cannot receive incremental stream: most recent snapshot of pool/dataset does not match incremental source. A naive cron-and-pipe pipeline has three structural weaknesses:

  • No common-snapshot resolution. If the source has @2026-05-12 and the target only has @2026-05-10, the pipeline must compute the most recent common snapshot and send from there — most homegrown scripts hard-code @last and break the moment a snapshot is missing.
  • No bookmarks. When you prune @2026-05-12 on the source for space reasons, the matching incremental anchor disappears too. ZFS bookmarks (zfs bookmark, introduced for exactly this case) are lightweight metadata that survive snapshot deletion and let you zfs send -i #bookmark @new without holding the disk space.
  • No idempotent retention. Source and target retention drift apart. The source keeps two weeks, the target keeps three months, but neither knows what the other has. A retention rotation must inspect the other side before pruning.

The dependable pipeline is: take a timestamped snapshot on the source, create a bookmark of it, send incrementally from the previous bookmark, rotate retention with a policy that always preserves at least one common anchor, and alert when the most recent common snapshot is older than a threshold.

How to verify

The single most useful query is “what’s the most recent snapshot that exists on both sides?” Run this from the source host:

SRC_DS=tank/data
TGT_HOST=dr.example.com
TGT_DS=backup/data

src_snaps=$(zfs list -t snapshot -H -o name -s creation -r "$SRC_DS" | awk -F@ '{print $2}' | sort -u)
tgt_snaps=$(ssh "$TGT_HOST" "zfs list -t snapshot -H -o name -s creation -r $TGT_DS" \
            | awk -F@ '{print $2}' | sort -u)

comm -12 <(echo "$src_snaps") <(echo "$tgt_snaps") | tail -1

If that returns nothing, the two sides have diverged completely and you’ll need a full zfs send (no -i) before incrementals can resume. If it returns a snapshot from eleven days ago, the pipeline has been failing silently — find out which day and why.

Inspect bookmarks (not all monitoring tooling shows them):

zfs list -t bookmark -r tank/data
# NAME                       CREATION
# tank/data#2026-05-13_0200  Wed May 13  2:00 2026
# tank/data#2026-05-14_0200  Thu May 14  2:00 2026

If you have no bookmarks at all, you’re depending entirely on snapshots staying alive on both sides — that’s the fragile mode this article fixes.

Finally, confirm the receiver isn’t holding a partial stream:

ssh "$TGT_HOST" zfs get -H -o value receive_resume_token "$TGT_DS"
# - (empty / dash) means no partial in progress

If that returns a long base64 token, a previous zfs send was interrupted mid-stream and the next run must resume it with zfs send -t <token>, not start a fresh incremental.

The fix

The pipeline below replaces an ad-hoc cron job. It runs on the source host out of /usr/local/sbin/zfs-replicate.sh, scheduled by a systemd timer. It uses bookmarks instead of holding source snapshots for replication, resumes partial transfers via receive_resume_token, computes the most recent common anchor on every run (not a stored “last sent” file that can lie), prunes on a tag-aware schedule, and exits non-zero with a clear message on every recoverable failure mode.

Install dependencies on both hosts:

dnf -y install zfs mbuffer pv jq    # AlmaLinux 9 / RHEL 9
# apt-get install -y zfsutils-linux mbuffer pv jq    # Debian / Ubuntu

Create the unprivileged replication user on the target:

useradd -r -m -s /bin/bash zfsrecv
mkdir -p /home/zfsrecv/.ssh
chmod 700 /home/zfsrecv/.ssh
# paste the source root's ed25519 public key, then:
chown -R zfsrecv:zfsrecv /home/zfsrecv/.ssh
chmod 600 /home/zfsrecv/.ssh/authorized_keys

zfs allow -u zfsrecv create,mount,receive,destroy,snapshot,hold,release backup/data

The receiver only gets the ZFS permissions it actually needs — no shell access to anything outside its home, no sudo. The replication script itself runs as root on the source because it needs to read every dataset.

Save the script as /usr/local/sbin/zfs-replicate.sh:

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

### ZFS replication pipeline — source side
### Run via systemd timer on the source host
### Sends tank/data -> backup/data on the DR host
### Uses bookmarks for incremental anchors so source snapshots can be pruned

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

# === EDIT ME ===
SRC_DS="tank/data"
TGT_HOST="dr.example.com"
TGT_USER="zfsrecv"
TGT_DS="backup/data"
SSH_KEY="/root/.ssh/id_ed25519_zfsrepl"
SSH_PORT="22"
LOCK_FILE="/var/run/zfs-replicate-${SRC_DS//\//_}.lock"
LOG_TAG="zfs-replicate[${SRC_DS}]"

# Retention (source side)
KEEP_HOURLY=24
KEEP_DAILY=14
KEEP_WEEKLY=8
KEEP_MONTHLY=12

# Bandwidth cap for the stream (set to "" to disable)
RATE_LIMIT="100M"

# How stale before the alert is loud
MAX_AGE_MINUTES_CRITICAL=180
# ================

log()  { logger -t "$LOG_TAG" -- "$*"; echo "$(date -Is) $*"; }
fail() { log "ERROR: $*"; exit 1; }

# Single instance per source dataset
exec 9>"$LOCK_FILE"
flock -n 9 || fail "another zfs-replicate run is in progress"

SSH="ssh -i $SSH_KEY -p $SSH_PORT -o StrictHostKeyChecking=accept-new \
     -o ServerAliveInterval=30 -o ServerAliveCountMax=4 \
     ${TGT_USER}@${TGT_HOST}"

remote() { $SSH "$@"; }

# --- 1. Verify the target dataset exists ---
if ! remote zfs list -H -o name "$TGT_DS" >/dev/null 2>&1; then
  fail "target dataset $TGT_DS does not exist on $TGT_HOST — bootstrap the initial full send first"
fi

# --- 2. Resume a partial stream if one is pending ---
RESUME_TOK="$(remote zfs get -H -o value receive_resume_token "$TGT_DS" 2>/dev/null || true)"
if [[ -n "$RESUME_TOK" && "$RESUME_TOK" != "-" ]]; then
  log "resuming partial stream via receive_resume_token"
  if [[ -n "$RATE_LIMIT" ]]; then
    zfs send -t "$RESUME_TOK" \
      | mbuffer -q -s 128k -m 256M -r "$RATE_LIMIT" \
      | $SSH "mbuffer -q -s 128k -m 256M | zfs receive -s -F $TGT_DS"
  else
    zfs send -t "$RESUME_TOK" | $SSH "zfs receive -s -F $TGT_DS"
  fi
  log "resume complete; continuing to incremental"
fi

# --- 3. Take today's snapshot ---
TS="$(date +%Y-%m-%d_%H%M)"
NEW_SNAP="${SRC_DS}@${TS}"
zfs snapshot -r "$NEW_SNAP"
log "created snapshot $NEW_SNAP"

# --- 4. Compute the most recent common anchor (snapshot OR bookmark on source, snapshot on target) ---
src_anchors=$( { zfs list -t snapshot -H -o name -s creation -r "$SRC_DS";
                  zfs list -t bookmark -H -o name -s creation -r "$SRC_DS"; } \
              | awk -F'[@#]' '{print $2}' | sort -u )
tgt_snaps=$( remote "zfs list -t snapshot -H -o name -s creation -r $TGT_DS" \
              | awk -F@ '{print $2}' | sort -u )
COMMON=$(comm -12 <(echo "$src_anchors") <(echo "$tgt_snaps") | tail -1 || true)

if [[ -z "$COMMON" ]]; then
  fail "no common snapshot between source and target — manual repair required (full bootstrap or rollback)"
fi
log "common anchor: $COMMON"

# --- 5. Send the incremental ---
SEND_FROM="${SRC_DS}@${COMMON}"
[[ -e "/${SEND_FROM}" ]] || SEND_FROM="${SRC_DS}#${COMMON}"  # fall back to bookmark if snapshot pruned

log "sending ${SEND_FROM} -> ${NEW_SNAP}"
if [[ -n "$RATE_LIMIT" ]]; then
  zfs send -L -e -c -w -I "$SEND_FROM" "$NEW_SNAP" \
    | mbuffer -q -s 128k -m 256M -r "$RATE_LIMIT" \
    | $SSH "mbuffer -q -s 128k -m 256M | zfs receive -s -F $TGT_DS"
else
  zfs send -L -e -c -w -I "$SEND_FROM" "$NEW_SNAP" \
    | $SSH "zfs receive -s -F $TGT_DS"
fi
log "incremental send complete"

# --- 6. Bookmark today's snapshot so we can prune the snapshot later safely ---
zfs bookmark "$NEW_SNAP" "${SRC_DS}#${TS}"
log "bookmarked $NEW_SNAP"

# --- 7. Retention rotation on the source ---
# Tag policy: hourly = HH00 between 00..23, daily = 0200, weekly = Sunday 0200, monthly = day 01 0200
prune_set=()
mapfile -t all_snaps < <(zfs list -t snapshot -H -o name -s creation -r "$SRC_DS")

hourly_count=0; daily_count=0; weekly_count=0; monthly_count=0
# iterate newest-first
for ((i=${#all_snaps[@]}-1; i>=0; i--)); do
  s="${all_snaps[i]}"
  tag="${s##*@}"
  # YYYY-MM-DD_HHMM
  [[ "$tag" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})_([0-9]{2})([0-9]{2})$ ]] || continue
  Y="${BASH_REMATCH[1]}"; M="${BASH_REMATCH[2]}"; D="${BASH_REMATCH[3]}"
  HH="${BASH_REMATCH[4]}"; MM="${BASH_REMATCH[5]}"
  dow=$(date -d "${Y}-${M}-${D}" +%u)
  keep=0
  if (( HH == 2 && MM == 0 && D == "01" )) && (( monthly_count < KEEP_MONTHLY )); then
    keep=1; ((monthly_count++))
  elif (( HH == 2 && MM == 0 && dow == 7 )) && (( weekly_count < KEEP_WEEKLY )); then
    keep=1; ((weekly_count++))
  elif (( HH == 2 && MM == 0 )) && (( daily_count < KEEP_DAILY )); then
    keep=1; ((daily_count++))
  elif (( MM == 0 )) && (( hourly_count < KEEP_HOURLY )); then
    keep=1; ((hourly_count++))
  fi
  if (( keep == 0 )); then
    prune_set+=("$s")
  fi
done

# Always keep the common anchor so the next incremental still works
for s in "${prune_set[@]}"; do
  tag="${s##*@}"
  if [[ "$tag" == "$COMMON" || "$tag" == "$TS" ]]; then continue; fi
  log "pruning source snapshot $s"
  zfs destroy "$s" || log "WARN: could not destroy $s"
done

# --- 8. Bookmark cleanup — keep last 30, drop older ---
mapfile -t all_bms < <(zfs list -t bookmark -H -o name -s creation -r "$SRC_DS")
total=${#all_bms[@]}
if (( total > 30 )); then
  cutoff=$((total - 30))
  for ((i=0; i<cutoff; i++)); do
    log "pruning bookmark ${all_bms[i]}"
    zfs destroy "${all_bms[i]}" || log "WARN: could not destroy ${all_bms[i]}"
  done
fi

# --- 9. Freshness probe on the target ---
last_recv=$(remote "zfs list -t snapshot -H -o name,creation -p -s creation -r $TGT_DS" | tail -1)
last_recv_epoch=$(echo "$last_recv" | awk '{print $2}')
now_epoch=$(date +%s)
age_min=$(( (now_epoch - last_recv_epoch) / 60 ))
log "target latest snapshot age: ${age_min} min"
if (( age_min > MAX_AGE_MINUTES_CRITICAL )); then
  fail "target replication is ${age_min} minutes stale (threshold ${MAX_AGE_MINUTES_CRITICAL})"
fi

log "replication complete: ${SRC_DS}@${TS} -> ${TGT_HOST}:${TGT_DS}"

Make it executable and bootstrap the initial full send manually (one time only):

chmod 700 /usr/local/sbin/zfs-replicate.sh

# On the target, create the parent if needed
ssh zfsrecv@dr.example.com "zfs create -p backup"

# On the source, first full send
zfs snapshot -r tank/data@bootstrap-$(date +%Y%m%d)
zfs send -L -e -c -w -R tank/data@bootstrap-$(date +%Y%m%d) \
  | mbuffer -q -s 128k -m 256M \
  | ssh zfsrecv@dr.example.com "mbuffer -q -s 128k -m 256M | zfs receive -s -F backup/data"
zfs bookmark tank/data@bootstrap-$(date +%Y%m%d) tank/data#bootstrap-$(date +%Y%m%d)

Then install the systemd timer for the recurring runs:

# /etc/systemd/system/zfs-replicate.service
[Unit]
Description=ZFS replication tank/data -> dr.example.com:backup/data
Wants=network-online.target
After=network-online.target zfs.target

[Service]
Type=oneshot
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7
ExecStart=/usr/local/sbin/zfs-replicate.sh
TimeoutStartSec=6h
StandardOutput=journal
StandardError=journal
# /etc/systemd/system/zfs-replicate.timer
[Unit]
Description=Hourly ZFS replication

[Timer]
OnCalendar=hourly
AccuracySec=1min
Persistent=true
RandomizedDelaySec=2min

[Install]
WantedBy=timers.target
systemctl daemon-reload
systemctl enable --now zfs-replicate.timer
systemctl list-timers --all | grep zfs-replicate

Verify the first run, then the second, then sleep for a few hours and verify again — most pipelines that go bad do so on run number two, when the script’s assumption about “yesterday’s snapshot” first meets retention. After that, the failure modes are predictable: target disk fills (alert on zfs list -o avail backup), receive_resume_token stays non-empty for more than two hours (the pipeline is stuck mid-stream), or the most-recent-common-anchor is older than MAX_AGE_MINUTES_CRITICAL. Wire all three into your monitoring stack as separate alerts — they need different responses.

Once a quarter, do a recovery drill: pick a recent snapshot on the DR host, zfs clone backup/data@<tag> backup/restore-test, mount it, and check that the data is what you expect. A replication pipeline that has never been restored from is the same hypothesis it was on day one — the drill is what converts it into evidence.

Stack Harbor runs ZFS replication pipelines like this on customer infrastructure under Managed Cloud Ops, with target-freshness alerts wired into our monitoring plane. If your DR replication has never been tested under load, book a DR readiness review.