DEV Community

Queenie Peng
Queenie Peng

Posted on • Updated on

How to reduce memory usage for your Rails app - R14 - Memory Quota Exceeded in Ruby (MRI)

If you have just started building your Rails app and discovered that your memory quota is reaching nearly 1 GB - that's not normal. Fortunately, I have the exact solution for you. I've successfully brought my Rails app -https://receipt-AI.com 's memory usage from 1 GB to 268 MB.

 

1. Lower your worker count

The default Puma worker pool size is 4, but you can reduce it if you are not using a lot of concurrent connections.

heroku config:set WEB_CONCURRENCY=1
Enter fullscreen mode Exit fullscreen mode

 

2. Remove unused gems and set some to require: false

It could be that the gems you used are not required for boot time. To determine how much memory your gems consume during boot time:

group :development do
    gem 'derailed'
end
Enter fullscreen mode Exit fullscreen mode

and then run bundle install and

bundle exec derailed bundle:mem
Enter fullscreen mode Exit fullscreen mode

Bear in mind that if any gems is set to require: false, make sure to add require to the file where it is used.

 

3. Use rack-mini-profiler to monitor your database queries.

Uncomment this gem in your Gemfile and run bundle install. This tool allows you to measure the speed of your HTML page. It's super straightforward.

  # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
  # gem "rack-mini-profiler"
Enter fullscreen mode Exit fullscreen mode

 

4. Caching

Rails has a built-in way to cache your view, as simple as:

<%= render partial: 'hero', cached: true %>
Enter fullscreen mode Exit fullscreen mode

You should only use caching on partials that are used frequently and whose output does not change frequently, such as your home page, which is also the most visited.

 

5. Garbage collector turning

I have read multiple sources that state the default value of RUBY_GC_HEAP_GROWTH_FACTOR in Ruby is 1.8. Some sources mention that it may vary depending on the Ruby version. Nevertheless, you can configure the value by running:

heroku config:set RUBY_GC_HEAP_GROWTH_FACTOR=1.03
Enter fullscreen mode Exit fullscreen mode

With this approach, your Rails app will be running super crisp and smooth without the need to upgrade the dyno.

 


 

Ruby memory use

https://devcenter.heroku.com/articles/ruby-memory-use

 

Garbage collection tuning

https://blog.appsignal.com/2021/11/17/practical-garbage-collection-tuning-in-ruby.html

Top comments (1)

Collapse
 
renanfranca profile image
Renan Franca

👏👏 Kudos to you for sharing such an insightful post, Queenie! 💡 This is a goldmine for developers struggling with memory usage in their Rails apps. 🛠️ Your strategies are clear, effective, and easy to implement. 🚀 Keep up the amazing work! 💎 You're making a real difference in the dev community! 🌐🤗