Continuous backups to S3
Starts a server that backs itself up to an S3 bucket while it runs: a full, compressed snapshot on a schedule (daily by default), and the write-ahead log archived every five minutes. Together they let you restore the database as it was at any moment covered by the archive, onto this machine or a new one (see the restore-from-s3 recipe). Any S3-compatible store works: AWS S3, MinIO, Cloudflare R2, Backblaze B2, Wasabi, Ceph.
Before you start
- The server binary (see the install recipe).
- A bucket, and an access key that may
s3:PutObject,s3:GetObject,s3:DeleteObject,s3:AbortMultipartUploadands3:ListBucketMultipartUploadson the prefix. - The key in
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY(andAWS_SESSION_TOKENfor temporary credentials). They are read from the environment, never from the command line. - A lifecycle rule on the bucket that aborts incomplete multipart uploads after a few days. The server cleans up after itself, but a server that is killed and never started again cannot.
Settings
| bash variable | PowerShell parameter | Default | What it does |
|---|---|---|---|
RDB_BIN | -RdbBin | rasterizeddb / rasterizeddb.exe | The server binary. |
RDB_DATA | -Data | ./data | The database directory. |
RDB_LISTEN | -Listen | 127.0.0.1 | The address PostgreSQL and the native protocol bind. |
RDB_TLS_CERT, RDB_TLS_KEY | -CertPath, -KeyPath | none | Your certificate for both listeners. |
RDB_S3_BUCKET | -Bucket | required | The bucket. Naming one is what turns backups on (--s3-bucket). |
RDB_S3_PREFIX | -Prefix | rasterizeddb/main | Key prefix in the bucket. One database per prefix: the server refuses to start if the prefix holds another database's backups. |
RDB_S3_REGION | -Region | $AWS_REGION, else us-east-1 | The region requests are signed for. |
RDB_S3_ENDPOINT | -Endpoint | AWS | The store's URL, for MinIO, R2, B2 or Wasabi, for example http://minio.internal:9000. |
RDB_S3_PATH_STYLE=1 | -PathStyle | off | Address the bucket as host/bucket/key. MinIO needs it, and so does a bucket name that is not DNS-safe. |
RDB_S3_SNAPSHOT_SECS | -SnapshotSeconds | 86400 | Seconds between snapshots, measured from the last one in the bucket. 0 takes them only when asked. |
RDB_S3_WAL_FLUSH_SECS | -WalFlushSeconds | 300 | Seconds between log uploads. This is how much recent write history a lost machine can lose. |
RDB_S3_RETAIN | -Retain | 7 | Snapshots kept; older ones, and the log only they needed, are deleted. 0 keeps everything. |
RDB_S3_START_OFFLINE=1 | -StartOffline | off | Start even when the bucket does not answer, holding the log on local disk until it does. Without it, an unreachable bucket stops the start. |
More backup flags exist for compression levels, multipart sizes, rollovers and incremental snapshots; rasterizeddb --help lists every --s3-* flag. Add them to the args line of the script.
Run it
export RASTERIZEDDB_PG_PASSWORD='use-a-long-secret'
export AWS_ACCESS_KEY_ID='…' AWS_SECRET_ACCESS_KEY='…'
RDB_S3_BUCKET=my-backups RDB_S3_PREFIX=prod/main RDB_S3_REGION=eu-central-1 ./setup.sh
# MinIO:
RDB_S3_BUCKET=backups RDB_S3_ENDPOINT=http://minio.internal:9000 RDB_S3_PATH_STYLE=1 ./setup.sh$env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
$env:AWS_ACCESS_KEY_ID = '…'; $env:AWS_SECRET_ACCESS_KEY = '…'
.\setup.ps1 -Bucket my-backups -Prefix prod/main -Region eu-central-1A prefix with no snapshot yet gets its first one as soon as the server starts. For a service that starts at boot, put the same --s3-* flags in the systemd-service or windows-service recipe's extra arguments and the AWS variables in its environment file (Linux) or the runner (Windows).
Check that it works
export PGPASSWORD='use-a-long-secret'
psql "postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require" -c "SHOW BACKUP STATUS"
psql "postgresql://rasterized@127.0.0.1:5432/postgres?sslmode=require" -c "SHOW BACKUPS"SHOW BACKUP STATUS reports configured as true and counts the snapshots. SHOW BACKUPS lists one row per snapshot and per uploaded bundle of log.
You can also back up on demand:
BACKUP DATABASE; -- a snapshot now, then the log, so it is restorable at once
BACKUP WAL; -- upload the log up to this moment: a point you can restore to
BACKUP PRUNE; -- apply the retention nowA backup nobody has restored is a hope. Restore into a scratch directory now and then (the restore-from-s3 recipe's verify mode) and query the copy.
Stop or undo
Ctrl+C stops the server cleanly; it uploads the log once more on the way out. To stop backing up, start the server without --s3-bucket. The bucket keeps what was uploaded; delete the prefix in the bucket to remove the backups.
Limits
--s3-wal-flush-secsis the recovery point: with the default, losing the machine can lose up to five minutes of commits. Lower it for less; each flush costs two requests.- A restore to a time stops at the last log upload at or before that time. For an exact point, restore to a commit sequence number (
--restore-at-lsn). - Tables kept on a key/value store, rather than in files, are restored as of the snapshot that copied them: they have no log to replay.
- If uploads keep failing, staged log piles up on local disk until
--s3-staging-max-mb(4096 by default). Past that, point-in-time recovery is suspended rather than the disk filling.
The files
#!/usr/bin/env bash
# RasterizedDB with continuous backups to S3 (or any S3-compatible store):
# a full snapshot on a schedule, the write-ahead log archived every few
# minutes, so the database can be restored to any point in between.
# Runs in the foreground.
#
# Every setting can be overridden from the environment, for example:
# RDB_S3_BUCKET=my-backups RDB_S3_PREFIX=prod/main ./setup.sh
# RDB_S3_BUCKET=backups RDB_S3_ENDPOINT=http://minio.internal:9000 RDB_S3_PATH_STYLE=1 ./setup.sh
set -euo pipefail
RDB_BIN="${RDB_BIN:-rasterizeddb}"
RDB_DATA="${RDB_DATA:-./data}"
RDB_LISTEN="${RDB_LISTEN:-127.0.0.1}"
RDB_TLS_CERT="${RDB_TLS_CERT:-}"
RDB_TLS_KEY="${RDB_TLS_KEY:-}"
RDB_S3_BUCKET="${RDB_S3_BUCKET:-}" # required
RDB_S3_PREFIX="${RDB_S3_PREFIX:-rasterizeddb/main}" # one database per prefix
RDB_S3_REGION="${RDB_S3_REGION:-${AWS_REGION:-us-east-1}}"
RDB_S3_ENDPOINT="${RDB_S3_ENDPOINT:-}" # MinIO, R2, B2, Wasabi…; empty for AWS
RDB_S3_PATH_STYLE="${RDB_S3_PATH_STYLE:-0}" # 1 for MinIO and non-DNS-safe bucket names
RDB_S3_SNAPSHOT_SECS="${RDB_S3_SNAPSHOT_SECS:-86400}" # a full snapshot daily
RDB_S3_WAL_FLUSH_SECS="${RDB_S3_WAL_FLUSH_SECS:-300}" # the most write history a lost host can lose
RDB_S3_RETAIN="${RDB_S3_RETAIN:-7}" # snapshots kept; 0 keeps all
RDB_S3_START_OFFLINE="${RDB_S3_START_OFFLINE:-0}" # 1 starts even when the bucket does not answer
die() { echo "error: $*" >&2; exit 1; }
command -v "$RDB_BIN" >/dev/null 2>&1 || die "'$RDB_BIN' not found; set RDB_BIN to the server binary"
[ -n "$RDB_S3_BUCKET" ] || die "set RDB_S3_BUCKET to the bucket to back up into"
: "${RASTERIZEDDB_PG_PASSWORD:?set RASTERIZEDDB_PG_PASSWORD to the password for the role rasterized}"
: "${AWS_ACCESS_KEY_ID:?set AWS_ACCESS_KEY_ID for the bucket}"
: "${AWS_SECRET_ACCESS_KEY:?set AWS_SECRET_ACCESS_KEY for the bucket}"
export RASTERIZEDDB_PG_PASSWORD AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
mkdir -p "$RDB_DATA"
RDB_DATA="$(cd "$RDB_DATA" && pwd)"
args=(--location "$RDB_DATA" --protocol both --pg-addr "$RDB_LISTEN" --rdb-addr "$RDB_LISTEN"
--s3-bucket "$RDB_S3_BUCKET" --s3-prefix "$RDB_S3_PREFIX" --s3-region "$RDB_S3_REGION"
--s3-snapshot-interval-secs "$RDB_S3_SNAPSHOT_SECS" --s3-wal-flush-secs "$RDB_S3_WAL_FLUSH_SECS"
--s3-retain-snapshots "$RDB_S3_RETAIN")
[ -z "$RDB_S3_ENDPOINT" ] || args+=(--s3-endpoint "$RDB_S3_ENDPOINT")
[ "$RDB_S3_PATH_STYLE" != 1 ] || args+=(--s3-path-style)
[ "$RDB_S3_START_OFFLINE" != 1 ] || args+=(--s3-start-offline)
if [ -n "$RDB_TLS_CERT" ]; then
args+=(--pg-cert "$RDB_TLS_CERT" --pg-key "$RDB_TLS_KEY" --rdb-cert "$RDB_TLS_CERT" --rdb-key "$RDB_TLS_KEY")
fi
echo "Backing up to s3://$RDB_S3_BUCKET/$RDB_S3_PREFIX: a snapshot every $RDB_S3_SNAPSHOT_SECS s, the log every $RDB_S3_WAL_FLUSH_SECS s."
echo "PostgreSQL: postgresql://rasterized@$RDB_LISTEN:5432/postgres?sslmode=require"
echo "Check: psql … -c 'SHOW BACKUP STATUS'"
echo "Stop with Ctrl+C (the log is archived once more on the way out)."
echo
exec "$RDB_BIN" "${args[@]}"#Requires -Version 5.1
<#
.SYNOPSIS
RasterizedDB with continuous backups to S3 (or any S3-compatible store):
a full snapshot on a schedule, the write-ahead log archived every few
minutes, so the database can be restored to any point in between.
Runs in the foreground.
.EXAMPLE
$env:RASTERIZEDDB_PG_PASSWORD = 'use-a-long-secret'
$env:AWS_ACCESS_KEY_ID = '…'; $env:AWS_SECRET_ACCESS_KEY = '…'
.\setup.ps1 -Bucket my-backups -Prefix prod/main -Region eu-central-1
.EXAMPLE
.\setup.ps1 -Bucket backups -Endpoint http://minio.internal:9000 -PathStyle
#>
[CmdletBinding()]
param(
[string]$RdbBin = $(if ($env:RDB_BIN) { $env:RDB_BIN } else { 'rasterizeddb.exe' }),
[string]$Data = $(if ($env:RDB_DATA) { $env:RDB_DATA } else { '.\data' }),
[string]$Listen = $(if ($env:RDB_LISTEN) { $env:RDB_LISTEN } else { '127.0.0.1' }),
[string]$CertPath = $env:RDB_TLS_CERT,
[string]$KeyPath = $env:RDB_TLS_KEY,
[string]$Bucket = $env:RDB_S3_BUCKET,
# One database per prefix.
[string]$Prefix = $(if ($env:RDB_S3_PREFIX) { $env:RDB_S3_PREFIX } else { 'rasterizeddb/main' }),
[string]$Region = $(if ($env:RDB_S3_REGION) { $env:RDB_S3_REGION } elseif ($env:AWS_REGION) { $env:AWS_REGION } else { 'us-east-1' }),
# MinIO, R2, B2, Wasabi…; empty for AWS.
[string]$Endpoint = $env:RDB_S3_ENDPOINT,
# For MinIO and bucket names that are not DNS-safe.
[switch]$PathStyle = ($env:RDB_S3_PATH_STYLE -eq '1'),
[int]$SnapshotSeconds = $(if ($env:RDB_S3_SNAPSHOT_SECS) { [int]$env:RDB_S3_SNAPSHOT_SECS } else { 86400 }),
[int]$WalFlushSeconds = $(if ($env:RDB_S3_WAL_FLUSH_SECS) { [int]$env:RDB_S3_WAL_FLUSH_SECS } else { 300 }),
[int]$Retain = $(if ($env:RDB_S3_RETAIN) { [int]$env:RDB_S3_RETAIN } else { 7 }),
# Start even when the bucket does not answer.
[switch]$StartOffline = ($env:RDB_S3_START_OFFLINE -eq '1')
)
$ErrorActionPreference = 'Stop'
$cmd = Get-Command $RdbBin -ErrorAction SilentlyContinue
if (-not $cmd) { throw "'$RdbBin' not found; pass -RdbBin with the path of rasterizeddb.exe." }
if (-not $Bucket) { throw 'Pass -Bucket (or set $env:RDB_S3_BUCKET) to the bucket to back up into.' }
if (-not $env:RASTERIZEDDB_PG_PASSWORD) { throw 'Set $env:RASTERIZEDDB_PG_PASSWORD to the password for the role rasterized.' }
if (-not $env:AWS_ACCESS_KEY_ID -or -not $env:AWS_SECRET_ACCESS_KEY) { throw 'Set $env:AWS_ACCESS_KEY_ID and $env:AWS_SECRET_ACCESS_KEY for the bucket.' }
New-Item -ItemType Directory -Force -Path $Data | Out-Null
$Data = (Resolve-Path -LiteralPath $Data).Path
$serverArgs = @('--location', $Data, '--protocol', 'both', '--pg-addr', $Listen, '--rdb-addr', $Listen,
'--s3-bucket', $Bucket, '--s3-prefix', $Prefix, '--s3-region', $Region,
'--s3-snapshot-interval-secs', "$SnapshotSeconds", '--s3-wal-flush-secs', "$WalFlushSeconds",
'--s3-retain-snapshots', "$Retain")
if ($Endpoint) { $serverArgs += @('--s3-endpoint', $Endpoint) }
if ($PathStyle) { $serverArgs += '--s3-path-style' }
if ($StartOffline) { $serverArgs += '--s3-start-offline' }
if ($CertPath) {
$c = (Resolve-Path -LiteralPath $CertPath).Path
$k = (Resolve-Path -LiteralPath $KeyPath).Path
$serverArgs += @('--pg-cert', $c, '--pg-key', $k, '--rdb-cert', $c, '--rdb-key', $k)
}
Write-Host "Backing up to s3://$Bucket/${Prefix}: a snapshot every $SnapshotSeconds s, the log every $WalFlushSeconds s."
Write-Host "PostgreSQL: postgresql://rasterized@${Listen}:5432/postgres?sslmode=require"
Write-Host "Check: psql … -c 'SHOW BACKUP STATUS'"
Write-Host 'Stop with Ctrl+C (the log is archived once more on the way out).'
Write-Host ''
& $cmd.Source @serverArgs
exit $LASTEXITCODE