# How to back up a Rails SQLite database

Add the litebackup gem and set config.litebackup.acquire, so each Rails server acquires its databases before Active Record connects and drains them to your server when Puma exits.

## Configure the Railtie in production

### production.rb

```ruby
# config/environments/production.rb
config.litebackup.acquire = {
  "app/production.sqlite3" => "storage/production.sqlite3",
  "app/production_queue.sqlite3" => "storage/production_queue.sqlite3"
}
config.litebackup.drain_on_shutdown = true
# Acquire in bin/rails db:prepare too, which runs before the server, but not
# in assets:precompile while the image builds.
config.litebackup.enabled = ENV["SECRET_KEY_BASE_DUMMY"].nil?
```

### Gemfile

```ruby
gem "litebackup", "~> 1.20"
```

## Questions

### Does the app's code change?

No. Active Record keeps using the sqlite3 adapter and the same files. The Railtie only acquires them before Active Record connects and drains them at exit.

### Why set enabled in production?

The Railtie is off in Rake tasks by default, and Rails 8 runs bin/rails db:prepare before the server. Without it, db:prepare on a new machine creates an empty database, and the server's acquire then refuses that file because it differs from the backup.

### What about Solid Cache and Solid Cable?

They can start empty after a move, so the example leaves them out. Add their names and paths to acquire if you want them to follow the app.

### Do I still need litebackup run?

Not with Puma alone. In a container, litebackup run acquires before anything in the image starts and passes the platform's signals on, so it is the simplest entrypoint. The Railtie works the same under it.

## What each setting does

- **acquire**. Takes each database by name before Active Record connects, and downloads the newest version on a new machine.
- **drain_on_shutdown**. Syncs and releases the databases in an at_exit hook once Puma has stopped serving.
- **enabled**. Turns the Railtie on in Rake tasks too, so db:prepare runs against the acquired database.
- **preload_app!** Lets the Puma master acquire before it forks and drain after its workers stop.

