- Shell 51%
- Go 47%
- Docker 2%
- Makefile <1%
zfs-backup-service #
Important
Please note that this repo is not ready yet, do not run it in a production environment!
A small Go microservice for snapshotting ZFS datasets and shipping them to
another machine over a private network (intended: a Tailscale tailnet).
Each ZFS node runs its own copy of the service. One curl against the
local service starts a transfer to the remote copy:
curl -XPOST http://localhost:8080/send/peers/<peer id>/snapshot/<snapshot to back up>
Data moves as a plain zfs send stream piped straight through an HTTP POST
body — nothing is buffered on disk, no TLS and no authentication by design
(the service is meant to live inside a tailnet, reachable only from there).
node A (source, send_prefix: "office") node B (target)
┌──────────────────────────────┐ ┌──────────────────────────────┐
│ zfs-backup-service :8080 │ zfs send │ zfs-backup-service :8080 │
│ │ stream │ │
│ POST /send/peers/b/snapshot/ ├────────────►│ POST /receive/office/ │
│ tank/data@snap │ HTTP POST │ tank/data │
│ │ │ (zfs receive) │
│ │ │ stored as │
│ state/b.json: │ │ <receive_target>/office/ │
│ office/tank/data -> snap │ │ tank/data │
└──────────────────────────────┘ └──────────────────────────────┘
AI Disclosure #
This project is written entirely with a locally hosted LLM. All contributions to it in the future may or may not be LLM written.
Requirements #
- Go 1.21+
- OpenZFS 2.2 or newer userspace libraries + headers (the vendored
go-libzfsis patched for the 2.x API — see third_party/go-libzfs/PATCHES.md) - The service runs as root or a normal user — non-root needs the
zfs allowdelegated privileges described in Running as a non-root user - A private network path between the nodes (Tailscale recommended)
Building #
make # normal build (needs the OpenZFS dev packages above)
or directly:
go build -o zfs-backup-service .
Configuration #
Copy config.yaml and edit it. The file is passed via
-config (or the ZFS_BACKUP_CONFIG environment variable; defaults to
config.yaml in the working directory).
# Local address:port for the HTTP API (default ":8080")
listen: ":8080"
# Name of this node; prepended to every dataset it sends, so backups from
# different senders don't collide. Sent as "tank/data" -> the peer stores
# it as "tank/backups/office/tank/data".
send_prefix: "office"
# Dataset root where received backups are stored. Full dataset path
# (pool/name). Incoming backups land below it, under the sender's prefix.
receive_target: "tank/backups"
# Directory for per-peer incremental backup state (default "state")
state_dir: "state"
# Remote nodes. Only `hostname` is required; `port` defaults to 8080.
peers:
office:
hostname: "office.tail1234abcd.ts.net"
home:
hostname: "home.tail1234abcd.ts.net"
port: 9090
| Key | Default | Meaning |
|---|---|---|
listen |
:8080 |
Local HTTP bind address |
send_prefix |
(required) | This node's name, a single dataset component (e.g. office); every dataset it sends is stored under it on the peer — this is what keeps two senders from overwriting each other's tank/data |
receive_target |
(required) | Dataset root for incoming backups, full path pool/name |
state_dir |
state |
Where per-peer incremental state files live |
peers |
— | Map of id -> {hostname, port?}; the id is used in URLs |
The receive target dataset is created at startup if it does not exist yet (the pool must).
Usage #
Back up a dataset (an auto-named snapshot is taken first if you don't name one):
# snapshot of tank/data, auto-named like auto-20260921-024058-1eedd64f
curl -XPOST http://localhost:8080/send/peers/office/snapshot/tank/data
# a specific snapshot (created on demand if it does not exist)
curl -XPOST http://localhost:8080/send/peers/office/snapshot/tank/data@nightly
Successful response:
{
"status": "ok",
"peer": "office",
"dataset": "tank/data",
"remote": "office/tank/data",
"snapshot": "tank/data@auto-20260921-024058-1eedd64f",
"created_snapshot": true,
"incremental": false
}
(remote is where the snapshot is stored on the peer, relative to the
peer's own receive_target.)
Incremental transfers #
After a dataset has been sent to a peer once, the service remembers the
snapshot it sent (per peer, per remote path <send_prefix>/<dataset>, in
<state_dir>/<peer>.json). The next send of the same dataset is
incremental (zfs send -i) from that snapshot. (Changing
send_prefix invalidates the recorded baseline, so the next send is full
again.)
Query parameters (combinable only as noted):
?full=true— force a full (non-incremental) send, e.g. after the target's copies were wiped or moved:curl -XPOST 'http://localhost:8080/send/peers/office/snapshot/tank/data?full=true'?from=<snapshot>— increment from an explicit previous snapshot instead of the recorded state (see Migrating from an existing backup strategy below). When both?from=and?full=trueare given,?from=wins.?recursive=true— send recursively (zfs send -R); the peer stores the whole subtree under itsreceive_target.?raw=true— raw send (zfs send -w); for encrypted datasets — see Encrypted datasets.- If the remembered snapshot no longer exists locally, the service falls back to a full send automatically.
- State is only written after the peer confirmed the transfer (HTTP 2xx);
the response reports the baseline used in
incremental_from, plusrecursive/rawechoing the wire options that were used.
Mirroring an existing zfs send / zfs receive pipeline #
If your current strategy is a classic zfs send -Rwi … | ssh peer 'zfs receive -Fuv …' pipe, the mapping is: -i is the per-peer state by
default (or explicit ?from=), -R is ?recursive=true, -w is
?raw=true, and the receive always runs with -Fuv plus -s (resumable).
The equivalent of your pipeline for one dataset is:
curl -XPOST 'http://localhost:8080/send/peers/office/snapshot/tank/data?recursive=true&raw=true'
Migrating from an existing backup strategy (?from=) #
If the peer already holds backups made by another tool with a different snapshot naming scheme, start the new service incrementally from one of those snapshots instead of sending a full copy again:
# the peer already has tank/data@nightly-2026-09-19 (made by the old tool);
# take a fresh snapshot and send only the delta since nightly-2026-09-19
curl -XPOST 'http://localhost:8080/send/peers/office/snapshot/tank/data?from=nightly-2026-09-19'
The from snapshot must satisfy the usual incremental-receive
requirement: it must exist locally (as the source of zfs send -i) and,
at the same dataset path under the peer's receive_target, on the peer.
The value may be a bare snapshot name (recommended), @name, or
pool/ds@name (rejected unless it is the dataset being sent). ?from=
is a one-shot override: after a successful transfer, the service's state
is updated to the snapshot that was just sent, so subsequent sends
continue incrementally from there with no extra parameters.
Concurrent transfers #
A dataset is snapshotted at most once at a time. While a send of a dataset is in flight:
- a concurrent send of the same dataset to another peer streams the
same snapshot (no second snapshot is taken); each peer gets its own
transfer, its own incremental baseline, and its own state entry. The
joining response reports the shared snapshot with
created_snapshot: false; - a concurrent send of the same dataset to the same peer is refused
with
409— that destination already has a transfer running; - a concurrent send naming a different snapshot of the dataset is
refused with
409(an in-progress snapshot can only be shared).
Different datasets are backed up fully in parallel. The same rules apply
on the receiving side: one receive per destination at a time, concurrent
receives into the same destination get a 409, receives into different
destinations run in parallel. In all cases: retry once the in-progress
transfer completes.
What happens on the receiving side #
The sender POSTs the zfs send stream to the peer's
POST /receive/<prefix>/<dataset path> — the sender's configured
send_prefix is part of the path. The receiver writes the stream into
<receive_target>/<prefix>/<dataset path>, creating the intermediate
datasets as needed. Received datasets are not mounted, and receives
use the resumable flag, so a transfer interrupted by a network drop can
be completed by simply re-running the same send.
The prefix is what prevents collisions: without it, two senders both
backing up tank/data into the same peer would receive into the same
dataset. Give each sender a distinct send_prefix (its node name is the
obvious choice).
The receiving node always applies a fixed policy mirroring a classic
zfs receive -Fuv, plus -s (resumable). Receives are done into the
exact destination path (no -d), so the layout matches a classic
zfs send | zfs receive <path> pipeline: a stream of pool/ds sent by a
node with prefix office lands at receive_target/office/pool/ds, and
recursive streams store the whole subtree there with the source pool name
preserved.
Before receiving, the service prepares the destination to match the
stream — the sender tells the receiver what is coming, via query
parameters on the /receive URL: ?from= (incremental baseline),
?enc=1 (set when the source dataset is encrypted), ?raw=1 (raw
stream), and ?keylocation= (the source's key location; encrypted
sources only):
- Intermediate datasets on the path are created when missing. The destination itself is never pre-created — the stream's own properties, including the source's encryption settings, define the copy.
- Full sends replace the previous copy. Any existing destination is destroyed first, and the receive then creates the destination from the stream's properties.
- Incremental sends are applied in place. The previous copy must exist
with the baseline snapshot and the same encryption state; the service
checks all of that before the transfer starts and fails early with an
actionable error (e.g. "run a full send with
?full=true") instead of discovering it mid-stream.
Note the -F trade-off: if a destination dataset at the same path holds
other data and a non-applicable stream arrives, -F lets the receive
override it. The service assumes receive_target is dedicated to backups.
Encrypted datasets #
What lands on the peer depends on the mode of the send. Only a raw stream carries encryption (the source's key and cipher properties); a non-raw stream of an encrypted dataset is decrypted into cleartext on the sender.
| Send mode | Source dataset | What arrives on the peer |
|---|---|---|
| plain | unencrypted | an unencrypted tree — the plain flow, no extra setup |
| plain | encrypted (key loaded on sender) | an unencrypted copy — a cleartext backup, not a replication of the encryption; no key needed on the peer |
| raw | encrypted (key may be locked) | an encrypted copy with the source's cipher/keyformat — works even with the key locked on the sender |
Caveats:
- An unencrypted source into an encrypted destination tree is
impossible (ZFS forbids unencrypted children under an encrypted
dataset); the service fails fast with an explanation before burning a
transfer. Encrypt the source dataset, or point the peer's
receive_targetat an unencrypted dataset. - An encrypted source into an encrypted destination tree works in any mode.
- The copy of a raw send is left locked, with
keylocationreset toprompt(a key location is never part of a received dataset, and ZFS drops the in-memory key mapping when a non-raw receive ends). Unlock it withzfs load-key -L file:///path/to/key <copy>for a one-off load, or persist it withzfs set keylocation=file:///path/to/key <copy>and plainzfs load-key <copy>. After every peer reboot the key must be loaded again. - Do not mix
?rawand non-raw sends for the same dataset: ZFS refuses a raw incremental after a non-raw receive. Pick one and be consistent per dataset. - A source with
keylocation=promptcan only be sent raw (the service rejects a plain send of such a source with an explanation). - Re-running a full send (
?full=true, or after a prefix change) destroys the previous copy and re-creates it exactly as described for its mode (raw: encrypted, locked,keylocation=prompt; plain: unencrypted). - Receiving an encrypted stream requires the
keylocationpermission on the peer (it is in the standard grant set below).
HTTP API #
| Method & path | Purpose |
|---|---|
POST /send/peers/:peer/snapshot/:dataset[@snap] |
Create (if needed) and send a snapshot to :peer (optional ?from=<snap>, ?full=true) |
POST /receive/:dataset... |
Internal endpoint used by other nodes — receives a snapshot stream |
GET /health |
Liveness probe ({"status":"ok"}) |
GET / |
Service description + configured peers |
Error responses are JSON: {"error": "..."} with the matching status code:
400 (bad request / unknown peer), 404 (dataset or route not found),
409 (a send or receive of that dataset is already in progress),
500 (local ZFS failure), 502 (peer unreachable or rejected the stream).
Dataset names in URLs are validated before any ZFS call and rejected with
a 400: every /-separated component, and any snapshot name, must be
1–255 characters of A-Z, a-z, 0-9, _, ., : or -, and may
not be . or ..; the full destination path must stay within ZFS's
255-character dataset name limit. This is deliberately stricter than
ZFS itself, which also allows spaces in component names — this service
does not use them. The same component rule applies to the send_prefix
and receive_target config values.
Running it #
The service runs on a machine where the target pool is imported. It works as root or as a normal user with the delegated privileges from the next section. A minimal systemd unit (non-root):
[Unit]
Description=zfs-backup-service
After=network-online.target zfs-import.service
Wants=network-online.target
[Service]
ExecStart=/opt/zfs-backup-service/zfs-backup-service -config /opt/zfs-backup-service/config.yaml
Restart=on-failure
User=zfs-backup
[Install]
WantedBy=multi-user.target
(Use User=root instead if you prefer to run it privileged — no
delegated-privilege setup is needed then.)
Running as a non-root user #
All ZFS operations the service performs are covered by a small set of
delegated privileges, so it can run as an ordinary user (the example uses
zfs-backup; any user or group works). Run the following once, as
root, before starting the service.
Prerequisites on the receiving node #
# 1. Create the receive target once. The service never creates top-level
# datasets — everything it creates lives *under* this one.
zfs create tank/backups
# 2. PREREQUISITE: the receive target subtree must stay unmounted.
# The service never mounts (it receives with -u) and never unmounts,
# and a forced overwrite (-F) cannot destroy a mounted dataset.
# canmount=off is hereditary, so this covers every dataset the
# service will create underneath.
zfs set canmount=off tank/backups
# 3. Delegate the privileges the service needs, on the receive target.
# Dataset-level grants are inherited by all child datasets, so this
# covers everything received under it (including recursive -R trees).
zfs allow zfs-backup create,mount,snapshot,receive,destroy,keylocation tank/backups
Why exactly these (OpenZFS 2.3 security-policy checks):
| Permission | Needed for |
|---|---|
receive |
zfs receive itself |
snapshot |
receiving creates snapshots in the destination (incremental receives) |
create |
creating intermediate datasets and the destination before a receive (the check runs on the parent) |
mount |
the create and receive checks require it to be held. It is not used — on Linux a non-root user still cannot actually mount, which is fine because the subtree stays unmounted (step 2) |
destroy |
replacing an existing copy on a full send (the previous backup is destroyed before the receive) |
keylocation |
receiving encrypted streams: the destination's key is set from the source's keylocation, applied as a delayed property after the receive |
No pool-level privilege is needed: the service only touches datasets under
receive_target.
Prerequisites on the sending node #
# Per dataset you back up. The grant is inherited by child datasets, which
# is what makes recursive (?recursive=true, zfs send -R) transfers work.
# (To cover an entire pool: zfs allow zfs-backup snapshot,send tank)
zfs allow zfs-backup snapshot,send tank/data
| Permission | Needed for |
|---|---|
snapshot |
creating the auto-named snapshot (recursively, for -R transfers) |
send |
streaming the snapshot to the peer |
Verifying #
sudo -u zfs-backup zfs allow tank/backups # show the effective grants
sudo -u zfs-backup zfs allow tank/data # (sending node)
The service logs its privilege mode at startup (a notice when it is not running as root), and ZFS permission errors in HTTP responses carry a hint pointing back to this section.
At startup the service also runs a self-check and refuses to start when
it could not possibly work: when /dev/zfs is missing or not accessible,
when the receive target cannot be opened, or — as a non-root user — when
the delegated permissions required for receiving
(receive,snapshot,create,mount,destroy,keylocation) are missing on the
receive target (it prints the exact zfs allow command to fix it).
Operational notes #
- No TLS, no authentication — by design. Anyone who can reach the
listening port can trigger sends and receive streams. The default
:8080bind is0.0.0.0, which also exposes the API on your LAN, not just the tailnet. If that matters, bindlistento your Tailscale interface's IP (e.g.100.x.y.z:8080) or keep the port firewalled. - Long transfers are normal: there is intentionally no HTTP timeout on send/receive requests (only the initial dial is bounded to 15 s).
- Keep the per-node
state_dirstable across restarts; deleting a peer's state file simply makes the next send a full one. - The service keeps the HTTP server alive even if the receive target dataset is missing (it logs a warning and keeps sending to peers); incoming transfers fail with a 500 until the target exists again.
- When running as a non-root user, keep the receive target subtree
unmounted (
canmount=off, see Running as a non-root user) — the service never mounts or unmounts, and a forced overwrite cannot destroy a mounted dataset.
Running in Docker #
The container is a thin client to the host's ZFS kernel module: it
only issues dataset-level ioctls on /dev/zfs and never mounts anything,
so no kernel module and no pool filesystem is needed inside the image —
just the host device passed in and the OpenZFS userspace libraries
(bundled). The host must have the OpenZFS module loaded and the pool
imported.
Prerequisites (on the host, once, as root) #
Identical to Running as a non-root user —
the receive target must exist with canmount=off, and the zfs allow
grants must be in place. The one difference: the grants go to the UID
the container process has on the host, not to a username. With
rootless Docker that is the uid of the user running Docker (or the one set
via user: in the compose file); with --userns-remap it is the mapped
host uid. Verify with docker exec zfs-backup id.
# Receiving node:
zfs create tank/backups
zfs set canmount=off tank/backups
zfs allow <host-uid> create,mount,snapshot,receive,destroy,keylocation tank/backups
# Sending node (per dataset you back up):
zfs allow <host-uid> snapshot,send tank/data
Build and run #
docker build -t zfs-backup-service .
Posture B (default — no root, no extra capabilities): the container
runs as an ordinary user and relies on the delegated privileges above.
The included docker-compose.yml (with config.docker.yaml as the config
example) is set up for this, including a one-shot files-init service
that chowns the state volume for the container's uid (a fresh volume is
root-owned; without that the service cannot save incremental state and
every send silently degrades to a full). user: "1000:1000" must be the
host identity that received the grants:
cp config.docker.yaml config.docker.yaml.local # and edit it
docker compose up -d
or without compose — chown the state volume once, before first start
(same reason as files-init above; uid must match --user below):
docker run --rm --entrypoint chown \
-v zfs-backup-state:/var/lib/zfs-backup \
zfs-backup-service \
-R 1000:1000 /var/lib/zfs-backup
docker run -d --name zfs-backup \
--user 1000:1000 \
--device /dev/zfs \
-v $PWD/config.docker.yaml:/etc/zfs-backup/config.yaml:ro \
-v zfs-backup-state:/var/lib/zfs-backup \
-p 127.0.0.1:8080:8080 \
zfs-backup-service
Posture A (fallback — rootful, CAP_SYS_ADMIN): if you would rather
not set up delegated privileges, run the container as root with
--cap-add SYS_ADMIN (and no --user) instead. The kernel then
authorizes every operation via the capability, and no zfs allow grants
are needed. This works, but note the container's root is the host's
root — it is far less isolated than posture B and is only recommended if
isolation is not a concern.
The startup self-check covers the common container misconfigurations:
a missing --device /dev/zfs, an unusable device, or missing delegated
grants all produce a clear, actionable fatal message at boot (the service
refuses to start rather than serving broken transfers).
Tailscale in the container #
Either run tailscaled as a sidecar container (needs /dev/net/tun and
NET_ADMIN, sharing a network namespace with the service) or run the
service with network_mode: host and tailscaled on the host.
Limitations #
- The container runs the backup service; it does not give you mounted access to the received backups — inspect them on the host.
- The image is built against OpenZFS 2.2 userspace (Ubuntu 24.04 base); the host should run a compatible 2.2+ kernel module.
- Everything else in Operational notes applies unchanged.
Integration testing (e2e) #
The repository ships a self-contained end-to-end rig that exercises the service against the real ZFS kernel of the machine it runs on: two instances of the service (a sender and a receiver) talk to each other over 127.0.0.1 against two small test pools on sparse files ("virtual devices") that cost almost nothing until written. No real disks needed.
See docs/e2e.md for details.
Dependencies #
Per the project constraint, only three third-party modules are used:
github.com/julienschmidt/httprouter— the HTTP router (required)github.com/bicomsystems/go-libzfsv0.4.0 — the ZFS bindings (required). The upstream package is unmaintained and does not compile against modern OpenZFS, so it is vendored inthird_party/go-libzfs/with minimal, documented patches (seethird_party/go-libzfs/PATCHES.md) and wired in via areplacedirective ingo.mod.gopkg.in/yaml.v3— required to parse the YAML config file.
Project layout #
main.go entry point, HTTP server, routes, health/index handlers
config.go YAML config loading + validation
send.go POST /send/... — snapshot + stream a dataset to a peer
receive.go POST /receive/... — accept a stream into receive_target
state.go per-peer incremental state (JSON files)
third_party/ vendored, patched go-libzfs
License #
This project (everything except third_party/) is licensed under the MIT
License — see LICENSE.
third_party/go-libzfs is a vendored, lightly patched copy of
go-libzfs by Faruk Kasumovic,
licensed under the BSD-3-Clause License
(its own license applies to that subtree; local modifications are listed in
third_party/go-libzfs/PATCHES.md).