# Database backups

Every Rask app's database is backed up the same way from the outside — `rask db backup`, `rask db restore`, a backup
before a deploy migrates — and each database does it with what it has:

| | SQLite | SQL Server | PostgreSQL |
|---|---|---|---|
| On demand | `rask db backup [--remote]`: a consistent copy of the file (Online Backup API / `VACUUM INTO`), pulled down | `rask db backup --remote`: a `COPY_ONLY` full backup, sent to the destination | not yet — the server's own tools |
| Continuous | [Litestream](https://rask.sh/docs/guides/sqlite/#continuous-backup-with-litestream) (`Rask:Litestream:ReplicaUrl`) + [snapshots](https://rask.sh/docs/guides/sqlite/) | `Rask:Backups`: a full backup a day, the log every 15 minutes, by the app's own schedule | not yet |
| Restore | `rask db restore <file> [--remote]` | `rask db restore --remote [--at <time>]`: restored beside the database, checked, swapped in; the replaced one kept | not yet |
| List | your files | `rask db backups --remote` | — |
| Verify | Litestream's [verification](https://rask.sh/docs/guides/sqlite/) | `rask db verify-backup --remote`, or weekly with `Rask:Backups:VerifyEvery` | — |
| Before a deploy migrates | — | a `COPY_ONLY` backup, then the migrations **rehearsed** on a throwaway copy | — |

The rest of this page is SQL Server's. SQLite's is in [the CLI's backup section](https://rask.sh/docs/guides/cli/#backup-and-restore) and
[SQLite in production](https://rask.sh/docs/guides/sqlite/).

## SQL Server

SQL Server Express has no SQL Server Agent, so nothing on the server schedules a backup — and a box should need no cron.
The app takes its own: once `Rask:Backups:Destination` is set, it backs the database up **whole** every day and **the log**
every 15 minutes between, each `WITH CHECKSUM` (every page checked as it is written), compressed by the server where its
edition can (Express and Web cannot, so Rask gzips the file instead), and sends each off the box. A box that is lost
costs at most a quarter of an hour.

```json
// appsettings.Production.json — or the same keys as environment variables (Rask__Backups__Destination, …)
{
  "Rask": {
    "Backups": {
      "Destination": "https://youraccount.blob.core.windows.net/backups/shop",
      "Sas": "sv=2023-11-03&ss=b&srt=co&sp=c&se=2036-01-01T00:00:00Z&sig=…",
      "Heartbeat": "https://hc-ping.com/your-check"
    }
  }
}
```

| Key | Default | What it is |
|---|---|---|
| `Destination` | — (nothing scheduled) | An Azure Blob container URL, with an optional folder (`…/backups/shop`), or a directory (a mounted disk) |
| `Sas` | — | The SAS the box writes with: **create permission only** (`sp=c`) |
| `ReadSas` | — | The SAS a restore, a listing or a verification reads with (`sp=rl`). Never kept by the running app: given for the one command |
| `Heartbeat` | — | A URL pinged after every scheduled run that left nothing unsent — a backup that stops is noticed by its silence |
| `FullEvery` | `1.00:00:00` | How often a whole backup is taken |
| `LogEvery` | `00:15:00` | How often the log is backed up between them — the most a lost box can cost |
| `Retention` | `30.00:00:00` | How long backups are kept: applied by Rask on a directory; on Azure Blob, by the storage account's lifecycle rule |
| `VerifyEvery` | — (off) | How often the newest backup is restored into a throwaway database and checked; needs `ReadSas` kept by the app |
| `Staging` | `/var/opt/mssql/backup` | Where the server writes a backup and the app picks it up — one directory mounted into both containers |
| `ServerStaging` | `Staging` | The same directory as the **server** sees it, when it is mounted elsewhere there |

`Rask:ConnectionStrings:Backups` is the login a restore, a verification and a rehearsal copy use: they create and drop
databases, so it needs `dbcreator`. It defaults to the app's own, which may back up (`db_owner`) but usually not restore.

### The box can add backups, never read, change or delete them

The SAS the app holds may only **create** blobs. Every write says `If-None-Match: *`, so even a credential that could
would never write over a backup — and one that can only create is refused nothing it needs, while a box that is broken
into cannot read your data back out of the backups, nor delete them. Make one for the container (Azure CLI):

```bash
az storage container generate-sas --account-name youraccount --name backups \
  --permissions c --expiry 2036-01-01 --https-only --auth-mode key -o tsv          # the box's: Rask__Backups__Sas
az storage container generate-sas --account-name youraccount --name backups \
  --permissions rl --expiry 2027-01-01 --https-only --auth-mode key -o tsv         # yours, at restore time only
```

**Retention is the storage account's**, since a create-only credential cannot delete: add a lifecycle rule that deletes
blobs in the container 30 days after they were created (Storage account → Data management → Lifecycle management, or
`az storage account management-policy create`). Each backup is a blob of its own, under `{database}/{yyyy}/{MM}/`, named
`{database}_{full|log|copy}_{yyyyMMddTHHmmssZ}[_{label}].{bak|trn}[.gz]`.

A backup that fails to go stays on the box, in the staging directory, and goes with the next run — of either kind,
oldest first — so a log backup missing from the destination never silently breaks the chain after it.

### The staging directory

`BACKUP DATABASE` writes to the **server's** disk, so the server and the app share one directory: the server writes the
backup, the app sends it. On a box where SQL Server runs in a container beside the app:

```bash
# once, on the box: the directory, owned by the server's user (10001) and the app's group (1654, the .NET images' app)
install -d -o 10001 -g 1654 -m 2770 /srv/mssql/shop/backup
docker run … -v /srv/mssql/shop/backup:/var/opt/mssql/backup mcr.microsoft.com/mssql/server:2025-latest
```

and the app mounts it at the same path through `.rask/deploy.json`:

```json
{ "volumes": ["/srv/mssql/shop/backup:/var/opt/mssql/backup"] }
```

The set-group-id bit (`2770`) makes every file the server writes there the app's group's, so the app can read and
delete what it sends; nothing else on the box can.

### Taking, listing, restoring, verifying

```bash
rask db backup --remote                                   # a COPY_ONLY full backup now, sent to the destination
RASK_BACKUP_READ_SAS='sv=…&sp=rl&sig=…' rask db backups --remote          # what the destination holds
RASK_BACKUP_READ_SAS='…' rask db restore --remote                         # the newest backup
RASK_BACKUP_READ_SAS='…' rask db restore --remote --at 2026-12-03T09:15:00Z   # to a moment, through the log
RASK_BACKUP_READ_SAS='…' rask db verify-backup --remote                   # restore the newest into a throwaway, check it, drop it
```

They run the app's own commands **inside its running container** (`docker exec`), with its own connection string and
settings — your machine needs no production secret. The read SAS reaches the container through an owner-only env file,
never a command line.

A **restore** never writes over the database. It plans from the backups' names (the newest whole backup at or before
the moment, then every log backup up to the one holding it), says the plan and asks, downloads them, restores them as a
new database beside the app's — `STOPAT` the moment, on the server's own clock — checks it, and only then swaps it in:
the app's connections are cut and come back to the restored database, and **the database it replaced is kept** as
`{database}_before_{stamp}` until you drop it (`dotnet App.dll rask db drop-copy <name>` in the container). A restored
database that fails its check is dropped and nothing is swapped.

The **check** — after a restore, and all of `verify-backup` — counts every table's rows exactly (`COUNT_BIG`), runs
`DBCC CHECKCONSTRAINTS` (a row that breaks a foreign key) and `DBCC CHECKDB` (a page that fails its check). With
`Rask:Backups:VerifyEvery = 7.00:00:00` and the read SAS kept by the app, the schedule does it weekly and logs the
report.

Locally, the same commands are the app's own: `dotnet run -- rask db backup`, `dotnet run -- rask db backups`, ….

### Before a deploy migrates: a backup and a rehearsal

When the new image brings migrations, `rask deploy` — while the running version still serves — first takes a
`COPY_ONLY` backup labelled `pre-deploy` (sent off the box like any other), then **rehearses** the migrations: the
running app restores a fresh `COPY_ONLY` copy of the database as `{database}_rehearsal_{stamp}` on the same server, the
new image's `rask db migrate` runs against that copy, and the copy is dropped either way. The database itself is
migrated only once the migrations passed on the copy; a backup or a rehearsal that fails stops the deploy with nothing
of the running version touched.

```
  Backed up demo to https://…/backups/demo/2026/12/demo_copy_20261203T091542Z_pre-deploy.bak.
Rehearsing 20261203000000_AddThings on a fresh copy of demo's database…
  Rehearsed on demo_rehearsal_20261203091544: the migrations apply. Migrating demo itself.
```

The rehearsal points the new image at the copy by rewriting the database in `Rask__ConnectionStrings__App` — so the
deploy must be given it with `--env`, as a CI deploy is; without it the deploy says it is not rehearsing. A rollback past
a migration that rewrote rows (`rask deploy rollback --accept-rewritten-data`) restores from the `pre-deploy` backup
first: `rask db restore --remote --at <the deploy's start>`.

## PostgreSQL

Not yet. Continuous protection on PostgreSQL is WAL archiving, and the archiver runs **in the server**
(`archive_command`), which Rask does not provision; until it does, back PostgreSQL up with the server's own tools
(`pg_dump`, or `wal-g`/`pgBackRest` configured on the server).