![On boot the Litebackup Railtie in the Puma master acquires the production database before Active Record connects, Puma workers read and write it, and on exit the master's at_exit hook drains it to the Litebackup server, which keeps every version in your bucket](https://litebackup-cdn.com/media/75573fd35801af47-rails-1400.webp)

## Install your server and add the gem

[Install your Litebackup server](/install), then add the `litebackup` gem to your app. It needs Ruby 3.2 or later, and its Linux and macOS platform gems include the Litebackup client, which starts and joins your server the first time the app uses it.

```bash
# Add the gem to the Gemfile and install it.
bundle add litebackup
```

Load the Railtie in `config/application.rb`, after `Bundler.require`.

```ruby
require "litebackup/integrations/rails"
```

Set `LITEBACKUP_API_KEY` to a join token from **Machines → Add machine** and your server's address in the production environment, as you set `SECRET_KEY_BASE`.

## Give the production databases fixed paths

Rails 8.1 generates a production `config/database.yml` with each database's path commented out, and refuses to start until it has one. Set them to files under `storage/`, the directory your deploy keeps.

```yaml
production:
  primary:
    <<: *default
    database: storage/production.sqlite3
  queue:
    <<: *default
    database: storage/production_queue.sqlite3
    migrations_paths: db/queue_migrate
```

Keep the `cache` and `cable` entries the same way. The cache and Action Cable's messages can start empty after a move, so the example acquires only the primary database and Solid Queue's jobs.

## Acquire at boot and drain at exit

```ruby
# config/environments/production.rb
config.litebackup.acquire = {
  "app/production.sqlite3" => "storage/production.sqlite3",
  "app/production_queue.sqlite3" => "storage/production_queue.sqlite3"
}
config.litebackup.drain_on_shutdown = true
# Acquire in bin/rails db:prepare too, which runs before the server, but not
# in assets:precompile while the image builds.
config.litebackup.enabled = ENV["SECRET_KEY_BASE_DUMMY"].nil?
```

`acquire` takes each database in an initializer that runs before Active Record connects, waiting up to 5 minutes while another machine still holds it. On a new machine it downloads the newest version first. `drain_on_shutdown` installs an `at_exit` hook that disconnects Active Record, syncs the databases to your server, and releases them, so the next machine acquires them at once.

The Railtie stays off in Rake tasks unless `enabled` says otherwise. Rails 8's `bin/docker-entrypoint` runs `bin/rails db:prepare` before the server, and on a new machine that task would create an empty database before the server acquires the real one, which the acquire then refuses as a conflict. Setting `enabled` acquires during `db:prepare` as well, and `SECRET_KEY_BASE_DUMMY`, which the generated Dockerfile sets only for `assets:precompile`, keeps the image build from trying to join.

## Drain once from the Puma master

Only the process that booted the app drains. With Puma workers, preload the app, so the master acquires before it forks and drains after its workers have stopped.

```ruby
# config/puma.rb
workers ENV.fetch("WEB_CONCURRENCY", 2)
preload_app!
```

## Run it in a container

In a container, `litebackup run` can acquire before anything else in the image starts, including `db:prepare`. Add the pinned command to the final stage of the Dockerfile Rails generated and make it the entrypoint, with Rails' own entrypoint after `--`.

```dockerfile
ARG TARGETARCH
ARG LITEBACKUP_VERSION=1.20.0
ARG LITEBACKUP_SHA256
ADD --chmod=0755 --checksum=sha256:${LITEBACKUP_SHA256} \
    https://litebackup-cdn.com/litebackup/${LITEBACKUP_VERSION}/litebackup-linux-${TARGETARCH} \
    /usr/local/bin/litebackup
ENV XDG_STATE_HOME=/rails/storage/state
USER 1000:1000
COPY --chown=rails:rails --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}"
COPY --chown=rails:rails --from=build /rails /rails
ENTRYPOINT ["litebackup", "run", \
    "--acquire", "app/production.sqlite3=/rails/storage/production.sqlite3", \
    "--acquire", "app/production_queue.sqlite3=/rails/storage/production_queue.sqlite3", \
    "--", "/rails/bin/docker-entrypoint"]
EXPOSE 80
CMD ["./bin/thrust", "./bin/rails", "server"]
```

Under `litebackup run`, the Railtie's acquire finds the databases already held and its drain finds nothing left to release, so the same configuration works with and without the wrapper. Pass the checksum with `--build-arg LITEBACKUP_SHA256=...` from the [release metadata](https://litebackup.com/pkg/metadata), and keep `/rails/storage` on a volume.

## Test a shutdown the way the platform does it

To check the drain, this initializer records a row with the host name when the process that drains exits. It runs before the Railtie's drain, because Ruby runs `at_exit` hooks in reverse order and the Railtie's hook is installed first. Add a `Shutdown` model with a `host` column and a route that lists the rows.

```ruby
# config/initializers/shutdown_row.rb
# Record a row when the platform stops the app, in the process that drains.
if Rails.env.production? && defined?(Rails::Server)
  started_pid = Process.pid
  at_exit do
    Shutdown.create!(host: Socket.gethostname) if Process.pid == started_pid
  end
end
```

Build the image, start one container, stop it the way a platform would, and start a second container on an empty volume.

```bash
# Start the first container, then stop it with TERM.
docker run --detach --name rails-1 --env LITEBACKUP_API_KEY --env SECRET_KEY_BASE \
  --volume rails-1-storage:/rails/storage YOUR_IMAGE
docker stop --timeout 60 rails-1
```

```bash
# Start a second container on a new volume and read the shutdown rows.
docker run --detach --name rails-2 --env LITEBACKUP_API_KEY --env SECRET_KEY_BASE \
  --volume rails-2-storage:/rails/storage --publish 127.0.0.1:8080:80 YOUR_IMAGE
curl http://127.0.0.1:8080/
```

The second container downloads both databases when it acquires them and lists the row the first container wrote as it stopped. Running the image with `--entrypoint /rails/bin/docker-entrypoint` tests the Railtie alone under Puma, and gives the same result.

## Deploy it

The [Fly.io guide](/sqlite-app-fly-io) and the [DigitalOcean guide](/sqlite-app-digitalocean) cover the platform's side, and [SQLite on autoscaled machines](/sqlite-autoscaling) explains the lifecycle. For deploys and restores in general, see [SQLite in production](/sqlite-in-production). The [Ruby SDK guide](/sdk-sqlite-ruby) lists every Railtie setting, including `databases` for continuous backup of a database that never moves between machines.

## Install

[Install your Litebackup server](/install) on a Linux machine you control, then join your first machine with the [command line](/cli) or an [SDK](/sdk). The [deployment guides](/sqlite-deployment-guides) cover each platform. Keep a second, independent backup of data you cannot lose, so no single system holds the only copy.
