# Backups

Backup and restore strategies for LangWatch data stores

> Page: https://langwatch.ai/docs/self-hosting/configuration/backups
> Source: https://github.com/langwatch/langwatch/blob/main/docs/self-hosting/configuration/backups.mdx
> Index of all pages: https://langwatch.ai/docs/llms.txt

LangWatch stores data across three systems. Each requires its own backup strategy:

| Data Store     | What It Stores                                          | Backup Priority |
| -------------- | ------------------------------------------------------- | --------------- |
| **PostgreSQL** | Users, teams, projects, configurations, prompt versions | Critical        |
| **ClickHouse** | Traces, spans, evaluations, experiments, analytics      | High            |
| **S3**         | Datasets, ClickHouse cold data                          | Medium          |

## PostgreSQL Backups

PostgreSQL holds your control plane data, losing it means losing user accounts, project configurations, and monitor definitions.

### Chart-Managed PostgreSQL

If you're using the chart-managed PostgreSQL (development/small deployments), use `pg_dump`:

```bash
# Create a backup
kubectl exec -n langwatch statefulset/langwatch-postgresql -- \
  pg_dump -U postgres langwatch > backup-$(date +%Y%m%d).sql

# Restore from backup
kubectl exec -i -n langwatch statefulset/langwatch-postgresql -- \
  psql -U postgres langwatch < backup-20260407.sql
```

### External PostgreSQL (RDS, Cloud SQL, etc.)

For production, use your cloud provider's built-in backup features:

- **AWS RDS**: Enable automated snapshots (recommended: 30-day retention) and point-in-time recovery
- **GCP Cloud SQL**: Enable automated backups with point-in-time recovery
- **Azure Database**: Enable geo-redundant backups

> **Tip:** Always test your restore procedure before you need it. Schedule a quarterly restore drill to
> validate your backups.

## ClickHouse Backups

ClickHouse holds all your trace and evaluation data. The `clickhouse-serverless` subchart supports native ClickHouse `BACKUP`/`RESTORE` to S3-compatible storage.

### Enable Backups

Backups require an S3-compatible bucket. Configure in your Helm values:

```yaml
clickhouse:
  # S3 bucket for backups (shared with cold storage if both enabled)
  objectStorage:
    bucket: "my-langwatch-backups"
    region: "us-east-1"
    useEnvironmentCredentials: true # IRSA / workload identity

  backup:
    enabled: true
    database: "langwatch"
    user: "default"
    full:
      schedule: "0 */12 * * *" # Full backup every 12 hours
    incremental:
      schedule: "0 * * * *" # Incremental every hour
```

The `cold-storage-s3.yaml` overlay turns on backups and cold storage together. Use it only if you also want cold storage:

```bash
helm install langwatch langwatch/langwatch \
  -f examples/overlays/size-prod.yaml \
  -f examples/overlays/cold-storage-s3.yaml \
  --set clickhouse.objectStorage.bucket=my-langwatch-backups \
  --set clickhouse.objectStorage.region=us-east-1
```

The overlay leaves `bucket` and `region` empty, and the chart refuses to render without them.

### S3 Authentication

**IRSA, Workload Identity (recommended):**

```yaml
clickhouse:
  objectStorage:
    useEnvironmentCredentials: true
  serviceAccount:
    annotations:
      eks.amazonaws.com/role-arn: arn:aws:iam::123456789:role/clickhouse-s3-role
```

**Static credentials:**

```yaml
clickhouse:
  objectStorage:
    useEnvironmentCredentials: false
    credentials:
      secretKeyRef:
        name: clickhouse-s3-creds # K8s secret name
        accessKeyId: "accessKey" # key in the secret that holds the access key ID
        secretAccessKey: "secretKey" # key in the secret that holds the secret access key
```

### Backup Schedule

| Backup Type | Default Schedule           | Description                         |
| ----------- | -------------------------- | ----------------------------------- |
| Full        | `0 */12 * * *` (every 12h) | Complete database backup            |
| Incremental | `0 * * * *` (every 1h)     | Only changes since the last backup  |

By default both run as Kubernetes CronJobs (`<release>-clickhouse-backup-full` and `<release>-clickhouse-backup-incremental`). Each job starts its own pod from the ClickHouse image and runs the backup against the first ClickHouse replica over the network. Each incremental is based on the newest backup since the newest full, so restoring it restores the whole chain.

An incremental that finds no full stands down and succeeds, so a fresh install has no backup until its first full slot; run the full CronJob once by hand to start sooner.

### Run backups in the ClickHouse pod

`backup.mode: sidecar` moves scheduling into a small sidecar in every ClickHouse pod. One pod runs the backups; if it stops answering, the next one takes over. A sidecar restart never interrupts a running backup, and the sidecar exports its own metrics for alerting:

