Speeding up Ruby on Rails

August 19, 2014


…with less sql queries

A Rails application will make a large number of sql queries per page unless steps are taken to mitigate this. This is bad because it degrades the performance of your app, affects your ability to scale, and will cost you money.

Install the New Relic gem to see the sql queries made when loading a page in your app.

Here is what we changed to reduce the number of sql queries per page:

  1. For lists: fix the n+1 problem with eager loading
  2. Avoid unnecessary count queries resulting from  ”.count” and “.empty” in views, for example when checking for no results - use “== []” instead
  3. Don’t count the total records when your pager already does this: get the total_count from your pager instead.
  4. Avoid unnecessary repeated data calls by using local variables in partial views to consolidate your data needs, and get the model data in one place in your controller layer, not in your views.
  5. Consider using local variables to populate select lists in your forms, rather than referencing the model class in the view.
  6. Avoid multiple sql queries when displaying aggregated data in lists - create a model method that returns a hash from a single sql query. Use “group”, “count” and “.pluck” to retrieve just the data you need.

…with appropriate database indexes

Periodically review your database schema column indexes, ensuring that columns used in joins and where clauses have an index. Remove any indexes, ( columns and even tables ) that are not used.

…with appropriate use of caching

  1. Separate site data from user data.
  2. Use a fast distributed cache service such as memcached.
  3. Employ an effective key-based cache expiration method.
  4. Use caching in your test environment, to avoid unpleasant surprises.
  5. Caching wont conceal your performance issues - fix them first.

…with upgrades

Upgrade to Ruby 2.1 or higher to take advantage of better Garbage Collection.

© 2018 Keith P | Follow on Twitter | Git