…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:
- For lists: fix the n+1 problem with eager loading
- Avoid unnecessary count queries resulting from ”.count” and “.empty” in views, for example when checking for no results - use “== ” instead
- Don’t count the total records when your pager already does this: get the total_count from your pager instead.
- 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.
- Consider using local variables to populate select lists in your forms, rather than referencing the model class in the view.
- 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
- Separate site data from user data.
- Use a fast distributed cache service such as memcached.
- Employ an effective key-based cache expiration method.
- Use caching in your test environment, to avoid unpleasant surprises.
- Caching wont conceal your performance issues - fix them first.
Upgrade to Ruby 2.1 or higher to take advantage of better Garbage Collection.