More Ruby Scaling

Ruby is an amazingly productive language, and Rails is an awesome framework. However, you need to be aware of what you are getting into. There are lot’s of items that make life difficult for your web server. Some of the biggest culprits are has_one, has_many, etc. They are so powerful, but use them wrong and your database will be in trouble.
For example:

class Company < ActiveRecord::Base
has_many :people
# There is a name column in the db

class Person < ActiveRecord:Base
belongs_to :company

Now, assume you will be showing 50 people with their company names on a page. The view code is very simple:

<% @people.each do |p| %>
<%= p.first_name + “, ” %>
<% end %>

Forget about the formating, but this simple loop will result in 50 database calls to retrieve the company name. If your application does this a lot, you will need some caching, or your database will be in trouble.

It’s a good idea to watch your logs and attack those areas that are performing excessive database queries.






2 responses to “More Ruby Scaling”

  1. Josh Kieschnick Avatar

    Hey Dave,Another way of getting around all of the database hits would be to include the other tables in your joins.

    In your controller you could have something like @people = Person.find(:all, :include => :companies

    When using active record in your views, it won’t need to make the db call because rails will keep the join information in memory. Depending on how many records there are, you will probably see a significant increase in speed.

  2. admin Avatar

    I use that trick for other things, but I have 30,000+ companies in my database. The include trick is not efficient. I keep the companies in a cache.
    Mostly, my point is to be aware of all the magic that Ruby is doing. The easy stuff works great when you start off, but you will want to watch the database calls.

Leave a Reply

Your email address will not be published. Required fields are marked *