Using Amazon CloudFront with Paperclip
There was a recent blog post over at Engine Yard discussing ways you can optimize client-side behavior. One of the recommendations provides guidance when using Amazon S3 for storage. Recently, we’ve been experimenting with Amazon CloudFront, their Content Delivery Network (CDN) in-the-cloud offering. For serving static content like photos in medium to high volume scenarios, CloudFront seems to be a smart bet and the costs are ridiculously low compared to the historical licensing costs when using a CDN. You’ve got lower latency, geographical distribution, and behind-the-scenes, CloudFront uses S3 for persisting your source content, so you can use the same interfaces and tools to tap into it. Optionally, CloudFront can generate request log files and persist them to an S3 bucket.
Naturally, uploading photos in a Ruby on Rails application usually involves a robust gem/plugin such as Thoughtbot’s Paperclip. We found that it’s very easy to configure it to seamlessly upload to CloudFront.
Here’s a sample polymorphic photo model that uses Paperclip:
class Photo < ActiveRecord::Base has_attached_file :data, :styles => { :lrg => "300x300>", :thumb => "100x100>", :micro => "50x50>" }, :storage => :s3, :s3_credentials => YAML.load_file("#{RAILS_ROOT}/config/amazon_s3.yml"), :s3_host_alias => "djoo9p6eu3n0g.cloudfront.net", :bucket => "listing-photos", :url => ":s3_alias_url", :path => ":class/:id/:style/:filename" belongs_to :attachable, :polymorphic => true end
The relevant configuration keys include :bucket, :storage, :s3_credentials, :s3_host_alias, and :url. The best thing is that your helper methods, e.g. photo.data.url(:lrg), continue to work the same way. Paperclip abstracts the file storage mechanism so that your views don’t need to have this responsibility.
Getting Started
1. Signup with CloudFront at http://aws.amazon.com/cloudfront/
2. Once you’re in there, you can use the AWS Management Console to define and deploy your CloudFront distribution bucket.

3. Setup Paperclip to use CloudFront as described above.
You’re done!
About this entry
Posted: Wednesday, October 21st, 2009 at 10:44 pm
- Author:
- Phil Misiowiec
- Category:
- Solutions
- Tags:
- amazon cloudfront, amazon s3, paperclip, ruby on rails
- License:
- Creative Commons

2 Comments
Jump to comment form | comments rss | trackback uri