# Backups and recovery
Source: https://sovaria.in/docs/backups-and-recovery

What Sovaria backs up and for how long, backup health and downloads, comparing with today, and restoring tables or the whole database (into an environment, another project or production) to a backup or any second, with undo.

Recovering from a mistake usually doesn't need a backup: most changes can be undone one at a time. Use the smallest tool that fixes the problem.

| Problem | Use | Keeps later changes? |
|---|---|---|
| A bad migration or schema change | [Version history: see, undo and restore changes](https://sovaria.in/docs/version-history) — roll back that change | Yes |
| A policy that let too much through | Policy **History › Roll back** ([Policy language (SPL)](https://sovaria.in/docs/policy-language)) | Yes |
| A broken function deploy | Function **Versions › Roll back** ([Functions](https://sovaria.in/docs/functions-overview)) | Yes |
| Rows deleted or overwritten in a few tables with history | Read them as of before ([Table history (time travel)](https://sovaria.in/docs/table-history)) | Yes |
| Rows deleted or overwritten in a few tables (no history) | **Restore tables** from a backup or a moment ([below](#tables)) — copied in beside the live ones | Yes |
| You want to look at the old data first, or test a fix | **Restore into an environment** ([below](#into)) — production stays as it is | Yes |
| The whole database is wrong (a bad bulk update, a script gone wrong) | **Restore** a backup (below) — undo within 7 days | No — set aside, undo brings them back |
| The whole database is wrong and you know when it happened | **Restore to a moment** ([point-in-time recovery](#pitr), Pro and higher) | No — set aside, undo brings them back |

## Daily backups

Every project database gets a logical backup (`pg_dump`) once a day, encrypted at rest and copied off the server, listed under **Project Settings › Database › Backups**. A backup that fails is tried again the same day (after 15 minutes, then 30, 60 … up to 4 hours); the owner is e-mailed only when the last attempt of the day fails. Staging environments are the exception: they start from production's structure and hold test data, so they are not backed up daily. Take a backup on demand before anything you want to keep ([Environments, staging and deploying to production](https://sovaria.in/docs/environments-and-staging)). Each month we also restore a randomly chosen recent backup into a throwaway, network-less database to prove backups really restore (only table and error counts are recorded, never your data). How long backups are kept and how many you can take on demand:

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Days daily and manual database backups are kept | 7 days | 14 days | 30 days | 30 days | 30 days |
| On-demand database backups per month | 10 | 100 | 300 | 1,000 | 5,000 |
| On-demand database backups per hour | 2 | 6 | 12 | 24 | 60 |

**Backup health** (top of the Backups panel, `sov db backups health`, `GET …/databases/{project}/backups/health`) shows the last good backup, failed attempts since, and your **recovery point** (RPO): about a minute with point-in-time recovery, otherwise the age of the last daily backup.

A backup is also taken right before a project's database is deleted. Backups cover the Postgres database (tables, and documents, which are stored in it). Files in storage buckets are not in these backups — keep copies of files you can't recreate ([S3-compatible storage access](https://sovaria.in/docs/storage-s3) works with `rclone` and the AWS CLI).

## Download a backup

**Backups › Download** (every plan) gives you the backup as plain SQL, gzip-compressed. It is a copy of the whole database, so only organization owners, admins and developers can download it (team permission `database.backup.read`; viewers and billing members can't, and app users and API keys for apps never can). Load it anywhere with `psql`.

CLI:
```bash
sov db backups list
sov db backups download 412 -o backup.sql.gz      # streamed to the file
gunzip -c backup.sql.gz | psql "$DATABASE_URL"
```

JavaScript:
```ts
const blob = await sovaria.governance.downloadDatabaseBackup(orgId, projectId, 412)
```

Python:
```python
await client.governance_download_database_backup(org_id, project_id, 412, dest="backup.sql.gz")
```

## Compare a backup with now

Before restoring anything, see what changed. **Backups › Compare** lists every table, column, function, policy, index and trigger added, removed or changed since that backup (with a diff), and how many rows each table gained or lost. Two backups can be compared too. Nothing is written. A large database takes a while: the answer comes back when it is ready (the API answers `202` with a `compare_id` to poll after 20 seconds).

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Backup compares per hour | 5 | 20 | 40 | 60 | 120 |

JavaScript:
```ts
const diff = await sovaria.api.governance.compareDatabaseMoments({ fromMoment: '412', toMoment: 'now' })
diff.summary  // { objects_added: 1, objects_removed: 0, objects_changed: 2, tables_with_row_changes: 3 }
diff.tables   // [{ table: 'public.orders', rows_before: 18240, rows_after: 17002, change: 'changed' }, …]
```

CLI:
```bash
sov governance db-compare <org-id> <project-id> --from 412 --to now
```

## Restore single tables

When only some tables are damaged, bring just those back. **Backups › Restore to… › Single tables** (or a moment, under point-in-time recovery) copies each table from the backup or the moment into production as `restored_<table>_<time>`, next to the live table: columns and rows, owned by your project role. Nothing live changes; you merge what you need with SQL. Dedicated databases (Pro and higher); owners and admins; counts as a database rollback.

CLI:
```bash
sov db restore-tables public.orders public.invoices --backup 412
sov db restore-tables public.orders --to '2026-10-22T14:32:00Z'
```

SQL (merge):
```sql
INSERT INTO public.orders SELECT * FROM public.restored_orders_202610261200
ON CONFLICT (id) DO NOTHING;
DROP TABLE public.restored_orders_202610261200;
```

JavaScript:
```ts
await sovaria.api.governance.restoreDatabaseTables({ tables: ['public.orders'], backupId: 412 })
```

## Restore into an environment or another project

A backup or a moment can go into **an environment of the project** instead of replacing production: the environment's database is replaced, production is not touched. Use it to look at the data as it was, copy rows out, or test a fix against yesterday's data. It can also go into **another project of the organization** (its database is replaced like a normal restore: safety backup first, undo for 7 days). Moments are recovered beside production in a separate container, exactly as for a point-in-time restore.

CLI:
```bash
sov db restore --into-env <env-id> --backup 412
sov db restore --into-env <env-id> --to '2026-10-22 14:32 +05:30'
sov db restore --into-project <other-project-id> --to '1 hour ago'
```

JavaScript:
```ts
await sovaria.api.governance.restoreDatabaseInto({ envId, targetTime: '2026-10-22T14:32:00Z', confirm: true })
```

HTTP:
```bash
curl -X POST "https://api.sovaria.in/api/v1/governance/tenants/$ORG/databases/$PROJECT/restore-into" \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"env_id": "'$ENV'", "backup_id": 412, "confirm": true}'
```

## Restore the database to a backup

On a dedicated database (Pro and higher), **Backups › Restore…** puts the whole database back the way it was when that backup was taken. Org owners and admins can restore; each restore counts toward the plan's database rollbacks per month.

1. **A safety backup is taken** — Today's data is backed up first, so nothing is lost.
2. **The backup loads beside production** — Into a new database, as your project's own role, in one transaction. If anything fails to load, production is never touched and the restore is marked failed with the reason.
3. **The two are switched** — Open connections are closed and reconnect to the restored database a moment later. Grants for app users are applied again.
4. **Undo for 7 days** — The database as it was right before the restore is kept. **Restores › Undo** switches back (a safety backup is taken first); after 7 days it is removed. Only the latest restore can be undone — undo a newer one first.

CLI:
```bash
sov governance db-backups <org-id> <project-id>
sov governance db-restore <org-id> <project-id> 412        # asks first
sov governance db-restores <org-id> <project-id>
sov governance db-restore-undo <org-id> <project-id> 7
```

JavaScript:
```ts
await sovaria.api.governance.restoreDatabaseBackup({ backupId: 412, confirm: true })
// Configuration and data together: go back on the timeline and include the database
await sovaria.chrono.restore('2026-10-15T09:00:00Z', 'main', { includeDatabase: true })
```

- Everything in the database goes back: tables, rows, functions, policies, triggers, and documents (they are stored in it). Storage files are not part of database backups.
- App users who signed up after the backup keep their accounts (accounts live outside your database); rows your tables held for them are as of the backup.
- Version history's **Restore** can go back in configuration (policies, functions, settings, buckets) and data together: it offers the closest backup before the moment you pick.
- On a shared database (Free), download the backup and load what you need into a scratch database with `psql`, then copy the rows back.

## Point-in-time recovery

On a dedicated database (Pro and higher) you can put the whole database back to **any second** inside your plan's window — "restore to 14:32 yesterday", just before a bad script ran — not only to the nightly backup. It works from Postgres's write-ahead log (WAL): every change is archived as it happens, at most about a minute behind.

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Point-in-time recovery window | Never | 7 days | 14 days | 28 days | 35 days |
| Point-in-time recovery archive included (base backups + WAL) | 0 MB | 10 GB | 60 GB | 200 GB | 1 TB |
| Point-in-time restore checks (verify only) per hour | — | 3 | 6 | 10 | 20 |

The archive (base backups plus WAL) included in the plan is `db.pitr_storage_bytes`; above it, paid plans are billed for it as point-in-time recovery storage. If archiving keeps failing for several minutes the database's state turns to error and the owners are e-mailed.

(Diagram: How a point-in-time restore works — Production is only switched after the recovered copy came up and was checked.)

### Turn it on

New Pro-and-higher databases have it from the first write. A database created before then needs one restart (a few seconds) to start archiving: **Project Settings › Database › Backups › Point-in-time recovery › Turn on** restarts it when you click, never by itself. The panel shows the window you can restore — earliest and latest moment — and how much is archived. The window starts at the first base backup (taken when archiving starts, then daily) and grows to your plan's days.

### Restore to a moment

1. **Pick the moment** — A date and time just before the bad change (shown in your time zone and in UTC). **Check only** recovers a copy and reports its tables and rows without touching production, so you can try a moment first.
2. **The latest changes are archived** — Whatever was written up to now is archived first, so any moment up to the present can be restored.
3. **A copy is recovered beside production** — The newest base backup before the moment and only the WAL it needs (up to just past the moment) are replayed in a new, separate container up to exactly that moment. If anything fails, production is never touched and the restore is marked failed with the reason.
4. **Checked, then switched** — Every table of the copy is counted, a safety backup of today's data is taken, and the copy is switched in the same way as a backup restore (connections reconnect a moment later; app-user grants are applied again).
5. **Undo for 7 days** — The database as it was right before the restore is kept. **Restores › Undo** switches back.

CLI:
```bash
sov db pitr status                                   # window: earliest and latest moment
sov db restore --to '2026-10-22T14:32:00Z' --verify   # check only, changes nothing
sov db restore --to '2026-10-22 20:02 +05:30'         # asks first, then follows the restore
sov db restore --to '15 minutes ago' --yes
sov db pitr enable --restart                         # older databases: one restart
```

JavaScript:
```ts
const pitr = await sovaria.api.governance.getPitrStatus()
pitr.earliest_restore_time  // '2026-10-16T09:00:12+00:00'
const job = await sovaria.api.governance.restoreDatabaseToTime({ targetTime: '2026-10-22T14:32:00Z', confirm: true })
await sovaria.api.governance.getRestoreJob({ jobId: String(job.id) })  // status: running → done; phase; undo_until
```

Python:
```python
job = await client.api.governance.restore_database_to_time(target_time="2026-10-22T14:32:00Z", verify_only=True)
await client.api.governance.get_restore_job(job_id=str(job["id"]))  # status "verified", phase "checked: 12 tables, 48211 rows"
```

HTTP:
```bash
curl -X POST "https://api.sovaria.in/api/v1/governance/tenants/$ORG/databases/$PROJECT/restore" \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"target_time": "2026-10-22T14:32:00Z", "confirm": true}'
```

| Answer | Why |
|---|---|
| `400 CONFIRM_REQUIRED` | Send `confirm: true` (or `verify_only: true` to only check). |
| `403 PLAN_FEATURE_REQUIRED` | The plan has no point-in-time recovery (Free). Restore a daily backup instead. |
| `409 PITR_NOT_ENABLED` / `PITR_NOT_READY` | Archiving is off, or the first base backup hasn't finished yet. |
| `409 TARGET_OUT_OF_RANGE` | The moment is before the earliest restorable one (the message says which). |
| `409 RESTORE_RUNNING` | Another restore of this project is running (one at a time; a restore cut off by a server restart stops blocking within minutes). |
| `409 UNDO_NOT_LATEST` | Only the latest restore can be undone; undo the newer one first. |
| `409 UNDO_RUNNING` | This restore is already being undone (a second click); wait for the first undo to finish. |
| `403 PLAN_LIMIT_REACHED` | Too many on-demand backups, compares or checks in the hour (`db.manual_backups_hour`, `db.backup_compares_hour`, `db.pitr_verifies_hour`) or month. |

- Org owners and admins can restore; each real restore counts toward the plan's database rollbacks per month (a check doesn't).
- It covers the project's main database (tables, documents, functions, policies, extensions). Staging environments use backups. Storage files are not part of it.
- The archive is encrypted at rest with the same keys as backups (your own KMS key with bring-your-own-key) and kept off the database server.
- Sovariq can do it for you ("put the database back to before 14:35") — it states the exact moment, offers a check first and asks before restoring.
- Staff can extend an organization's window from the Control Center; every restore is in the audit log.

## Documents, files and settings

- **Documents** live in the project database, so daily backups include them.
- **Files**: deleting a file or bucket is immediate and permanent; there is no file versioning or trash.
- **Policies, functions and schema** keep every version — [Version history: see, undo and restore changes](https://sovaria.in/docs/version-history).
- **Deleted projects** can't be restored from the console. A last backup is taken before the database is deleted; contact support straight away if you deleted one by mistake.

## Plan for recovery

- Download a backup before risky manual changes (`sov db backups download`).
- Check **Backup health** after big changes; a failing status means no fresh backup.
- Run destructive SQL in a transaction, check the row counts, then commit.
- Keep important files in two places.
- Try changes in staging first ([Environments, staging and deploying to production](https://sovaria.in/docs/environments-and-staging)).
