skip to content

How do you use Active Storage's Mirror service to move a live Rails app's files from one storage service to another?

level: seniorimportance: nice to knowfreq 22%

answer

  1. primary plus mirrors in storage.yml
  2. reads and URLs come from the primary
  3. ActiveStorage::MirrorJob copies to mirrors
  4. backfill old blobs with mirror_later
  5. service_name on each blob row

basics

~20 s

Define a Mirror service whose primary is the current store and whose mirrors include the new one, make it the active service, backfill existing blobs with mirror_later, verify the copies, then switch to the new service.

solid answer

~40 s

A Mirror entry in `storage.yml` names a `primary` and a list of `mirrors`. Uploads go to the primary synchronously and are copied to the mirrors by `ActiveStorage::MirrorJob`; deletes go to all; `download`, `exist?` and `url` always use the primary. To migrate inspection photos from disk to S3: make the Mirror (`primary: local`, `mirrors: [inspections_s3]`) the configured service, point existing blobs at it (their `service_name` still names the old service), enqueue `blob.mirror_later` for each, verify every key exists in S3, then make S3 the primary or the sole service and update `service_name` accordingly. Mirroring is not atomic: a mirror upload can fail after the primary succeeded, so verification is a required step. Rails 8.1.4 fixed `MirrorService#mirror` dropping content type and disposition on copies.

code

ruby · 10 lines
ruby
# config/environments/production.rb (during the migration)
config.active_storage.service = :migrating

# one-off backfill, run in a console or a task
ActiveStorage::Blob.where(service_name: "local").update_all(service_name: "migrating")
ActiveStorage::Blob.where(service_name: "migrating").find_each(&:mirror_later)

# verification
s3 = ActiveStorage::Blob.services.fetch(:inspections_s3)
missing = ActiveStorage::Blob.where(service_name: "migrating").find_each.reject { |b| s3.exist?(b.key) }

go deeper

for a junior

Recall that a Mirror service writes to several services and reads from one primary.

for a middle

Explain which operations go to the primary, the mirrors or both, and how MirrorJob copies uploads after the primary succeeds.

for a senior

Run the migration safely: service_name on existing rows, the backfill through mirror_later, verification because mirroring is not atomic, and the role flip before cut-over.

for a principal

Plan a storage migration's cost, duration, rollback points and verification evidence, and decide whether Mirror or an out-of-band bulk copy fits the data volume.

## What the Mirror service is `Mirror` is a storage adapter built from other services in `config/storage.yml`: ```yaml local: service: Disk root: <%= Rails.root.join("storage") %> inspections_s3: service: S3 bucket: inspection-photos-<%= Rails.env %> region: eu-central-1 migrating: service: Mirror primary: local mirrors: [ inspections_s3 ] ``` `ActiveStorage::Service::MirrorService` behaves like this: | Operation | Goes to | |---|---| | `upload` | primary synchronously, then `mirror_later`, which enqueues `ActiveStorage::MirrorJob` for the mirrors | | `download`, `download_chunk`, `exist?`, `url`, direct-upload URLs | primary only | | `delete`, `delete_prefixed` | every service | | `mirror(key, checksum:)` | copies from the primary to each mirror that lacks the key | The guide is explicit that the service is **meant for temporary use during a migration** and that **mirroring is not atomic**: an upload can succeed on the primary and fail on a mirror. `MirrorJob` retries `ActiveStorage::IntegrityError` up to ten times and discards itself on `ActiveStorage::FileNotFoundError`. Direct uploads land on the primary, and attaching them enqueues the mirror copy. ## The service_name trap Every blob row records a `service_name`, and `Blob#service` resolves the adapter from it. Switching `config.active_storage.service` to `:migrating` affects only new blobs; the 40,000 existing photos still say `local`, so their deletes would skip S3 and nothing copies them. `MirrorJob` itself calls `ActiveStorage::Blob.service.mirror`, the **global** service, so the global service must be the Mirror while copies run. Two ways to handle it: - **Re-point existing rows**: `ActiveStorage::Blob.where(service_name: "local").update_all(service_name: "migrating")` during the migration window, and again to the final name at the end. - **Reuse one name**: keep a single service key, for example `primary_store`, and change its definition from Disk, to Mirror, to S3 across deploys, so rows never change. This needs the name planned from the start. ## A migration runbook 1. Add the new service and a Mirror entry; deploy with `config.active_storage.service = :migrating`. New uploads now land in both stores. 2. Re-point existing blob rows to the Mirror name (or rely on a shared name). 3. Backfill: `ActiveStorage::Blob.find_each(&:mirror_later)`. Each job copies the file from the primary to any mirror missing it, verifying the checksum, and passing the blob's content type, disposition and metadata (the 8.1.4 fix). 4. **Verify**: iterate blobs and check `exist?` on the new service for every key, including variant blobs, which are ordinary blobs with their own keys when variant tracking is on. 5. Flip roles: make S3 the `primary` and disk the mirror, so reads and URLs come from S3 while disk still receives writes as a fallback. 6. When confident, set `config.active_storage.service = :inspections_s3`, update `service_name` on every row to `inspections_s3` (or redefine the shared name), and remove the Mirror and Disk entries. ## Risks to plan for - **Queue volume**: one `MirrorJob` per blob; throttle the backfill and give the mirror queue its own workers. - **Cost and time**: everything is read from the primary once; on a large store this is hours of transfer. - **Writes during the copy** are covered by the Mirror's upload path, which is why the Mirror must be live before the backfill starts. - **Deletes** go to every service, so purges during the migration stay consistent. - **Rollback**: until the final step, the old store holds every file, so reverting the configuration is enough. Mirror gives no automatic failover: reads never fall back to a mirror when the primary fails, so on its own it does not replace replication in the object store.

  • During the Mirror phase the primary disk fails. Do reads fall back to S3?
    No. `MirrorService` delegates `download`, `exist?` and `url` to the primary only. Mirrors receive writes and deletes but are never read from, so recovery means making S3 the primary in configuration and redeploying, not an automatic failover.
  • Why must the configured global service be the Mirror while the backfill runs?
    `ActiveStorage::MirrorJob#perform` calls `ActiveStorage::Blob.service.try(:mirror, key, checksum:)`, using the global service rather than the blob's own `service_name`. If the global service is plain Disk or S3, it has no `mirror` method, the `try` returns nil, and the jobs complete without copying anything.

  • A Mirror service reads from a mirror when the primary is unavailable
  • Switching config.active_storage.service to the Mirror copies existing files automatically
  • Mirror uploads are atomic across all services
  • Changing config.active_storage.service updates service_name on existing blobs
  • The Mirror service is designed as a permanent multi-region setup

Assumes Rails 8.1.4, whose MirrorService#mirror forwards content type, disposition and custom metadata to mirrors; earlier 8.1 releases stored mirrored copies as application/octet-stream.