# Litestream with Rails 8 and SQLite: a guide from production

Date: 2026-11-18
Tags: rails, sqlite, litestream, deployment
URL: https://joelgaff.com/blog/litestream-with-rails-8-and-sqlite-a-guide-from-production/

---

*Written to answer John Gorriceta ([@john_gorri](https://x.com/john_gorri)), who asked in the Ruby on Rails community on X on November 14, 2026: "Is anyone using Litestream with Rails 8 and SQLite? Looking for a good guide that I can follow to set it up."*

Everything here comes from two production Rails 8 apps running on one Hetzner server, in two different deployment shapes. Nothing is copied from another tutorial.

## TL;DR

1. **Pick your Litestream version before you read anything else.** Nearly every guide online describes 0.3; current is 0.5.18. A 0.3 config usually still *starts* on 0.5 and silently ignores the settings that moved, which is worse than a parse error.
2. **Litestream is not a backup.** It replicates a bad migration as faithfully as a real write. Run it alongside dated, gzipped snapshots; the snapshots are the ones that save you.
3. **Replicate the primary database only.** Solid Cache, Queue and Cable are disposable by design.
4. **Kamal:** run Litestream as an accessory in its own container, mounting the same Docker volume as the app, and pin the image tag.
5. **Hatchbox, Capistrano, anything with a `current` symlink:** run it as a deploy-user systemd service and point it at the *shared* path. Through the symlink it watches the old release forever and looks perfectly healthy doing it.
6. **Set retention deliberately.** On 0.5 the defaults are five minutes of `l0-retention` and 24h of snapshots, both easy to inherit without noticing.
7. **Two R2 tokens, one bucket each:** uploads and backups never share a credential.
8. **Drill the restore at install time.** A backup is only real once you have restored it.

## Read this part before you write any config

Almost every Litestream guide you will find online is written for 0.3, and the current release is 0.5.x (0.5.18, published 3 November 2026). The two config formats are different, and the dangerous part is that 0.5 will usually start on a 0.3 config anyway.

0.5 decodes the config leniently and then re-decodes it in strict mode purely so it can log *configuration contains unrecognized or duplicate key*. The source says this is deliberate, so that existing deployments with a stray key keep starting. Unknown keys are a warning, not an error. The long-form replica keys (`type`, `bucket`, `path`, `endpoint`, `region`, `force-path-style`) also all still exist in 0.5, and `url:` is shorthand rather than a replacement. So a 2023 blog post's config will quite likely load, replicate, and quietly do something other than what it says.

The three changes that genuinely bite:

1. **`replicas:` list becomes a single `replica:` map.** A one-entry 0.3 `replicas:` list still loads as a deprecated field. Two or more entries fail at startup with *multiple replicas on a single database are no longer supported*, and setting both `replica` and `replicas` is also an error. One remote is the source of truth now; if you want a second copy, replicate at the storage layer.
2. **Retention moved out of the replica and up to the top level.** 0.5 has `snapshot: {interval, retention}`, `l0-retention`, and a `retention: {enabled: true}` block (set `enabled: false` to hand expiry to bucket lifecycle rules instead). There is no replica-level retention in 0.5, so a `retention: 720h` copied from a 2023 post gives you one warning line in the log and no retention policy at all. This is the trap: a parse error you would notice.
3. **`age` encryption is gone.** 0.5 refuses to start with *age encryption is not currently supported, if you need encryption please revert back to Litestream v0.3.x*. If your 0.3 config is encrypted, you are staying on 0.3.

On the commands: `ltx` replaced `wal`, and `wal` survives as a deprecated alias that prints a warning. `generations` was *removed* with no replacement, because generations as a concept went away with the LTX format. The full 0.5 command set is `databases`, `replicate`, `start`, `stop`, `register`, `unregister`, `reset`, `restore`, `status`, `sync`, `list`, `info`, `version`, `ltx`.

One more 0.5 usage change worth knowing before you fight it: flags must come after the subcommand, so `litestream -config c.yml restore ...` is a usage error.

Decide which version you are installing first, then only read documentation for that version. This single issue will cost you more time than the rest of the setup combined.

## The thing that actually matters: Litestream is not a backup

This is the part most guides skip, and it is the reason to keep reading.

> Litestream replicates your mistakes exactly as faithfully as it replicates your real writes. A bad migration, a mistaken `DELETE FROM`, a model callback gone wrong: all of it streams to your replica within seconds, and now your replica is wrong too.

- **Litestream** protects against the server dying. Worst case data loss: seconds.
- **Nightly snapshots** protect against a bad migration, a mistaken DELETE, or corruption. Worst case data loss: 24 hours.

Run both. Litestream is for "the machine is gone." Dated, gzipped snapshots are for "we broke the data." They are not alternatives and neither one covers the other's case. Both of the apps described below run Litestream alongside a nightly `db:backup` rake task that writes dated snapshots to a separate bucket prefix, and the nightly snapshots are the ones that have actually saved me.

## Replicate the primary database only

A Rails 8 app generated today has four SQLite databases **in production**: primary, cache, queue and cable. Only replicate the primary one.

That split exists only in the production block. The generator puts a single `storage/development.sqlite3` in development and `storage/test.sqlite3` in test, and `--skip-solid` leaves you with one production database (`--skip-action-cable` drops the cable one), so do not go hunting for four files locally.

The Solid Cache, Solid Queue and Solid Cable databases are disposable by design. Replicating them costs money and write bandwidth, and buys nothing: if you lose the server you do not want yesterday's job queue back, you want a clean one. Here is the production `database.yml` for reference, with only `storage/production.sqlite3` going to R2:

```yaml
production:
  primary:
    <<: *default
    database: storage/production.sqlite3
  cache:
    <<: *default
    database: storage/production_cache.sqlite3
    migrations_paths: db/cache_migrate
  queue:
    <<: *default
    database: storage/production_queue.sqlite3
    migrations_paths: db/queue_migrate
  cable:
    <<: *default
    database: storage/production_cable.sqlite3
    migrations_paths: db/cable_migrate
```

## Shape one: Kamal, with Litestream as an accessory

This is the simpler of the two and it is what I would recommend if you are deploying with Kamal. Litestream runs as a Kamal accessory in its own container, mounting the same Docker volume the app writes its database into. No Ruby gem, no process inside the app container, no coupling to Puma's lifecycle.

In `config/deploy.yml`:

```yaml
volumes:
  - "myapp_storage:/rails/storage"

accessories:
  litestream:
    image: litestream/litestream:0.3
    host: <%= server %>
    cmd: replicate -config /etc/litestream.yml
    files:
      - config/litestream.yml:/etc/litestream.yml
    volumes:
      - "myapp_storage:/rails/storage"
    env:
      secret:
        - LITESTREAM_ACCESS_KEY_ID
        - LITESTREAM_SECRET_ACCESS_KEY
        - LITESTREAM_BUCKET
        - LITESTREAM_ENDPOINT
```

The `files:` key is the nice part. Kamal copies your local `config/litestream.yml` onto the server for you, so the config lives in your repo and travels with the deploy.

And `config/litestream.yml` (this one is 0.3 syntax, matching the pinned image):

```yaml
dbs:
  - path: /rails/storage/production.sqlite3
    replicas:
      - type: s3
        bucket: ${LITESTREAM_BUCKET}
        path: production.sqlite3
        endpoint: ${LITESTREAM_ENDPOINT}
        region: auto
        force-path-style: true
        retention: 720h
        sync-interval: 10s
```

Three things worth copying here:

1. **Pin the image tag.** `litestream/litestream:0.3`, not `latest`. Otherwise one day your accessory restarts onto 0.5 and your 0.3 config either refuses to start (two replicas, age encryption) or starts with its retention silently ignored, at the worst possible moment. Note that `0.3` is a floating minor tag: it resolves to 0.3.14 today and protects you from waking up on 0.5, not from a 0.3.x patch. `0.3.14` is the actual pin. Both `0.5` and `0.5.18` also ship `-scratch` variants if you want the smaller image.
2. **`force-path-style: true`** is harmless and it is what I run, but it is not required for Cloudflare R2. I had that wrong. Litestream documents it as required for Backblaze B2, MinIO, Filebase, Scaleway and Hetzner Object Storage; `forcePathStyle` defaults to false, and R2's auto-applied defaults are `sign-payload=true` and `concurrency=2`. The R2 fact worth having in its place: R2 tolerates only two or three concurrent uploads, does not support `aws-chunked` content encoding, and does not support request or response checksums. 0.5 recognises a `*.r2.cloudflarestorage.com` endpoint and sets `concurrency=2` with checksums off for you; on 0.3 you can hit upload failures there with no hint why.
3. **Everything is an environment variable**, so no credential or bucket name is ever committed.

### Secrets, Kamal's way

`.kamal/secrets` is committed to the repo and contains only references, never values:

```sh
RAILS_MASTER_KEY=$RAILS_MASTER_KEY
LITESTREAM_ACCESS_KEY_ID=$LITESTREAM_ACCESS_KEY_ID
LITESTREAM_SECRET_ACCESS_KEY=$LITESTREAM_SECRET_ACCESS_KEY
LITESTREAM_BUCKET=$LITESTREAM_BUCKET
LITESTREAM_ENDPOINT=$LITESTREAM_ENDPOINT
```

The values live in a gitignored `.env` that `bin/kamal` loads. I fill that file once per machine from my password manager with a small `bin/secrets-pull` script, so the password manager is the source of truth but nothing has to run at deploy time. A new machine never copies `.env` from another machine, it pulls its own.

I also have a Minitest test asserting that `.kamal/secrets` contains no `$(...)` command substitution, no password-manager calls, and that `.env` is gitignored. That sounds excessive until the first time someone pastes a real key into a committed file.

## Shape two: Hatchbox, with Litestream as a user systemd service

If you are on Hatchbox, Capistrano, or anything else that deploys with a `current` symlink, this is your shape. Litestream runs on the host, not inside the app, so a deploy or a Puma restart never interrupts replication.

This is where the one genuinely dangerous trap lives.

### The symlink trap

> Hatchbox repoints `current` at a new release directory on every deploy. If you point Litestream at the database through that symlink, it resolves the path once at startup and then goes on watching the old release's file forever, while your app writes to the new one. Replication appears healthy. The metrics look fine. The data is frozen at your last deploy, and you will not find out until you try to restore.

Always point Litestream at the shared path. Confirm it before you install:

```bash
readlink -f /home/deploy/myapp/current/storage/production.sqlite3
# use the shared/... path it prints, not the current/... path
```

Then the 0.5.x config:

```yaml
snapshot:
  interval: 24h
  retention: 168h

l0-retention: 24h

dbs:
  - path: /home/deploy/myapp/shared/storage/production.sqlite3
    replica:
      url: s3://backups/myapp-litestream?endpoint=https://ACCOUNT_ID.r2.cloudflarestorage.com&region=auto
```

`l0-retention: 24h` is worth setting deliberately. The default is 5 minutes (swept every 15s by `l0-retention-check-interval`), and what that buys you is five minutes of *transaction-level precision*, not five minutes of history. Behind L0 the compaction levels default to L1 30s, L2 5m, L3 1h, so you keep coarser restore points until snapshot retention expires. Still worth overriding: when you need a point-in-time restore you want fine granularity around the moment things went wrong, and a day of it costs almost nothing on a database of this size. Note that `snapshot.retention` defaults to 24h too, so the 168h above is a deliberate seven-fold increase rather than a default. (Zero is not an option: `l0-retention: 0` is rejected at startup.)

Note the separate bucket prefix (`myapp-litestream`). The nightly snapshots live under their own prefix in the same bucket, and the snapshot pruning job deletes old objects under its prefix. Keep them apart or one will eat the other.

### Installing it as a user service

Running as the `deploy` user with lingering enabled means it survives reboots and needs no root at all:

- Binary at `~/.local/bin/litestream` (the static build; 0.5.17 is the version I installed, 0.5.18 is current).
- Config at `~/.config/litestream/litestream.yml`.
- Keys at `~/.config/litestream/litestream.env`, chmod 600, written directly on the server. Litestream cannot read Rails encrypted credentials, so the keys have to exist in plain form somewhere; a 600 file owned by the deploy user is the smallest reasonable exposure.
- Unit at `~/.config/systemd/user/litestream.service`, with `EnvironmentFile` pointing at that env file.
- `loginctl enable-linger deploy` so it starts at boot without a session.

Day to day: `systemctl --user status litestream` and `journalctl --user -u litestream`.

## Use two R2 tokens, scoped to one bucket each

If you are already on Cloudflare R2 for Active Storage, do not reuse that token for backups. Two jobs, two tokens:

- **Uploads token:** the photos bucket only. Used by Active Storage.
- **Backups token:** the backups bucket only, scoped to this app's prefix. Used by Litestream and the nightly snapshots.

The uploads token cannot touch your backups and the backups token cannot touch user files. R2's endpoint is `https://<account_id>.r2.cloudflarestorage.com` and the region is always `auto`.

## The step nobody does: drill the restore

> A backup is only real once you have restored it. Do this at install time and again after anything changes.

```bash
set -a; . ~/.config/litestream/litestream.env; set +a
litestream restore -config ~/.config/litestream/litestream.yml \
  -o /tmp/restore-test.sqlite3 \
  /home/deploy/myapp/shared/storage/production.sqlite3
sqlite3 /tmp/restore-test.sqlite3 'select count(*) from users;'
rm /tmp/restore-test.sqlite3
```

Restore to a scratch path, query a table you know the size of, compare, delete. Two minutes. If this fails you have learned it on a Tuesday afternoon instead of during an outage.

Three flags that make the drill better, all 0.5: `restore` refuses to write over an existing non-empty file unless you pass `-force`, which is the real reason the scratch path matters; `-integrity-check quick|full` checks the restored file before you trust it; and `-dry-run` tells you whether a point-in-time target is reachable at all. On 0.5 you can only restore to the boundaries of the LTX files still in the replica, so `litestream ltx -level all` plus `restore -dry-run -timestamp` is how you confirm a target before you need it. `-txid` is there too if you know the transaction.

## The payoff: moving the whole app to another machine

This is what the setup buys you, and it is genuinely the moment it stops feeling like paranoia. On the Kamal side I keep a `bin/restore-db` script that pulls the database out of R2 straight into a fresh Docker volume on a new server. The full migration is four commands:

```bash
bin/kamal app stop && bin/kamal accessory stop litestream   # one writer at a time
export MYAPP_SERVER=<new machine> MYAPP_SSH_USER=<user>
bin/restore-db                                              # R2 to the new machine's volume
bin/kamal setup                                             # proxy, web, litestream
```

What `bin/restore-db` does over SSH, in order:

1. Copies `config/litestream.yml` to the new server.
2. Creates the Docker volume if it does not exist.
3. Deletes any existing database file plus its `-wal`, `-shm` and `.tmp-` siblings. `litestream restore` refuses to write over an existing non-empty file unless you pass `-force`, and a stale WAL next to a fresh restore is its own kind of trouble.
4. Runs `litestream restore` in a throwaway container mounting that volume, with `-if-replica-exists` so a fresh install is not an error.
5. `chown -R 1000:1000` on the storage directory, because the Rails container does not run as root and will not be able to write otherwise.

> Stop the old app and the old Litestream before you restore. Two writers against one replica is the one way to genuinely corrupt this setup.

## Things I would tell you over coffee

- **Do not put Litestream inside the app container.** Deploys restart that container, and you want replication running during a deploy more than at any other time.
- **`sync-interval: 10s` is what I run, but it is not the default.** Litestream's default is 1s. Ten seconds is me relaxing it tenfold on purpose: the write amplification on a small app is negligible either way, and this is the knob that sets the hard ceiling on your data-loss window, so pick the number rather than inherit it.
- **Set retention explicitly, in the right block.** 720h (30 days) under the replica on 0.3; 168h (7 days) under the top-level `snapshot:` block on 0.5, where the default is only 24h. On 0.5 a replica-level retention is ignored, so know which block your number belongs in, and set it rather than inheriting a default you have not read.
- **Test your deploy config.** I render `config/deploy.yml` through ERB in a Minitest test and assert that the Litestream accessory mounts the same volume as the app. That is exactly the kind of thing that silently drifts and is invisible until a restore fails.
- **Write down the install date and the version in your README.** When you come back in eight months, "installed 2026-09-01, Litestream 0.5.17, restore drill passed" is worth more than any amount of cleverness.

If you would rather not read all of it: this page is self-contained, so pointing your coding agent at the URL and asking it to set Litestream up for your app works fine. Happy to answer questions on any of this. The two shapes above are both running in production right now on a single Hetzner box, serving Rails 8 on SQLite with Solid Queue, Solid Cache and Solid Cable.
