The big list of Ruby on Rails performance tweaks
So you wrote an app and you think it’s slow. You might be ready to blame Rails or start Googling “why is Ruby dead?”; maybe you’ll think “oh, this is why Twitter stopped using Rails in 2008.”
Don’t worry, it’s not: the Toyota Camry from 2008 is much different than the 2021 Camry.
Contents
Database tweaks
Tune your RDBMS
Heroku doesn’t provide for this, but if you’re shipping your own code or using something like HatchBox (which you should be) make sure that your RDBMS is tuned for the hardware its using. The default config does not know anything about your hardware.
PGTune can help you with a low-effort config.
Check for N+1s
Bullet will get you where you need to be.s
Make sure your data is properly indexed
I cannot stress this enough. I have seen too many developers — of all different titles and backgrounds — not know enough about indexing to understand that yes, it does greatly impact performance.
lol_dba is a good start. PgHero is too.
Vacuum
Dead indexes can hurt you. PgHero can help you.
Stop querying all that data
Post.all
selects all the columns by default. You probably don’t need all the columns.
Skip ActiveModel unless you need it
ActiveModel
is slow for large datasets. By slow, I mean really slow. Skipping it can lead to incredible gains.
Use SQL where SQL can be used
Don’t be using group_by
when group
will do. Letting your RDBMS do the work is a great place to start optimizing your
app.
And on that note…
Serializing in the database, or at least not from ActiveModel
Caching
Cache frequently used objects
Memcached and Redis both provide an easy way to cache things. Rails does too.
Utilize HTTP caching
Rails can do this out of the box. Make sure you’re using it correctly.
Server and hardware
Tune your app server
This one’s easy.
Add some hardware
Rails is a memory-hungry thing.
Optimized libraries
Swapping out ActionController::Base
for a different stack
You probably don’t need everything ActionController::Base
gives you for every controller. Using Rails as an API?
Drop in ActionController::API
.
Using optimized JSON
OJ is a fast JSON parser and object marshaller written in C with Ruby extensions.