All posts

Fix MemoryError in Rails When Deploying

Resolve out-of-memory errors during Rails deployments from asset compilation, bundle install, and database migrations.

Rails Deployment Memory Errors

Rails deployments can fail with memory errors during bundle install, assets:precompile, or database migrations. Each has different solutions.

Asset Precompilation

Sprockets and Webpacker/Shakapacker can consume several GB during compilation:

# Increase Node heap for JavaScript compilation
export NODE_OPTIONS="--max-old-space-size=4096"
bundle exec rails assets:precompile

For Docker builds:

ENV NODE_OPTIONS="--max-old-space-size=4096"
ENV RAILS_ENV=production
ENV SECRET_KEY_BASE=dummy_for_precompile
RUN bundle exec rails assets:precompile

Bundle Install

Compiling native gems (nokogiri, grpc) uses lots of memory:

# Use pre-built gems when possible
RUN bundle config set --local without 'development test'
RUN bundle install --jobs 2  # Fewer parallel jobs = less memory

Reducing --jobs from the default (number of cores) to 2 significantly lowers peak memory.

Database Migrations

Large data migrations should use batching:

class BackfillUserNames < ActiveRecord::Migration[7.0]
  disable_ddl_transaction!

  def up
    User.in_batches(of: 1000) do |batch|
      batch.update_all("display_name = CONCAT(first_name, ' ', last_name)")
    end
  end
end

CI Configuration

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - run: bundle install --jobs 2
      - run: bundle exec rails assets:precompile
        env:
          NODE_OPTIONS: --max-old-space-size=4096

Bugsly captures deployment events and correlates build failures with error trends, so you know if a failed deployment caused downstream issues.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free