How to deploy assets on Amazon S3 and why deploying assets to Amazon S3 is important.

I was working on my project Kwaab and suddenly because of massive traffic (1500-2000 hits per second), the site starts slowing down. Page load time was increased to 10 seconds and sometimes even more than that. We tried to increase the server, still no significant improvements. Here are some things we have already done:

  • Landing Page is cached
  • 6GB of RAM and only 800MB is used
  • CPU utilization is less than 40%
  • User uploaded images are already coming from Amazon s3
  • Use cache control and expiry headers
  • Compress images using smusher
  • Compress js and CSS and lot more basic things we should do.

But still, the site is super damn slow, because the issue was loading time for assets. As my assets were coming from Linode itself and due to high traffic of the website, the client was waiting for assets for like 5 seconds just for the logo, etc., and that was slowing my site. I got a life saver i.e. asset_sync a gem to deploy your assets on Amazon bucket :)

How to implement deploying assets on amazon s3

  • Install the gem: If you want, you can put it within your :assets group in your Gemfile.
  gem "asset_sync"
  • Create a file asset_sync.yml in your config directory or check out the inbuilt generator i.e
  rails g asset_sync:install --use-yml --provider=AWS

which will generate a file in app/config/asset_sync.yml. Now I have this asset_sync.yml file, but you can configure it as per the docs of the gems.

    fog_provider: AWS
    aws_access_key_id: **********************
    aws_secret_access_key: **********************
    fog_directory: assetsstaging
    gzip_compression: 'true'
    existing_remote_files: keep

    fog_provider: AWS
    aws_access_key_id: **********************
    aws_secret_access_key: **********************
    fog_directory: assetsproduction
    gzip_compression: 'true'
    existing_remote_files: keep
  • Place these lines of code in your production/staging environment file:
    asset_sync_config_file = File.join(Rails.root, 'config', 'asset_sync.yml')
      ASSETCONFIG =[Rails.env]
      ASSETCONFIG.each do |k,v|
        ENV[k.upcase] ||= v
  • Down the above code. Place these lines of code which will tell rails to get the assets from here.
  config.action_controller.asset_host = "//#{ENV['FOG_DIRECTORY']}"
  • Also make sure your production/staging environment files have:
    • config.assets.digest is set to true.
    • config.assets.enabled is set to true.

That’s it. Now just deploy your Rails application and all the assets will be pushed to the respective bucket on Amazon :) and it solved my server issue to with a considerable amount. We made some more tweaks. I will post them soon.