Operations & disaster recovery
A good backup tool is one you forget about — until the day you need it, when recovery follows a fixed checklist. This page covers both: how to run bakelite so it pages you the moment a backup stops or goes stale, and the exact steps to bring a database back when one is lost or corrupt.
bakelite is built to run two ways, and a healthy deployment uses both:
- Noninteractive — the daemon backs up continuously, and scheduled checks
configured in
[checks]prove the replica is alive and restorable, paging you when it isn't. Set once, then ignore. - Interactive — you inspect (
status,list,usage,doctor) and, on the bad day, restore.
The two operating modes
| Mode | You run | Cadence | Surfaces |
|---|---|---|---|
| Noninteractive | bakelite.service (daemon) | continuous | journald logs, /metrics, status files |
| Noninteractive | bakelite-check.timer | ~5 min | exit code → your alert |
| Noninteractive | [checks] jobs inside the daemon | verify / deep_verify / repair intervals | verify marker, daemon log, heals bit-rot across destinations |
| Interactive | status / list / usage / doctor | on demand | terminal or --json |
| Interactive | restore | on incident | a restored database file |
The daemon: continuous backup
The daemon (bakelite.service) is the engine: it watches each database's -wal
file and ships changes the instant they commit. A healthy daemon produces no output;
the checks below exist to detect when it stops or falls behind, so its absence raises
an alert.
One daemon covers every database on the host, whoever owns it. The packaged
unit runs as the unprivileged bakelite user and replicates each database as its
owner, in one worker process per owner (see
One daemon for every owner).
Leave User=bakelite as shipped. Don't point User= at an app's account, and
don't add a second bakelite unit for another user: if a database should run as
someone other than its owner, set run_as
in the config.
bakelite init configures the unit for you. By
hand, the one thing to set is ReadWritePaths=: list every database
directory (bakelite writes -wal/-shm and a .bakelite/ lock dir there) and,
for a file backend, the backup directory (sudo systemctl edit --full bakelite).
sudo systemctl enable --now bakelite
journalctl -u bakelite -f # watch it bootstrap + back up
The log shows one started worker line per database owner. If a database can't
be replicated, the error names its owner and what to change.
See Configuration for every option and Daemon tuning for the footprint knobs.
Scheduled verification and liveness
The daemon ships backups. Scheduled checks prove they're alive and restorable, and
page you when they're not. You turn them on in bakelite.toml; all are off by
default:
[checks]
liveness = true # let bakelite-check.timer act
max_lag = "10m" # liveness fails if a database's replication lag exceeds this
max_verify_age = "36h" # ...or the last clean verify is older (default: 1.5x `verify`)
verify = "24h" # shallow integrity check, run inside the daemon
deep_verify = "7d" # restore drill, run inside the daemon
repair = "7d" # heal bit-rot across destinations, run inside the daemon
[checks] is a global section, not per-database. Every key is optional; see
Configuration for each.
In-daemon jobs. verify, deep_verify and repair run inside the daemon, per
database, beside its replicator. They run as the database's owner with the daemon's
own backends and credentials, so there is no unit to enable and no ReadWritePaths=
to match. One job runs at a time per daemon process, so a host with many databases
doesn't verify them all at once. Last-run times persist in a per-database
maintenance.json next to the other sidecars, so a restart doesn't re-run jobs
early; a job that came due while the daemon was down, or a database that was never
checked, runs about five minutes after start. A deep verify also counts as a shallow
one. Results land in the verify marker (which status and status --check read) and
in the daemon log.
verifyrunsverify: it checks every stored object's integrity and the change-set lineage chain, and writes the "last verified" marker thatmax_verify_agereads.deep_verifyrunsverify --deep: it additionally restores the latest backup to a temp file and runsPRAGMA integrity_check, the end-to-end proof that the replica is actually restorable. It downloads and replays the full history to rebuild that state, so a weekly interval is plenty. On a large database theintegrity_checkis the slow part (hours of random reads), so it runs at the lowest I/O priority, and it is skipped when the restore is byte-identical to one an earlier deep verify already proved clean: those exact bytes have passed it.repairrunsrepair. It does nothing for a database with a single destination.
Liveness. The one packaged timer, bakelite-check.timer, is installed enabled and
runs every five minutes. It runs
status --check --if-enabled, which exits 0 and does nothing
until liveness = true, then fails if any replica's daemon is stopped, stale, or
backing off, if lag (RPO) exceeds max_lag, or if the last clean verify is older than
max_verify_age. It reads only local status files, cheap enough to run every few
minutes, and it is the one check that catches a fully dead daemon, which no
in-process alerter can. The unit is read-only and needs no per-host drop-in.
The verify marker links the two: the in-daemon jobs prove integrity and stamp the
marker; the check timer gates liveness on the marker's freshness. The bakelite verify,
bakelite verify --deep and bakelite repair commands remain for running by hand.
Alerting is yours to wire. The check unit carries a commented
#OnFailure=notify-failure@%n.service line: create your own notify-failure@.service
(it receives %i = the failed unit) and uncomment it to be paged. Add the same line
to bakelite.service to catch the daemon's own death. A failed in-daemon job is
logged and recorded in the verify marker, so max_verify_age turns it into a liveness
failure.
No systemd? The liveness check runs from cron — but where the file goes (and its
format) depends on the host. The shipped bakelite.cron is the 6-field form: a user
column plus SHELL/PATH/MAILTO lines, the format a system crontab or cron.d drop-in
expects. The one rule to remember: a system crontab or cron.d file carries the user
column; a per-user crontab does not — so drop that column when you install into one.
- Vixie/cronie Linux (Devuan, Gentoo, Void, Slackware-with-cronie) — copy it in verbatim:
sudo cp /usr/share/bakelite/bakelite.cron /etc/cron.d/bakelite sudo "$EDITOR" /etc/cron.d/bakelite # set the user + your alert command - BSD / TrueNAS (FreeBSD, OpenBSD) — there is no
/etc/cron.d/, but the system crontab keeps theusercolumn: append the job line frombakelite.cronto/etc/crontab. Native cron picks them up; nothing to enable. - Alpine / busybox
crond— nocron.dand nousercolumn: drop thebakelitecolumn (leaving the 5-field form), install as/etc/crontabs/bakelite, then enable crond (off by default):sudo rc-update add crond default && sudo rc-service crond start. (See Monitoring without a scraper for the same recipe written out by hand, and the Prometheus metrics if you'd rather scrape.)
What to alert on
Starting points to tighten to your RPO:
| Signal | Default | Means | Do |
|---|---|---|---|
status --check non-zero | — | daemon stopped / stale / backing off | page |
--max-lag exceeded | 10m | RPO breached (replica falling behind) | page if sustained |
--max-verify-age exceeded | 36h | integrity not re-proven recently | page |
| deep verify fails | — | replica is not restorable | page hard |
Scraping Prometheus instead? The equivalents are bakelite_up == 0,
bakelite_replica_lag_seconds > 300, bakelite_backing_off_seconds present, and
bakelite_verify_ok == 0 — see the metrics list. The cron
exit-code path and the metrics read the same status files; use whichever your
monitoring already speaks.
Why exit codes, not a built-in alerter
bakelite deliberately ships exit-code primitives (status --check, verify)
wired to your scheduler, rather than a built-in notifier. Three reasons:
- A backup tool's worst failure is the daemon silently stopping — and an in-process alerter can't fire when its own process is dead. The liveness signal has to come from outside — a cron job or systemd timer.
- Exit codes compose with the alerting you already run — cron mail, systemd
OnFailure=, an Alertmanager probe — instead of adding a second thing to configure. - The in-daemon jobs run the same
verifyyou'd run by hand, on intervals you set, one at a time, so bandwidth use is predictable.
Repair: heal bit-rot across destinations
If you back up a database to more than one destination (two SFTP/SSH servers,
local + S3, two regions), bakelite repair keeps every copy honest. It scans every
backup object on each destination, and where one is corrupt or missing while
another holds a good copy, it rewrites the good copy over the bad one — healing
bit-rot in place, before you ever need to restore.
bakelite repair --db app # heal corrupt/missing copies
bakelite repair --db app --dry-run # report what would be healed, change nothing
bakelite repair # every configured database
It's backend-only and safe to run while the daemon is up — the heal is an
idempotent, byte-for-byte copy of an object that already exists, so it races
nothing. A single-destination database is a no-op (no sibling to heal from), and a
fleet-wide repair skips them cleanly. It exits non-zero if any object is corrupt
on every destination (only a fresh backup can replace it) or if a degraded copy
couldn't be overwritten.
To run it on a schedule, set repair in [checks]:
the daemon then heals each multi-destination database at that interval (weekly, say,
just after the deep verify), and skips single-destination databases.
[checks]
repair = "7d"
Because repair reads every object on every destination (and writes the repairs),
it is off by default and runs one job at a time, so a scheduled heal doesn't compete
with itself for bandwidth.
This complements the automatic recovery on the read path: with 2+
destinations, restore and verify already
validate each object and fall through to a healthy copy when one has rotted (see
Redundancy & bit-rot recovery).
verify flags which destination is rotting; repair is how you fix it.
One caveat: on a WORM / S3-Object-Lock destination the rotted object is immutable,
so repair can't overwrite it — it reports that destination as degraded (the replica
is still restorable from the others) rather than failing.
Inspecting a replica
The read commands are backend-only (no daemon required) and all take --json and
exit non-zero on failure:
status— is replication healthy right now? Lag, state, last error, verify freshness.list— what can I restore to? Restore-point spans (and the full structure with--verbose).usage— what is it costing, and am I near a limit?doctor— will a restore or a config change actually work? Run it before a recovery. Two of its checks are about cost rather than health: object-store hot path warns when a request-priced destination (S3/GCS/Azure) is on thesyncpath with compaction on — every change-set is paid for and then deleted inside the first compaction window — and recommends a localfileprimary with the object store as anasyncmirror; mirror request cost warns when such a mirror has no level floor (min_level = 0), or a floor higher than any configured compaction level, and otherwise states the recovery point the floor buys.
Disaster recovery: restoring a lost database
Work to a checklist. Every step restores to scratch and proves the copy before anything touches production.
- Pre-flight.
bakelite doctor --db app— backend reachable, replica format readable, encryption key loads. Seedoctor. - Pick a restore point.
bakelite list --db appshows restorable UTC spans; paste one into--timestamp, or omit it for the latest state. If this is a corruption incident, restore to a point before it landed — restore is point-in-time, not just "latest". See Choosing a target. - Restore to scratch.
time bakelite restore --db app --output /tmp/dr.db --timestamp '<point>'. Restore walks the lineage chain and verifies each object's hash before writing — a corrupt or substituted object is refused, not applied — then prints what it did:
Restore also runsRestored "app" -> /tmp/dr.db target: 2026-05-30T11:55:03Z -> 2026-05-30T11:55:03Z applied: full backup + 14 incremental change-set(s) ✓ lineage verified: 14/14 change-set(s), hashes match size: 280000 pages x 4096 bytes (1.07 GiB) downloaded: 412.5 MiB ✓ integrity_check: okPRAGMA integrity_checkinternally; it never touches the live database. - Second integrity check, different tool.
sqlite3 /tmp/dr.db 'PRAGMA integrity_check;'— run by sqlite3 rather than bakelite, so a bug in one is less likely to pass both. - App smoke test. Point a throwaway instance at
/tmp/dr.db, run your read-path queries, and spot-check row counts against what you expect. - Swap. Stop the app, replace the database (remove any stale
-wal/-shm), restart, confirm — see Integrity & safe swaps. Then let the daemon take a fresh snapshot of the recovered database.
How long to budget. Restore streams in roughly constant memory and is dominated
by download time on object stores. As a rough guide it runs at hundreds of MB/s
locally (a ~1 GB database in a second or two); measure your own with the time
command above. See How long it takes.
Suspect tampering? Prefer --timestamp <recent> over latest (it resolves
independently of the CURRENT pointer), and check verify for a CURRENT-not-newest
warning. For prevention, see
immutable backups with Object Lock.
Boot-time auto-recovery
On disposable infrastructure, make every boot self-healing: seed the database from the replica when the volume is empty, and no-op otherwise. The guarded restore is safe to run unconditionally on every start:
bakelite restore --db app --if-db-not-exists --if-replica-exists \
--config /etc/bakelite/bakelite.toml
--if-db-not-exists makes it a no-op if the database file already exists (the
steady-state reboot); --if-replica-exists makes it a no-op on a brand-new
deployment with nothing backed up yet. With --output defaulting to the configured
path, it's an in-place restore. See Restore on boot.
A container entrypoint that seeds then runs the app:
#!/bin/sh
set -e
bakelite restore --db app --if-db-not-exists --if-replica-exists \
--config /etc/bakelite/bakelite.toml
exec /usr/local/bin/myappRunning many databases
One daemon replicates thousands of idle databases for well under a tenth of one core. Measured with idle databases on a 16-core Linux x86_64 host, one directory each, a file backend and default settings, summed over the daemon and its workers, once the databases have been idle for ten minutes:
| Databases | Idle CPU (% of a core) | Memory (RSS) | Startup, all replicated |
|---|---|---|---|
| 1 | 0.01 | 31 MiB | 1 s |
| 100 | 0.01 | 48 MiB | 2 s |
| 1,000 | 0.02 | 170 MiB | 20 s |
| 5,000 | 0.04 | 714 MiB | 104 s |
For reference, litestream 0.5.11 on the same host used 0.07%, 4.4%, 40% and 185% of a core at 1, 100, 1,000 and 5,000 databases. Startup costs about 20 ms per database, because databases start one at a time so their first snapshots don't all land at once.
An idle database costs almost nothing between writes. The fallback poll
(safety_poll) is a single stat of the WAL, it backs off
to every 5 minutes (safety_poll_max) while a database stays idle, and the daemon
checks in for all of its databases with one small heartbeat file per process
(heartbeat.<pid>.json in the state directory) instead of rewriting each database's
status file.
Three OS limits grow with the number of databases:
- Open files. About 5 per database (more with a remote backend). The daemon raises
its soft
RLIMIT_NOFILEto the hard limit at startup, and the packaged unit setsLimitNOFILE=1048576. Under a hand-written unit, set it yourself and budget 10 per database. - inotify watches. One per database directory, so 5,000 databases in their own
directories need 5,000 of
fs.inotify.max_user_watches. Databases that share a directory share its watch. - inotify instances. One per daemon or worker process, however many databases
each runs, so the default
fs.inotify.max_user_instancesof 128 is plenty unless other programs use most of it.
bakelite doctor warns when the open-file or watch limit is too low for the
databases in the config. If a limit runs out anyway, the other databases carry on.
The one that hit it shows as backing off in bakelite status, with the limit named,
and recovers on its own once the limit is raised. Without a watcher a database still
replicates, on its safety_poll timer; one that couldn't be opened retries with
backoff. See Too many databases for the OS limits.
Containers
No container image is published. To run bakelite in a container, copy the static binary from a release tarball into your own image; it has no runtime dependencies. bakelite must be able to write each database's directory, so run it as the user that owns the database files, and mount the same volume the app writes to.
For liveness, bakelite status --check works as a Docker HEALTHCHECK or a
Kubernetes probe: it reads only local status files and exits non-zero when the daemon
is stopped, stale, or backing off. Keep --max-lag / --max-verify-age off a
liveness probe (restarting the container can't fix backend lag, so it would only
thrash); put thresholds on a readiness probe or your external alerting. The
[checks] jobs run inside the daemon, so there's nothing else to schedule.
Upgrading
Stop the daemon, install the new package, run doctor, start it again:
sudo systemctl stop bakelite
sudo apt-get update && sudo apt-get install --only-upgrade bakelite
sudo bakelite doctor
sudo systemctl start bakelite
On a tarball install, swap /usr/local/bin/bakelite for the new binary instead of
the apt-get step. doctor confirms the new binary reads the existing replica
format, loads the key, and reaches every backend before the daemon starts.
Nothing in flight is lost. The daemon resumes from its saved position and works out
what's already stored by listing the backend, so a change-set that was mid-upload at
the stop is either there and kept, or sent again. An object written just before the
stop can sit above the latest restore point; restore and resume ignore anything
that isn't part of a complete chain, so it does no harm. For storage-format and
config compatibility across versions, see
Versioning & compatibility, and check the
changelog before a minor (0.x) upgrade.
Advanced: watching request cost
Skip this unless a destination bills per request (R2, S3, GCS, Azure) and the database writes often.
On a request-priced object store — Cloudflare R2 above all, but S3/B2/GCS/Azure too — a write-heavy database's bill is dominated by operations, not bytes. A change-set every second is a PUT every second; each mirror pass is a handful of LISTs. Those are Class A operations, and nothing about them shows up in stored bytes. Three surfaces make them visible before the invoice does.
In status. The daemon counts every request it makes, per destination, and
publishes the tally with the rest of its live status:
DATABASE STATE FRESH SYNCED CHANGES SHIPPED
app watching live 12s 847 4.21 MiB
dest s3://duggan/cube: requests: 1.2k put / 340 list / 12 get
mirror s3://offsite/app: in sync (45s ago)
requests: 180 put / 22 list · throttled (every 4m)
Counts are cumulative for the current daemon run — they reset when it restarts.
--json carries the exact figures.
In /metrics. bakelite_backend_requests_total{database,destination,class}
and bakelite_backend_bytes_total{database,destination,direction} are counters,
so rate() over them is the thing worth graphing and alerting on. An alert at,
say, 0.4 Class A requests/second catches a topology that is on course to spend
past R2's free million a month.
In usage --estimate. The same counters, multiplied by a provider price
table and projected over a month:
bakelite usage --estimate # every database
bakelite usage --estimate --db app --json # one, machine-readable
See usage --estimate for
the flags and the caveats on the built-in prices.
Spending less
If the numbers are higher than you want, in rough order of effect:
- Mirror less of the churn.
min_level = 1on an async mirror skips the L0 change-sets compaction is about to retire anyway. The primary still captures every commit, so local restores keep per-commit granularity; only the mirror's restore points coarsen to compaction granularity. - Skip the manifest on mirrors.
copy_manifest = false. It's an advisory cache restore rebuilds by listing, and the primary rewrites it every few seconds. - Keep the object store off the hot path. A local
syncdestination plus anasyncmirror to the object store costs a fraction of syncing straight to it. - Cap the spend outright.
request_budget = "30k/day"on a mirror stretches that destination's reconcile interval whenever its Class A rate runs over the cap (doubling, up to an hour) and snaps it back when the rate falls.statusshows the destination asthrottledso a mirror that's behind on purpose doesn't read as one that's failing. Sync destinations are never throttled — delaying them would cost recovery point.
See Per-mirror policy for the keys.
See also
- Restore — the full target-selection rules and timing detail.
- Configuration — tuning, encryption, and storage limits.
- Troubleshooting — common errors and what to do about them.