RoR is famous for its convenient conventions and quick development. But as applications grow more complex and user demand increases performance can cause problems. There are plenty of strategies and best practices for optimizing the performance of Ruby on Rails application. Here in this blog post we will discuss some important tips which will improve your performance in RoR.
- Optimize Database Queries
A web app’s bottleneck is often database performance. Making the best use of where you spend your time with the database can yield a large performance improvement.
Tips:
Use Eager Loading: Use includes
to load the associations upfront, and thus avoid N+1 query problems. It decreases the number of database queries executed.
ruby
Instead of this:
@users = User.all
@users.each do |user|
puts user.posts.count
end
Do this:
@users = User.includes(:posts).all
Index Your Database: Index your database tables properly which means index them on the columns that are included in queries or joins. It helps speed up the lookups.
Avoid SELECT : Reduce the amount of data transferred and processed by specifying (in your queries) only the columns you need.
ruby
Instead of this:
User.select(‘*’)
Do this:
User.select(:id, :name)
- Leverage Caching
One of the best techniques to improve performance is caching. This allows it to reduce the frequency at which we compute or fetch data.
Tips:
Fragment Caching: Expensive to render parts of your views and cache them. That way you can serve cached content and don’t have to regenerate it on every request.
erb
Explanation:
This renders the explicit cache of the user_posts view passing it user data, whereas previously it was rendered as a raw string.
<%= render user.posts %>
<% end %>
Action Caching: Caching entire output of controller actions. This is good for static content that doesn’t get updated very often.
Use Redis or Memcached: Choose caching stores like Redis or Memcached to store data in memory and so we can access the data faster.
- Optimize Asset Pipeline
Rails asset pipeline provides a better way to compile and serve your JavaScript, CSS and images.
Explanation:
The way Rails serves up assets in your project is called Rails Asset Pipeline and this provides a better way to manage and serve your JavaScript, CSS and images. So basically that’s what it is, it’s a better way to manage and serve up assets. With faster load times, there is an opportunity to optimize asset delivery.
Tips:
Minify and Compress Assets: You can minify and compress your JavaScript and CSS files by using tools like Uglifier and Sass.
Precompile Assets: In production always precompile assets. This makes the load time faster because it won’t require Rails to compile assets on-the-fly.
bash
RAILS_ENV=production bin/rails assets:precompile
Use a Content Delivery Network (CDN): Reduce load times for users geographically distant from your server by serving your assets using a CDN.
- Optimize Middleware
Included in rails are several middleware components that are used to process the various aspects of request handling. By minimizing unnecessary, we could improve the performance.
Tips:
Remove Unused Middleware: Check your middleware stack and go through stripping out any unnecessary elements so you’re not unnecessarily going through hoops to do your request processing.
ruby
In your config/application.rb
config.middleware.delete ActionDispatch::DebugExceptions
Group Middleware: Think of grouping middleware which can be batched together such that less calls are made during request processing.
- Database Connection Pooling
The ordering of connections under heavy load is one of the most important tools for performance.
Tips:
Configure Connection Pool Size: Determine an appropriate pool size from your database configuration to conform with your application’s requirement and server capabilities.
yaml
In config/database.yml
production:
adapter: postgresql
encoding: unicode
pool: 5
database: my_app_production
Use Database Connection Pooling Libraries: One thing we didn’t mention in the video, and something we have implemented in earlier SO answers is using libraries like pgpool or connection_pool to manage database connections better.
- Long Running task jobs are known as Background Jobs.
Many long running tasks can be offloaded to background jobs to help keep your application as responsive as possible.
Tips:
Use Sidekiq or Resque: These libraries for background job processing let you run your tasks in queues that are processed asynchronously.
ruby
Enqueue a job
welcome_email(user).deliver_later UserMailer
Batch Processing: So, if you are dealing with bulk operations, then see if you can process jobs in bulk to reduce load on your server and make things run a little faster.
- They will monitor and Analyze Performance.
Monitoring your applications performance on a regular basis can help you identify bottlenecks and place of improvement.
Tips:
Use Performance Monitoring Tools: New tools like New Relic, Skylight, or Scout can tell you about response times, database queries and memory use.
Log Performance Metrics: Use logging to collect performance data and see how changes and work done over time improves.
- Upgrade to Ruby and Rails Version
Having your Ruby and Rails versions up to date means that you are getting the benefits of performance and security improvements.
Tips:
Check Compatibility: However, before you upgrade check for release notes and verify that your application is compatable to the new version.
Test Thoroughly:After upgrades test thoroughly to see if you didn’t introduce regressions, or performance issues.
Conclusion
Performance optimization of a Ruby on Rails application involves a mixture of measures from possible database query optimizations through effective caching, to proper asset management. Following are all the tips you should implement to improve your application’s responsiveness and speed greatly, resulting in a better experience for the users.
In short, performance optimization is an iterative process: you continuously monitor and adapt your strategies and as your Ruby on Rails application grows and changes, your app will continue to operate well. But, if you can embrace these practices, you’ll have a strong application that can ride the wave of competition in today’s environment.