Thursday, June 29, 2023

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 - Receipt-AI'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

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

and then run bundle install and


bundle exec derailed bundle:mem

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
# gem "rack-mini-profiler"

More details: https://github.com/MiniProfiler/rack-mini-profiler

4. Caching

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


<%= render partial: 'hero', cached: true %>

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 RUBYGCHEAPGROWTHFACTOR=1.03

With these 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

Memory

ruby on rails

heroku

Memory Quota Exceeded

receipt ai

Related Articles

Start uploading Receipts using SMS.

Save 97% of your time with efficient receipt processing

Works with Xero and QuickBooks

Perfect for businesses, big and small

No extra app downloads. Works with tools you already have (Email and SMS)

Start texting receipts β†’
A working professional traveling at a client site smiles as he takes a photo of a receipt with his smartphone. He plans to upload the receipt using SMS and Receipt-AI, which is integrated with Xero or QuickBooks, while sitting in a cozy cafΓ© environment. Indicating the ease of using the app.

Receipt-AI with AI and SMS

What's new? Accounting Tips, Product News & Stories

2024 Receipt AI - Big Green Company Terms Privacy