Friday, October 14, 2011

Simple nginx tuning for rails application on production server

Recently I was working on tuning my production environment for better performance. In production server mainly three things makes a difference to the web application,
  1. REE-GC Tuning
  2. Nginx Tuning
  3. Passenger Tuning

As I have already done REE-GC tuning in previous articles, so lets discuss on Nginx tuning. Passenger tuning will be get covered in subsequent articles.

In Nginx there are many ways to boost your application performance, but I would like to share few important tweaks.

To validate performance improvement, you can use page-speed or Yslow

Before doing these tweaks on my rails application, yslow and page-speed score was around 25-35/100. After doing these tweaks it increased to 90-96/100

To get 100/100 we have to write a good code-design not best code-design ;). In our application the performance dip is due to not using CSS sprite.


A. Enable Gzip :
Gzip helps to compress and decompress the data on-the-fly between browser and server. Nginx has HttpGzipModule for same.

Add following lines into to http block nginx.conf
gzip  on;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
gzip_vary on;
gzip_disable     "MSIE [1-6]\.";
#gzip_proxied any;
#gzip_buffers 128 128k;
#gzip_min_length  1100;
Depending on your need you can set the above commented directives.


B. Enable caching :
Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network.

Add following lines into to server block nginx.conf
   location ~* \.(ico|css|js|gif|jpe?g|png|swf)(\?[0-9]+)?$ {
         expires max;
         break;
   }

C. Minify JavaScript :
Compacting JavaScript code can save many bytes of data and speed up downloading, parsing, and execution time.
For this you can use any third party tools or gems like Jammit,asset_packager to minify your JavaScript files. Rails 3 has built in support.

Sample nginx.conf :
Apart from this you can use multiple assets server for static resources, which will be covered in subsequent articles.