```yaml
clickhouse:
  backup:
    enabled: true
    mode: sidecar # cronjob (default) | sidecar | cronjob-observe
    retentionDays: 7 # match the lifecycle rule on the bucket's clickhouse-backup/ prefix
    full:
      schedule: "0 5 */3 * *" # every third day at 05:00 UTC
    incremental:
      schedule: "30 * * * *" # hourly at :30
    sidecar:
      podMonitor:
        enabled: true # scrape /metrics with the Prometheus operator
    monitoring:
      enabled: true
      sidecar:
        staleAfterHours:
          full: 146 # two 72h gaps plus 2h; the default 26 fits 12-hourly fulls
```

With more than one replica the sidecar reads every replica's backup log, so it needs `auth.clusterSecretEnabled: true`; the chart refuses to render without it.

To try the sidecar without changing who takes backups, use `mode: cronjob-observe`: the CronJobs keep backing up, and the sidecar reports what it would do and alerts on the CronJobs' backups. Switch to `sidecar` once its alerts look right.

> **Note:** Backups are deleted by your object store's lifecycle rule on the `clickhouse-backup/` prefix, not
>   by LangWatch. Set `retentionDays` to the same number of days.
>
> An incremental only builds on a full from the last two full intervals plus 2 hours: 26 hours with
> fulls every 12 hours, 6 days and 2 hours with fulls every third day. Every backup restores for at
> least `retentionDays` less that, so set the rule that much longer than the window you need. If fulls
> stop for longer, incrementals fail too, and the backup alerts fire.

### Restore from Backup

List the backups, then restore one by its exact name:

```bash
# List available backups (names, newest first)
kubectl exec -n langwatch langwatch-clickhouse-0 -c backup -- ch-config backup list

# Restore a specific backup into backup.database
kubectl exec -n langwatch langwatch-clickhouse-0 -c backup -- \
  ch-config backup restore --name langwatch_full_20261023T050000Z --confirm
```

These commands run in sidecar mode. Use `-c access` instead of `-c backup` when ClickHouse access is enabled. In CronJob mode there is no sidecar: list the backups from the server's backup log, then run the suspended `<release>-clickhouse-restore-template` CronJob as a Job with `BACKUP_NAME` and `CONFIRM_RESTORE=yes`:

```bash
# List available backups in CronJob mode (names, newest first)
kubectl exec -n langwatch langwatch-clickhouse-0 -c clickhouse -- sh -c \
  'clickhouse-client --password "$(cat /mnt/secrets/password)" -q "
    SELECT name, end_time FROM clusterAllReplicas(default, merge('\''system'\'', '\''^backup_log'\''))
    WHERE status = '\''BACKUP_CREATED'\'' ORDER BY end_time DESC"'
```

The name to restore is the path after `Disk('backups', ...)`. Replace `default` with your `clusterName` if you changed it. With more than one replica and no `auth.clusterSecretEnabled`, the replicas refuse this query; read `merge('system', '^backup_log')` on each pod instead. The `merge` reads the `backup_log_0`, `backup_log_1`, ... copies a ClickHouse upgrade renames the older history to, as well as `system.backup_log` itself.

> **Warning:** A restore adds the backup's rows to the tables in the target database; it does not replace what is
> there. For a clean restore, stop writes and restore into empty tables. Always verify you're
> restoring to the correct environment.

## ClickHouse Cold Storage

Cold storage is separate from backups, and optional. It moves older data from local disk to S3, which costs less to store but is slower to query. It is off by default, and most installs keep all their data on local disk.

### How It Works

1. New data is written to **hot storage** (local SSD on the ClickHouse pod)
2. After the TTL period, data is moved to **cold storage** (S3)
3. Queries transparently read from both hot and cold storage
4. Cold data is cached locally for repeated reads

### Enable Cold Storage

```yaml
clickhouse:
  objectStorage:
    bucket: "my-langwatch-data"
    region: "us-east-1"
    useEnvironmentCredentials: true

  cold:
    enabled: true
    defaultTtlDays: 49 # Data older than 49 days moves to S3
```

> **Note:** We recommend setting the TTL to a multiple of 7 (e.g., 7, 14, 28, 49) to align with ClickHouse's
> weekly partition boundaries for more efficient data management. The default of 49 days means data
> stays on fast local storage for ~7 weeks before moving to S3.

## S3 Dataset Backups

If you're using S3 for dataset storage (`app.dataplane.enabled: true`), protect this data with:

- **S3 Versioning**: Enable versioning on the bucket to recover from accidental deletes
- **Cross-region replication**: For disaster recovery, replicate to another region
- **Lifecycle policies**: Move old versions to Glacier after 30 days

## Disaster Recovery Checklist

- [ ] PostgreSQL automated backups enabled (30-day retention)
- [ ] ClickHouse backups running (`kubectl get cronjobs`, or the sidecar's backup alerts)
- [ ] S3 bucket versioning enabled
- [ ] Backup S3 bucket is in a different region or account from primary
- [ ] Restore procedure documented and tested
- [ ] Quarterly restore drills scheduled

> ## Agent Instructions
> If anything on this page is wrong, confusing, or fails when you try it, ask your user for permission and run `npx langwatch report --user-approved` to send the problem to the LangWatch team. No login is needed and secrets are redacted locally. `npx langwatch report --help` has the details.
