# Continuity and recovery

**Last updated:** 2026-11-27T14:16:11-03:00 (UTC-3)

[Security and trust](/docs/security/trust/) · [Data inventory](/docs/security/data-inventory/) · [Cryptography](/docs/security/cryptography/) · [Managed PostgreSQL](/docs/operate/managed-postgres/) · [Availability](/docs/operate/kubernetes-availability/)

The m7gtw continuity plan: what needs a backup, how to restore, and what is lost in each failure. Persistent gateway records live in PostgreSQL. Preserve the matching operator YAML, encryption/session keys and external Secret/file references separately; a database archive does not provision or copy those external resources.

## What goes into the backup

| Item | Where it lives | Without it |
|---|---|---|
| **PostgreSQL database** | The operator's database (`storage.database_url_env`) | You lose usage, configuration managed through the console, keys, evals, files and audit |
| **Provider key** (`GATEWAY_PROVIDER_ENCRYPTION_KEY`) | Secret, file or secret store | Provider, MCP and alert secrets and eval captures **do not come back**: they become unreadable, with no way to recover them |
| **Session key** (`GATEWAY_UI_SESSION_KEY`) | Secret, file or secret store | Sessions drop, and Responses and Conversations IDs and the semantic cache stop being valid. Nothing is permanently lost |
| **Configuration YAML** | The operator's repository or ConfigMap | The declarative baseline (the database stores only the overrides) |
| **Cache key** | Secret or managed secret | Only the exact cache, which rebuilds itself |

Redis and Memcached do not need a backup: they hold cache, which fills up again.

**The provider key goes together with the database backup**, but is stored somewhere else. A database backup without it restores the data, but not the secrets.

## How to back up

- **Managed PostgreSQL** (RDS, Cloud SQL, Azure): use the automatic backup with point-in-time recovery (PITR). The RPO is in minutes.
- **Self-hosted PostgreSQL:** a scheduled `pg_dump -Fc`, or continuous WAL archiving for PITR. With `pg_dump`, the RPO is the interval between runs.
- Test restores periodically, as below. A backup that has never been restored does not count as a backup.

## Explicit PostgreSQL transfer procedure

This procedure transfers the currently supported PostgreSQL database to another PostgreSQL endpoint. It uses existing PostgreSQL tools, not a gateway import/export API or an engine-conversion module. Selecting a new endpoint never moves existing data. Cross-engine transfer, online replication, managed failover and automatic provisioning are outside this profile.

### 1. Prepare and stop writers

Record the gateway revision, actual PostgreSQL and client-tool versions, database/cluster identities, extensions, encoding and collation. Use compatible tools and a reviewed, independent **empty** destination. Database object OIDs and cluster identifiers are expected to differ; application schema and records must match. Recreate/review roles, privileges and required extensions separately: a single-database dump is not a backup of cluster-global roles or tablespaces.

Preserve the provider encryption key and the operator YAML/Secret references. Keep session-signing keys when preserving existing signed identifiers is required. Store key material separately from the archive. Do not print a key, password, connection string, ciphertext or individual credential hash in a verification report.

Drain and stop **all source writers**, including gateway replicas and administrative jobs. Wait for completed operations' usage/receipt recording, not merely their HTTP response. Inventory pending/indeterminate receipts and held quota before copying. Do not infer a refund or replay from an interrupted operation. Quota settlement and receipt/event/valuation completion have separate commit boundaries. A consistent database dump alone does not prevent writes after its snapshot from being lost during cutover.

### 2. Export privately and verify the archive

Prepare private PostgreSQL service/pass files with restricted permissions. The following names are operator-created connection-service references, not passwords or literal DSNs. Choose a private output location and restrict its permissions before running the command:

```sh
umask 077
pg_dump --format=custom --file="$DUMP" --dbname='service=gateway-source'
shasum -a 256 "$DUMP" > "$DUMP.sha256"
```

Review warnings and record the exit status, archive size/checksum, source version and backup identity. Encrypt/protect the archive according to the operator's storage policy: it contains sensitive data even when provider credentials are encrypted. Accept only a trusted source/archive; restoration executes SQL from that source. Verify the recorded checksum before import. A mismatched or truncated archive is rejected before the restore command runs.

### 3. Restore into a new empty destination

Verify the destination database identity and absence of application objects before invoking restore. Refuse a nonempty destination; do not use `--clean`, drop the source, overwrite an existing database or silently continue after an error.

```sh
shasum -a 256 -c "$DUMP.sha256"
pg_restore --single-transaction --exit-on-error --no-owner --no-acl \
  --dbname='service=gateway-destination' "$DUMP"
```

This selected single-owner procedure omits ownership and grants intentionally; the operator must establish the reviewed destination privileges. Do not combine the single-transaction restore with parallel jobs. Treat a failed restore as a failed disposable destination and investigate before creating a fresh target. Do not assume that transaction rollback rewinds sequence effects in an existing database; the empty-target rule is mandatory.

### 4. Verify before starting the destination

Compare a private integrity manifest collected while source writers are stopped with the restored database **before its first gateway boot**:

