How to save 100m of RAM per mongrel (Part 2)

UPDATE I’ve added a patch to Rails Edge for this fix, which is much different than the patch below. See here

In a previous article, I called out the massive memory usage of the default rails resource behavior, and it seems others have as well. In an attempt to decrease the number of routes, I commented out the “formatted_*” routes, and manually entered them back by hand.

But after some internal discussion/testing with Warren, we realized that was sloppy and error prone. Instead, I hacked Routing segments to allow for an optional format segment, so that formatted routes and normal routes are shared. The one downside, from what I can tell so far, is you lose “formatted_*” named routes + url helpers for those routes, but passing format to a url_for still works

   person_path(:id => 1, :format => "json") =>  /people/1.json

In the below gist, you’ll see a OptionalFormatSegment, which sneakily gets around the ‘.’ regex separator, removes the formatted_* named routes added by default, and should be the same solution as the previous post, but without the need to manually put all the routes back in.

I’m still testing this approach, but am interested in what other folks think.

Note: This monkey-patch only works on Rails 2.2

4 Comments

  1. hosiawak says:

    Formatted routes are no longer added as separate route names (formattes_route_name). It’s in Edge Rails, see http://ryandaigle.com/articles/2008/11/27/what-s-new-in-edge-rails-no-more-formatted-routes

  2. Ingemar Edsborn says:

    If I get time I’m going to try it out on our application today. I’ll keep you posted.

  3. Very elegant && unobtrusive.

    Have you considered aliasing in the anonymous routes module for backwards compat ( formatted_ ) ?

  4. James Chan says:

    This is really awesome! Edge Rails recently added :except and :o nly options to Routing, which would also reduce memory usage. See http://ryandaigle.com/articles/2008/11/13/what-s-new-in-edge-rails-except-and-only-routing-options, which credits your great two parts articles.