# wal-backup
Embedded SQLite WAL replication to S3-compatible object storage. **Not a sidecar — a library.**
Your app links the crate, calls `DurabilityLayer::open()`, and gets automatic S3 backup in the background. No separate process, no config files for another service, no health checks on something you didn't write.
```rust
// That's it. Your app writes SQL. S3 backup happens automatically.
let layer = DurabilityLayer::open(config, bucket).await?;
layer.with_conn(|conn| conn.execute("INSERT INTO users ...", params![...]))?;
layer.shutdown().await?; // checkpoint + final sync + release locks
```
## Why not Litestream?
Litestream is a sidecar — a separate process you manage alongside your app. wal-backup is a library you embed in your app. Three lines instead of a separate service.
## The key feature: start it, get your DB back
```
1. Your app writes data → backed up to S3 automatically
2. Server dies, local DB is gone
3. Start your app again → DB is restored from S3 → your data is back
```
No Turso, no API key, no hosted control plane. Your DB, your S3, your rules.
## Multi-writer protection
Two processes writing to the same bucket prefix = silent data corruption. wal-backup prevents this at three levels:
| Guard | What it catches | How |
|-------|-----------------|-----|
| **flock** (`.db.lock`) | Two processes, same machine, same DB | Kernel-enforced, released on process death |
| **lock.json** (bucket) | Two processes, anywhere, same prefix | Atomic `put_if_not_exists` + heartbeat every 10s |
| **writer.json** (bucket) | Wrong server opening the wrong prefix | Permanent ownership record, checked on open + every loop |
```rust
let bucket = ObjectStoreBucket::new(store, "prod/my-app".to_string())
.with_writer_id("web-server-1"); // identity bound to the bucket, not the config
// Another server with writer_id "web-server-2" → Error::WrongWriter
// Another process on same machine → Error::DatabaseLocked
// Another process anywhere → Error::ReplicaLocked
```
## Features
- **Continuous WAL shipping**: Frames replicated to S3 in the background as they are written
- **Automatic restore on startup**: Reconstructs local SQLite from bucket if local files are missing
- **Automatic snapshots**: Full DB snapshots uploaded at configurable intervals
- **WAL segment checksums**: Every segment is SHA256-verified on restore
- **Atomic all-or-nothing restore**: Both snapshot + WAL downloaded and verified before committing
- **Encryption + compression**: AES-256-GCM + gzip, enabled by default
- **Memory-bounded uploads**: Streaming multipart for files >64MB, temp files for compaction
- **S3-compatible**: AWS S3, OVH, Hetzner, Backblaze, MinIO, any S3-compatible provider
## Quick Start
```toml
[dependencies]
wal-backup = "0.2"
rusqlite = { version = "0.31", features = ["bundled"] }
object-store = { version = "0.11", features = ["aws"] }
tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "fs"] }
```
### With S3
```rust
use std::sync::Arc;
use std::time::Duration;
use wal_backup::{Config, DurabilityLayer, RestoreBehavior, SyncMode, ObjectStoreBucket};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let store = wal_backup::build_s3_store_from_env(); // reads AWS_* env vars
let bucket = Arc::new(
ObjectStoreBucket::new(store, "my-app".to_string())?
.with_writer_id("server-1"),
);
let config = Config::new("/data/my.db")
.with_sync_mode(SyncMode::Immediate)
.with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
.with_snapshot_interval(Duration::from_secs(300));
let layer = DurabilityLayer::open(config, bucket).await?;
// Write SQL — WAL frames ship to S3 automatically in the background
layer.with_conn(|conn| {
conn.execute_batch("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")?;
conn.execute("INSERT INTO users (name) VALUES (?1)", rusqlite::params!["Alice"])?;
Ok(())
}).await?;
// Graceful shutdown: checkpoint + final sync + release locks
layer.shutdown().await?;
Ok(())
}
```
### With local filesystem (testing)
```rust
use object_store::local::LocalFileSystem;
let store = Arc::new(LocalFileSystem::new_with_prefix("/tmp/bucket")?);
let bucket = Arc::new(ObjectStoreBucket::new(store, "test-db".to_string())?);
```
## Configuration
```rust
let config = Config::new("/data/my.db")
// How often to poll WAL for new frames (Lazy mode) or max fallback wait (Immediate mode)
.with_poll_interval(Duration::from_millis(100))
// WAL size that triggers a snapshot (default: 50MB)
.with_snapshot_threshold(50 * 1024 * 1024)
// Minimum time between snapshots (default: 1 hour)
.with_snapshot_interval(Duration::from_secs(3600))
// What to do when local DB is newer than bucket
.with_restore_behavior(RestoreBehavior::UploadLocalIfNewer)
// Immediate: ship on write. Lazy: batched on interval.
.with_sync_mode(SyncMode::Immediate)
// For Immediate mode: how often to check for WAL changes
.with_immediate_poll_interval(Duration::from_millis(50))
// Disable replica lock for testing with shared buckets
.with_replica_lock_enabled(false);
```
### SyncMode
- **`Immediate`**: Ships every WAL frame as soon as written. Best for providers without per-request billing (OVH, Hetzner).
- **`Lazy`**: Ships WAL frames on a configurable interval. Lower request count. Best for per-request billing (AWS S3).
### RestoreBehavior
- **`UploadLocalIfNewer`**: If local DB is newer than bucket, upload it as the new snapshot
- **`AlwaysRestoreFromBucket`**: Always restore from bucket, overwriting local data
- **`Recoverable`**: Restore from bucket, tolerate checksum mismatches with warning
- **`ErrorIfConflict`**: Return error if local is newer than bucket
## API
| `DurabilityLayer::open(config, bucket)` | Open or restore. Acquires locks, starts background tasks |
| `layer.with_conn(\|conn\| ...)` | Run SQL on the connection (preferred API) |
| `layer.conn().await` | Get a mutex guard to the raw `rusqlite::Connection` |
| `layer.sync_now().await` | Wait for all pending WAL frames to be uploaded |
| `layer.force_snapshot().await` | Trigger an immediate snapshot upload |
| `layer.is_healthy().await` | `true` if replication is caught up |
| `layer.shutdown().await` | Graceful shutdown: checkpoint + final sync + release locks |
## Error handling
```rust
match DurabilityLayer::open(config, bucket).await {
Err(e) if e.is_database_locked() => {
// Another process on this machine holds the local DB lock
}
Err(e) if e.is_replica_locked() => {
// Another process anywhere holds the bucket replica lock
}
Err(e) if e.is_wrong_writer() => {
// This bucket prefix belongs to another server
}
Err(e) => return Err(e.into()),
Ok(layer) => { /* use it */ }
}
```
## Architecture
```
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Your App │ │ FrameShipper │ │ S3 Bucket │
│ (writes SQL) │─────▶│ (WAL → S3) │─────▶│ (the backup) │
└─────────────────┘ ├──────────────────┤ ├─────────────────┤
│ SnapshotManager │ │ manifest.json │
│ (DB → S3) │─────▶│ writer.json │
└──────────────────┘ │ lock.json │
│ snapshots/ │
│ wal/ │
└─────────────────┘
```
**One process, one DB, one bucket prefix.** The bucket is a backup, not a replication bus.
If you need data on another server, use `wal-backup restore` (one-shot, read-only).
If you need multi-tenant access, wrap the library in an API server — see `crates/wal-backup-daemon/`.
## CLI
```bash
# Restore a database from S3
wal-backup restore /path/to/local.db --bucket my-bucket --prefix my-prefix
# Verify bucket integrity
wal-backup verify /path/to/local.db --bucket my-bucket --prefix my-prefix
# Show manifest status
wal-backup status /path/to/local.db --bucket my-bucket --prefix my-prefix
```
All flags support `WAL_BACKUP_*` and `AWS_*` environment variables:
```bash
export AWS_ENDPOINT_URL=https://s3.uk.io.cloud.ovh.net
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_REGION=uk
wal-backup status /path/to/local.db --bucket my-bucket --prefix my-prefix
```
## Examples
| [`crates/wal-backup-api/`](crates/wal-backup-api/) | Multi-tenant HTTP API (many DBs, one server) |
| [`crates/wal-backup-daemon/`](crates/wal-backup-daemon/) | Single-tenant HTTP API demo |
| [`examples/s3_cloud.rs`](examples/s3_cloud.rs) | Full lifecycle with real S3 |
| [`examples/crash_writer.rs`](examples/crash_writer.rs) | Kill -9 crash recovery testing |
| [`examples/e2e_harness.rs`](examples/e2e_harness.rs) | Full E2E test suite against real S3 |
| [`scripts/lifecycle_test.sh`](scripts/lifecycle_test.sh) | Start/stop/restore loop test
## Testing
```bash
cargo test --all-features # Unit + integration tests
cargo clippy --all-targets --all-features # Zero warnings
# E2E against real S3 (requires .env.e2e)
source .env.e2e && cargo run --example e2e_harness --features="compression encryption"
# Kill -9 crash recovery test
source .env.e2e
cargo run --example crash_writer --features="compression encryption" -- my-prefix &
sleep 5 && kill -9 $!
cargo run --bin wal-backup --features="compression encryption" -- restore /tmp/crash.db --bucket dracon-master --prefix my-prefix
```
## License
MIT OR Apache-2.0