- The full application table inventory, row counts and canonical ordered row fingerprints, not a selected count alone.
- Columns/defaults, constraints, indexes/functions and sequence definitions/current values.
- Migration IDs and original application timestamps, coherent control version/overrides/audit, identities and revocations/tombstones.
- Quota reservations/counters/captured rates, usage events/valuations, durable receipts and opaque encrypted references, including uncertain holds.

Compare logical data and definitions, not physical OIDs. Keep the manifest private; never publish credential-level hashes or raw records. Counts and checksums complement the functional checks below. If anything differs, stop: an endpoint change is not a data repair.

Validate the same YAML and start one destination replica with the matching encryption/session keys and external references. Before opening traffic, verify readiness, managed-key authority/revocation, control version and encrypted credential use without exposing the secret. A wrong operator encryption key must fail safely; it cannot recover the archived credential. Inspect uncertainty without replaying or releasing it. Startup and subsequent operations may legitimately update bookkeeping; after boot compare the selected business invariants and explicitly expected writes rather than claiming every row remains byte-identical forever.

### 5. Cut over and recover safely

Keep the source stopped while destination writers run. Record the cutover and the first destination write. Before releasing destination writes, rollback can stop the destination and return to the intact source after readiness/integrity checks. Do not run writers on both independent databases.

After a destination write, the old source is stale. To return, drain/stop the destination, make a **new complete dump of it**, restore into a **fresh empty return database**, repeat the full preboot manifest comparison and native read-only checks, then cut over. Preserve the destination-only charge/history in that return database. Do not point back to the stale original source or imply that changing a Secret reverses data or schema. Keep the known binary compatible with the stored migration history.

The selected current profile uses PostgreSQL **16.15, Linux ARM64**, and the pinned image documented in [Managed PostgreSQL](/docs/operate/managed-postgres/#current-standalone-recovery-profile). The current native procedure transferred **107 application tables and seven sequences at schema 96**, comparing all recorded table/schema/sequence manifests before boot. It exercised source→independent destination and a fresh post-write reverse restore, active/revoked key authority, control version/audit, encrypted credential use, exact known settlement and held uncertainty. A wrong encryption master failed before serving without changing restored data. Three controlled loopback sends covered the known source request, abandoned operation and new destination request; no paid/public provider was called. The reverse copy retained the destination-only charge and the held reservation without replay/refund, while the stale original source remained unchanged. This is a same-engine local procedure, not a managed-cloud/PITR, cross-engine, production throughput or RPO/RTO guarantee. The historical measurements below remain separate.

## Historical restore test

On 2026-10-27, on the local gateway database (14 MB, 104 tables, migration 84):

1. **Backup:** `pg_dump -Fc` in **0.17 s**, producing 366 KB.
2. **Restore** into a new database with `pg_restore --no-owner`: **0.74 s**.
3. **Check:** the counts of usage events (426), valuations (426), keys (22), captures (20), datasets (3) and audit records (9) matched the original.
4. **A second gateway on the copy, with the same provider key:** it started, listed the captures and opened the encrypted content.
5. **The same gateway with a different provider key:** it started and served the console, but the capture responded `encryption_unavailable` ("Capture cannot be decrypted"). It is an explicit error, without returning corrupted data. This confirms the key is part of the backup.

The test environment (second instance, restored database and dump) was deleted afterwards.

## Failure scenarios

| Failure | Effect | Recovery |
|---|---|---|
| A gateway replica goes down | The others serve traffic; streams in progress on it are lost | Automatic, by Kubernetes. See the [availability](/docs/operate/kubernetes-availability/) profile |
| PostgreSQL goes down | The inference path continues with the last configuration snapshot. Managed keys, RPM and budgets **fail closed** (503). With `durable_usage`, unrecorded usage is marked as indeterminate, never made up | Bring the database back; the durable receipts reconcile |
| Redis or Memcached goes down | The cache fails open, after authorization | No action: the cache comes back on its own |
| A provider goes down | Fallback to another target, if configured; circuit breaker | Automatic |
| Loss of the database | All state is lost | Restore the most recent backup with the **same provider key** |
| Loss of the provider key | Stored secrets and captures become unreadable | Re-enter the provider and MCP credentials in the console; old captures do not come back |
| Security incident | Ongoing misuse | [Incident response](/docs/security/incident-response/), with an emergency stop |

## Reference objectives

The operator sets and measures these objectives for the actual volume and backup policy; the small historical test is not a service guarantee:
- **RTO** is dominated by the database restore time (seconds for tens of MB) and by the rollout of the replicas;
- **RPO** is that of the chosen backup mechanism: minutes with PITR, the schedule interval with `pg_dump`.

## Limits

- The test used a small database. Large databases (months of usage) take longer: measure at your volume.
- Provider-key rotation uses the explicit [offline keyring procedure](/docs/security/keyring-rotation/); preserve the matching old/new keys and backup through retirement. A successful snapshot scan is not proof that another old writer cannot restart.
- Multi-region and cross-region failover are not implemented (roadmap).

## PostgreSQL tool references

- [PostgreSQL16 pg_dump](https://www.postgresql.org/docs/16/app-pgdump.html).
- [PostgreSQL16 pg_restore](https://www.postgresql.org/docs/16/app-pgrestore.html).
- [Persistence operation boundaries](/docs/operate/persistence-contracts/).
