arrow_backward Back to blog

Built For Speed: Using Amazon CloudFront To Serve Assets

This is the second in a series of posts on improving your site’s performance with the help of the YSlow Firefox plugin. In the last Built for Speed post, we took a look at YSlow’s most important factor in page speed – the number of HTTP requests. We demonstrated using the AssetPackager plugin to help reduce both the number of HTTP requests and the size of your CSS and JavaScript files. The source for the Built for Speed application is available on Github.

This week, we’ll learn how to use a Content Delivery Network (CDN) to help users see our static content faster. Granted, this may be overkill for a lot of sites, but I think it’s worth the time to see how it’s done. There are a lot of CDNs out there, but I’ve decided to use Amazon’s CloudFront because it’s relatively cheap and easy to set up (not to mention it integrates seamlessly with S3). Before you get much further, you’ll want to set up an account with S3 and CloudFront.

First, let’s install the Paperclip plugin so we can upload an image to go with our post.

   script/plugin install git:// 

Next, we need to add the Paperclip fields to the Post model:

   script/generate migration AddPaperclipColumnsToPost  
   # in the newly-created migration   def self.up     add_column(:posts, :image_file_name, :string)     add_column(:posts, :image_content_type, :string)     add_column(:posts, :image_file_size, :integer)     add_column(:posts, :image_updated_at, :datetime)   end    def self.down     remove_column(:posts, :image_file_name)     remove_column(:posts, :image_content_type)     remove_column(:posts, :image_file_size)     remove_column(:posts, :image_updated_at)   end 

We also need to make the Paperclip declaration in the Post model:

   class Post < ActiveRecord::Base     has_attached_file :image, :styles => {:large => "500x500", :medium => "250x250", :thumb => "100x100"}   end 

And finally we make the updates to the views. First change the new and edit views, adding the file_field for the attachment and making sure the form is set to accept multipart data (see the source on Github if you have questions). Then update your show view to display the image:

   <%= image_tag @post.image.url(:large) %> 

Now let’s take a look at our application in Firefox. Remember, we’re running it in production mode to see the benefits of the AssetPackager plugin among other things. Create a new post with the image attachment of your choice.

One gotcha – if you are running your application using Passenger, you may see an error something like this when you try to create a Paperclip attachment:

   Image /tmp/passenger.621/var/stream.818.0 is not recognized by the 'identify' command. 

In order to avoid this, create a file in /config/initializers to tell Paperclip where to find ImageMagick. I installed ImageMagick using MacPorts, so my file looks like:

   Paperclip.options[:command_path] = "/opt/local/bin" 

Okay, now that we have a new post with an image, browse to the post detail page, open up the YSlow interface, click “Run Test” and take a look at the second grade, “Use a Content Delivery Network (CDN)”.

Posts: show
Uploaded with plasq’s Skitch!

Ugh, we got a “D”. Okay, let’s see how we can implement Amazon CloudFront to make that grade an “A”.

Let’s start by telling Paperclip to use S3 for our image storage. Go ahead and create a configuration file called amazon_s3.yml. Obviously, you’ll need to replace the values here with your own keys:

   # config/amazon_s3.yml   development:     access_key_id: 123...     secret_access_key: 123...   test:     access_key_id: abc...     secret_access_key: abc...   production:     access_key_id: 456...     secret_access_key: 456... 

Paperclip depends on the ‘right_aws’ gem for its S3 storage, so make sure you add that to your config.gem list in /config/environment.rb and install it with:

   rake gems:install 

Next, update the Post model so it will use the new S3 configuration:

   class Post < ActiveRecord::Base     has_attached_file :image,                      :styles => {:large => "500x500", :medium => "250x250", :thumb => "100x100"},                      :storage => 's3',                      :s3_credentials => YAML.load_file("#{RAILS_ROOT}/config/amazon_s3.yml")[RAILS_ENV],                      :bucket => "built-for-speed",                      :path => ":class/:id/:style.:extension"   end 

Now restart your application and create a new post with an image. When you get to the post detail page, check out the source and you should see that your image is being served from your S3 bucket. That’s great, but what we really want to do is serve the image from the CloudFront CDN. The easiest way to do this is to install the S3 Firefox Organizer plugin). Once you enter your credentials, you should see your newly-created ‘built-for-speed’ bucket. Right-click on the bucket name and click “Manage Distributions”, then optionally add a comment and click “Create Distribution” (we’ll skip the CNAME option for now).

S3 Firefox Organizer
Uploaded with plasq’s Skitch!

This will generate a new resource URL for you to use in your application so you can take advantage of CloudFront. Now we have to go back and tell our application to use this resource URL:

   # /config/initializers/cloudfront.rb   #    # Note that your CloudFront resource URL will be different   CLOUDFRONT_DISTRIBUTION = "" 
   # in /app/models/post.rb   def cloudfront_url( variant = nil )     image.url(variant).gsub( "", CLOUDFRONT_DISTRIBUTION )   end 
   # in /app/views/posts/show.html.erb   <%= image_tag @post.cloudfront_url(:large) %> 

Restart the application and go back to the post detail page. Inspect the source and you’ll see that your image is now being served from CloudFront.

Okay, I think that’s enough for today. In the next post, I’ll show you how to avoid CloudFront serving stale assets and how to make YSlow recognize that you are now using a CDN. Please leave any questions or comments below.



New Project Request